问:
Access Invocations reference using Roslyn
I want to create a Visual Studio Extension(VSIX) using Roslyn. This extension should find all invocations, then looks for their definitions to analyse attributes defined on them. The definition of the method can be any where in the solution.

My first class is like this:

```<code>namespace MainProject
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(BusinessProject.Calc.AddNumbers(5, 8));
        }
    }
}
</code>```

My second class is something like the following:

```<code>namespace BusinessProject
{
    public class Calc
    {
        [CustomAttr("Do something")]
        public static long AddNumbers(int a, int b)
        {
            return a + b;
        }
    }
}
</code>```

In above sample, in class Program, I have an invocation of AddNumbers method. I want to 1) analyse the code, 2) find this invocation, 3) get all attributes of the reference method in class Calc, 4) process attributes parameters, 5) and then make a warning/error if needed.
I can analyse current class to find all invocations by RegisterCodeBlockAction, But what I can't do is accessing the entire solution to find definition of the invocation and after that, accessing attributes of the reference.

How can I access the entire solution in RegiserCodeBlockAction?

答:
You're calling the wrong method.

You actually want your analyzer to run on every method invocation, not every code block.

Therefore, you should call RegisterSyntaxNodeAction, and pass SyntaxKind.InvocationExpression.

It will then call you with an InvocationExpressionSyntax which has all the information you need (mostly in the Semantic Model).

Body:
I want to create a Visual Studio Extension(VSIX) using Roslyn. This extension should find all invocations, then looks for their definitions to analyse attributes defined on them. The definition of the method can be any where in the solution.

My first class is like this:

namespace MainProject
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(BusinessProject.Calc.AddNumbers(5, 8));
        }
    }
}

My second class is something like the following:

namespace BusinessProject
{
    public class Calc
    {
        [CustomAttr("Do something")]
        public static long AddNumbers(int a, int b)
        {
            return a + b;
        }
    }
}

In above sample, in class Program, I have an invocation of AddNumbers method. I want to 1) analyse the code, 2) find this invocation, 3) get all attributes of the reference method in class Calc, 4) process attributes parameters, 5) and then make a warning/error if needed.
I can analyse current class to find all invocations by RegisterCodeBlockAction, But what I can't do is accessing the entire solution to find definition of the invocation and after that, accessing attributes of the reference.

How can I access the entire solution in RegiserCodeBlockAction?


来源: stackexchange

问:
Qt5: filtering out the horizontal component from wheel events
I am trying to filter out any horizontal wheel/touchpad scrolling in a widget (ProjectTreeView) that is based on a QTreeView. The idea is to let the vertical movement pass through, supporting horizontal scrolling only via the scrollbar.

I've tried to implement this via a ProjectTreeView::wheelEvent() event handler (below), but that function somehow has the opposite effect. Am I overlooking something (too) obvious or doing something wrong altogether?

```<code>void ProjectTreeView::wheelEvent(QWheelEvent *e)
{
    if ((e->pixelDelta().x() != 0 || e->angleDelta().x() !=0)
#ifdef Q_OS_MACOS
        // allow horizontal scrolling controlled by a physical mouse wheel
        && e->source() != Qt::MouseEventNotSynthesized
#endif
    ){
        QPoint pixelDelta(e->pixelDelta()), angleDelta(e->angleDelta());
        // disable horizontal wheel scrolling
        pixelDelta.setX(0);
        angleDelta.setX(0);
        // discard the original event
        e->accept();
        QWheelEvent filtered(e->posF(), e->globalPosF(), pixelDelta, angleDelta,
            e->delta(), e->orientation(), e->buttons(),
            e->modifiers(), e->phase(), e->source(), e->inverted());
        QCoreApplication::sendEvent(this, &filtered);
    } else {
        QTreeView::wheelEvent(e);
    }
}
</code>```

When I try to filter via ProjectTreeView::event(QEvent*) I observe that
1) I hardly receive any wheel events at all, at least not when I'm trying to scroll (some come in when I release the touchpad)
2) the events that do come in don't have the required delta information (both components are 0).

This reminds me of remarks I've seen about the Qt4 implementation about how the events are actually treated by a different widget.

thanks!

答:
In the end, this works:

```<code>void ProjectTreeView::wheelEvent(QWheelEvent *e)
{
    if ((e->pixelDelta().x() !=0 || e->angleDelta().x()!= 0
        || e->orientation() == Qt::Orientation::Horizontal)
#ifdef Q_OS_MACOS
        // Cocoa: allow horizontal scrolling controlled by a physical mouse wheel
        && (!isCocoa || e->source() != Qt::MouseEventNotSynthesized)
#endif
    ){
        QPoint pixelDelta(e->pixelDelta()), angleDelta(e->angleDelta());
        pixelDelta.setX(0);
        angleDelta.setX(0);
        // discard the original event
        e->ignore();
        if (!pixelDelta.isNull() || !angleDelta.isNull()) {
            QWheelEvent filtered(e->posF(), e->globalPosF(), pixelDelta, angleDelta,
                e->delta(), Qt::Orientation::Vertical, e->buttons(),
                e->modifiers(), e->phase(), Qt::MouseEventSynthesizedByApplication, e->inverted());
            QCoreApplication::sendEvent(this, &filtered);
        }
    }
    QTreeView::wheelEvent(e);
}
</code>```

The key was realising that some events only had the orientation set to horizontal but no non-zero delta information.

The isCocoa member is to detect when I'm running my tweaked XCB QPA plugin (= using Qt under XQuartz).

ContentLicense: CC BY-SA 3.0

Body:
I am trying to filter out any horizontal wheel/touchpad scrolling in a widget (ProjectTreeView) that is based on a QTreeView. The idea is to let the vertical movement pass through, supporting horizontal scrolling only via the scrollbar.

I've tried to implement this via a ProjectTreeView::wheelEvent() event handler (below), but that function somehow has the opposite effect. Am I overlooking something (too) obvious or doing something wrong altogether?

void ProjectTreeView::wheelEvent(QWheelEvent *e)
{
    if ((e->pixelDelta().x() != 0 || e->angleDelta().x() !=0)
#ifdef Q_OS_MACOS
        // allow horizontal scrolling controlled by a physical mouse wheel
        && e->source() != Qt::MouseEventNotSynthesized
#endif
    ){
        QPoint pixelDelta(e->pixelDelta()), angleDelta(e->angleDelta());
        // disable horizontal wheel scrolling
        pixelDelta.setX(0);
        angleDelta.setX(0);
        // discard the original event
        e->accept();
        QWheelEvent filtered(e->posF(), e->globalPosF(), pixelDelta, angleDelta,
            e->delta(), e->orientation(), e->buttons(),
            e->modifiers(), e->phase(), e->source(), e->inverted());
        QCoreApplication::sendEvent(this, &filtered);
    } else {
        QTreeView::wheelEvent(e);
    }
}

When I try to filter via ProjectTreeView::event(QEvent*) I observe that
1) I hardly receive any wheel events at all, at least not when I'm trying to scroll (some come in when I release the touchpad)
2) the events that do come in don't have the required delta information (both components are 0).

This reminds me of remarks I've seen about the Qt4 implementation about how the events are actually treated by a different widget.

thanks!

Body:
In the end, this works:

void ProjectTreeView::wheelEvent(QWheelEvent *e)
{
    if ((e->pixelDelta().x() !=0 || e->angleDelta().x()!= 0
        || e->orientation() == Qt::Orientation::Horizontal)
#ifdef Q_OS_MACOS
        // Cocoa: allow horizontal scrolling controlled by a physical mouse wheel
        && (!isCocoa || e->source() != Qt::MouseEventNotSynthesized)
#endif
    ){
        QPoint pixelDelta(e->pixelDelta()), angleDelta(e->angleDelta());
        pixelDelta.setX(0);
        angleDelta.setX(0);
        // discard the original event
        e->ignore();
        if (!pixelDelta.isNull() || !angleDelta.isNull()) {
            QWheelEvent filtered(e->posF(), e->globalPosF(), pixelDelta, angleDelta,
                e->delta(), Qt::Orientation::Vertical, e->buttons(),
                e->modifiers(), e->phase(), Qt::MouseEventSynthesizedByApplication, e->inverted());
            QCoreApplication::sendEvent(this, &filtered);
        }
    }
    QTreeView::wheelEvent(e);
}

The key was realising that some events only had the orientation set to horizontal but no non-zero delta information.

The isCocoa member is to detect when I'm running my tweaked XCB QPA plugin (= using Qt under XQuartz).


问:
Performance of using same observable in multiple places in template with async pipe
In my component template I am calling async pipe for same Observable in 2 places.

Shall I subscribe to it and use returned array in my template or using async pipe for same Observable in multiple places of template has no negative effect to performence?

答:
I had better luck with .shareReplay from 'rxjs/add/operator/shareReplay' which is very new (https://github.com/ReactiveX/rxjs/pull/2443)

I also had luck with .publishReplay.refCount(1) (Angular 2 + rxjs: async pipe with .share() operator)

I'm honestly not sure about the difference between the two strategies.  The comments in the PR for shareReplay suggest that there might be more risk for memory leaks of Subscriptions if not implemented correctly, so I might go with the .publishReplay.refCount(1) for now.


问:
Regex exclude word from matches
Does anyone know what am I doing wrong?
I have this sentence:

```<code>hi [user=1234]John Jack[/user] take me home
</code>```

and I need regex which select only John Jack

My regex:

```<code>(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))
</code>```

I want exclude [user=1234] and [/user]

This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack

Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

答:
Full decoding:

```<code>public class RegExpPattern_002 {

   public static void main( String[] args ) {
      final String text =
         "hi [user=1234]John Jack[/user] take me home."
         + " [user=12] Jonno Ha [/user]"
         + " where you are [differentTag] hm? [/differentTag]."
         + " Peter Im here with [user=1]Danny Di [/user]";
      final Pattern p = Pattern.compile(
         "([^\\[]*)\\[(\\w+)(=([^\\]]+))?\\]([^\\[]*)\\[/(\\w+)\\]" );
      final Matcher m = p.matcher( text );
      while( m.find()) {
         final String preText   = m.group( 1 );
         final String attrOpen  = m.group( 2 );
         final String value     = m.group( 4 );
         final String content   = m.group( 5 );
         final String attrClose = m.group( 6 );
         assert attrClose.equals( attrOpen );
         System.err.printf(
            "pre = '%s', attr = '%s', value = '%s', content = '%s'\n",
            preText, attrOpen, value, content );
         System.err.println("-----------------------------");
      }
   }
}
</code>```

Execution log:

```<code>pre = 'hi ', attr = 'user', value = '1234', content = 'John Jack'
-----------------------------
pre = ' take me home. ', attr = 'user', value = '12', content = ' Jonno Ha '
-----------------------------
pre = ' where you are ', attr = 'differentTag', value = 'null', content = ' hm? '
-----------------------------
pre = '. Peter Im here with ', attr = 'user', value = '1', content = 'Danny Di '
-----------------------------
</code>```

Title: Regex exclude word from matches

Body:
Does anyone know what am I doing wrong?
I have this sentence:

hi [user=1234]John Jack[/user] take me home

and I need regex which select only John Jack

My regex:

(\[user=\d\d\d\d](.+?)\[\/user\])(?!(\[user=\d\d\d\d\])|(\[\/user\]))

I want exclude [user=1234] and [/user]

This (\[user=\d\d\d\d](.+?)\[\/user\]) selects [user=1234]John Jack[/user] but I want only John Jack

Full example:

hi [user=1234]John Jack[/user] take me home. [user=12] Jonno Ha
  [\user] where you are [differentTag] hm?  [/differentTag]. Peter Im
  here with [user=1]Danny Di [\user]

Body:
Full decoding:

public class RegExpPattern_002 {

   public static void main( String[] args ) {
      final String text =
         "hi [user=1234]John Jack[/user] take me home."
         + " [user=12] Jonno Ha [/user]"
         + " where you are [differentTag] hm? [/differentTag]."
         + " Peter Im here with [user=1]Danny Di [/user]";
      final Pattern p = Pattern.compile(
         "([^\\[]*)\\[(\\w+)(=([^\\]]+))?\\]([^\\[]*)\\[/(\\w+)\\]" );
      final Matcher m = p.matcher( text );
      while( m.find()) {
         final String preText   = m.group( 1 );
         final String attrOpen  = m.group( 2 );
         final String value     = m.group( 4 );
         final String content   = m.group( 5 );
         final String attrClose = m.group( 6 );
         assert attrClose.equals( attrOpen );
         System.err.printf(
            "pre = '%s', attr = '%s', value = '%s', content = '%s'\n",
            preText, attrOpen, value, content );
         System.err.println("-----------------------------");
      }
   }
}

Execution log:

pre = 'hi ', attr = 'user', value = '1234', content = 'John Jack'
-----------------------------
pre = ' take me home. ', attr = 'user', value = '12', content = ' Jonno Ha '
-----------------------------
pre = ' where you are ', attr = 'differentTag', value = 'null', content = ' hm? '
-----------------------------
pre = '. Peter Im here with ', attr = 'user', value = '1', content = 'Danny Di '
-----------------------------


问:
How can I get the source code of a Python function?
Suppose I have a Python function as defined below:

```<code>def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a
</code>```

I can get the name of the function using foo.func_name. How can I programmatically get its source code, as I typed above?

答:
You can use inspect module to get full source code for that. You have to use getsource() method for that from the inspect module. For example:

```<code>import inspect

def get_my_code():
    x = "abcd"
    return x

print(inspect.getsource(get_my_code))
</code>```

You can check it out more options on the below link.
retrieve your python code

OwnerDisplayName: david

Body:
Suppose I have a Python function as defined below:

def foo(arg1,arg2):
    #do something with args
    a = arg1 + arg2
    return a

I can get the name of the function using foo.func_name. How can I programmatically get its source code, as I typed above?

Body:
You can use inspect module to get full source code for that. You have to use getsource() method for that from the inspect module. For example:

import inspect

def get_my_code():
    x = "abcd"
    return x

print(inspect.getsource(get_my_code))

You can check it out more options on the below link.
retrieve your python code


问:
inaccessible due to 'internal' protection level
I am implementing the ScrollableGraphView library in my code (https://github.com/philackm/ScrollableGraphView) and experiencing the following problem:

To confirm to ScrollableGraphViewDataSource, when i add

```<code>func value(forPlot plot: Plot, atIndex pointIndex: Int) -> Double
</code>```

to my code, Xcode gives the following error at "plot.identifier" :

```<code>'identifier' is inaccessible due to 'internal' protection level.
</code>```

Can anyone help what is going on?

```<code>import UIKit

import ScrollableGraphView

class ViewController: UIViewController, ScrollableGraphViewDataSource {

// Class members and init...

var linePlotData: [Double] = [1, 2, 3, 4, 5]// data for line plot
var barPlotData: [Double] =  [1, 2, 3, 4, 5]// data for bar plot
var xAxisLabels: [String] =  ["Jan", "Feb", "Mar", "Apr", "May"]// the labels along the x axis

var numberOfPointsInGraph = 5

override func viewDidLoad() {
    super.viewDidLoad()

    let graph = ScrollableGraphView(frame: self.view.frame, dataSource: self)

    // Graph Configuration
    // ###################

    graph.backgroundColor = UIColor.white
    graph.shouldAnimateOnStartup = true

    // Reference Lines
    // ###############

    let referenceLines = ReferenceLines()
    referenceLines.positionType = .relative
    referenceLines.relativePositions = [0, 0.5, 0.8, 0.9, 1]

    graph.addReferenceLines(referenceLines: referenceLines)

    // Adding Plots
    // ############

    let linePlot = LinePlot(identifier: "linePlot")
    linePlot.lineWidth = 5
    linePlot.lineColor = UIColor.black

    let barPlot = BarPlot(identifier: "barPlot")
    barPlot.barWidth = 20
    barPlot.barLineColor = UIColor.gray

    graph.addPlot(plot: linePlot)
    graph.addPlot(plot: barPlot)

    self.view.addSubview(graph)
}

// Implementation for ScrollableGraphViewDataSource protocol
func value(forPlot plot: Plot, atIndex pointIndex: Int) -> Double {

    switch (plot.identifier) {
    case "linePlot":
        return linePlotData[pointIndex]
        break
    case "barPlot":
        return barPlotData[pointIndex]
        break
    }
}

func label(atIndex pointIndex: Int) -> String {
    return xAxisLabels[pointIndex]
}

func numberOfPoints() -> Int {
    return numberOfPointsInGraph
}
}
</code>```

答:
The identifier property of the Plot class does not have an explicit access level, so it receives the default access level of "internal". Internal properties can be accessed by from code within the defining module but not from code in another module.

Your code is not in the defining module, so it cannot access the internal identifier property.

The author of that framework should probably make a read-only public identifier property available.

Submitting an issue on the repo, as you have done, is a reasonable approach.

You can work around the problem by forking the repo and explicitly changing identifier to be public var identifier:String! although this is a bit of a hack.

identifier should really be public let identifier:String with an appropriate initialiser that the subclasses call. It looks like the author is intending Plot to be an "abstract" class by not providing an initialiser, but they then have to use an implicitly unwrapped identifier variable. An internal init(identifier:) function would be preferable in my opinion

Body:
I am implementing the ScrollableGraphView library in my code (https://github.com/philackm/ScrollableGraphView) and experiencing the following problem:

To confirm to ScrollableGraphViewDataSource, when i add

func value(forPlot plot: Plot, atIndex pointIndex: Int) -> Double

to my code, Xcode gives the following error at "plot.identifier" :

'identifier' is inaccessible due to 'internal' protection level.

Can anyone help what is going on?

import UIKit

import ScrollableGraphView

class ViewController: UIViewController, ScrollableGraphViewDataSource {

// Class members and init...

var linePlotData: [Double] = [1, 2, 3, 4, 5]// data for line plot
var barPlotData: [Double] =  [1, 2, 3, 4, 5]// data for bar plot
var xAxisLabels: [String] =  ["Jan", "Feb", "Mar", "Apr", "May"]// the labels along the x axis

var numberOfPointsInGraph = 5

override func viewDidLoad() {
    super.viewDidLoad()

    let graph = ScrollableGraphView(frame: self.view.frame, dataSource: self)

    // Graph Configuration
    // ###################

    graph.backgroundColor = UIColor.white
    graph.shouldAnimateOnStartup = true

    // Reference Lines
    // ###############

    let referenceLines = ReferenceLines()
    referenceLines.positionType = .relative
    referenceLines.relativePositions = [0, 0.5, 0.8, 0.9, 1]

    graph.addReferenceLines(referenceLines: referenceLines)

    // Adding Plots
    // ############

    let linePlot = LinePlot(identifier: "linePlot")
    linePlot.lineWidth = 5
    linePlot.lineColor = UIColor.black

    let barPlot = BarPlot(identifier: "barPlot")
    barPlot.barWidth = 20
    barPlot.barLineColor = UIColor.gray

    graph.addPlot(plot: linePlot)
    graph.addPlot(plot: barPlot)

    self.view.addSubview(graph)
}

// Implementation for ScrollableGraphViewDataSource protocol
func value(forPlot plot: Plot, atIndex pointIndex: Int) -> Double {

    switch (plot.identifier) {
    case "linePlot":
        return linePlotData[pointIndex]
        break
    case "barPlot":
        return barPlotData[pointIndex]
        break
    }
}

func label(atIndex pointIndex: Int) -> String {
    return xAxisLabels[pointIndex]
}

func numberOfPoints() -> Int {
    return numberOfPointsInGraph
}
}


问:
How to get state from child to parent react
I'm new in React

I have two components. Parent Square, child Row.

I want to get setValues cellTop and cellLeft from Row to parent and use it.

How can I do it.

My code is bellow

var Square = React.createClass({

 getInitialState: function () {

  return {

  countRow: 4,
  countCol: 4,
  mouseOnTable: false,
  onDelRow: false,
  onDelCol: false

  }

 },

 appendCol: function() {

  var countColNew = this.state.countCol + 1;

  this.setState({countCol: countColNew});  //change initiale state "countCol" (add new column)

  //console.log(this.state.countCol)

 },

 appendRow: function() {

  var countRowNew = this.state.countRow + 1;

  this.setState({countRow: countRowNew});  //change initiale state "countRow" (add new row)

  //console.log(this.state.countRow)

 },

 deleteCol: function() {

  var countColNew = this.state.countCol - 1;

  this.setState({countCol: countColNew});  //change initiale state "countCol" (delete col)

  //console.log(this.state.countCol)

 },

 deleteRow: function() {

  var countRowNew = this.state.countRow - 1;

  this.setState({countRow: countRowNew});  //change initiale state (delete row)

  //console.log(this.state.countRow)

 },

 hiddenButtons: function(){
  var mouseOnTableNew = true;
  this.setState({mouseOnTable: mouseOnTableNew})
 },

 showButtons: function(){
  var mouseOnTableNew = false;
  this.setState({mouseOnTable: mouseOnTableNew})
 },

 render: function() {

  var timeOut;

  return (

 {timeOut=setTimeout(this.showButtons,200)}}>

       <Row countRow={this.state.countRow}
         countCol={this.state.countCol}
         ref={(ref) => this.state}

         />

       <button className="square__button square__button_append square__button_col-append"
         onClick={this.appendCol}>
       </button>

             <button className="square__button square__button_delete square__button_col-delete"
               style={this.state.countCol===1 ||
                   this.state.mouseOnTable===false ||
                   this.state.onDelRow===true ? {visibility: "hidden"} : {visibility: "visible"}}

               onClick={this.deleteCol}
               onMouseOver={() => {clearTimeout(timeOut);
                    this.setState({onDelCol:true})}}
               onMouseLeave={() => {this.setState({onDelCol:false})}}>
             </button>

             <button className="square__button square__button_append square__button_row-append"
               onClick={this.appendRow}>
             </button>

             <button className="square__button square__button_delete square__button_row-delete"
               style={this.state.countRow===1 ||
                   this.state.mouseOnTable===false ||
                   this.state.onDelCol===true ? {visibility: "hidden"} : {visibility: "visible"}}

               onClick={this.deleteRow}

               onMouseOver={() => {clearTimeout(timeOut);
                    this.setState({onDelRow:true})}}

               onMouseLeave={() => {this.setState({onDelRow:false})}}>
             </button>

  )

 }

})

//==================================================

var Row = React.createClass({

 getInitialState: function(){
  return {

   cellTop: 0,
   cellLeft: 0,

  }

 },

 createCol: function() {

  var columns = [];

  for(let i = 0; i < this.props.countCol; i++){
   columns.push(this.createCell)
  }

  return columns;

 },

 createRow: function (k) {

  return (

    {this.createCol().map(function(cell,key){
     return (
       cell(key)
      )
    })}

  )
 },

 createCell: function(k){

  return (

  )

 },

 getMousePosition: function(element){

  let coordinates = element.target.getBoundingClientRect();
  let top = coordinates.top;
  let left = coordinates.left;

  this.setState({
   cellTop: top,
   cellLeft: left
  })

 },

 render: function(){

   var lines = []
   for (let i = 0; i < this.props.countRow; i++) {
   lines.push(this.createRow(i))
  }

  return (

    {lines}

  )
 }

})```

答:
You can pass your child component a callback function that accepts two arguments, cellTop and cellLeft. In your child component pass cellTop and cellLeft values at the same time you are calling getMousePosition() function in your child component.

In your parent component create a function like this:

```<code>handleSizeChange: function(cellTop, cellLeft){
    this.setState({
        cellTop: cellTop,
        cellLeft: cellLeft
    })
},
</code>```

In your Parent <Row> component pass a callback function as a prop like this:

```<code><Row countRow={this.state.countRow}
     countCol={this.state.countCol}
     ref={(ref) => this.state}
     onSizeChange={this.handleSizeChange}
/>
</code>```

In your Child component add this.props.handleSizeChange(top, left) to your getMousePostion() function:

```<code>getMousePosition: function(element){

    let coordinates = element.target.getBoundingClientRect();
    let top = coordinates.top;
    let left = coordinates.left;

    this.setState({
        cellTop: top,
        cellLeft: left
    })

    this.props.handleSizeChange(top, left)
},
</code>```

Its also true that whenever possible its best for data to flow from Parent -> Child components, but callback functions are common for things like button events.  You could use something like Redux to handle state management, but that is fairly advanced and is probably overkill if this is a simple beginner application.

Also, you should be using the newest React syntax for components.  Create new classes like this:

```<code>import React, { Component } from 'react'

class App extends Component {
      constructor() {
          super()

          //getinitialstate
          this.state = {
            cellTop: 0,
            cellLeft: 0
          }
      }
}
</code>```

and define class methods like this:

```<code>  componentWillMount() {
    // this runs right before the <App> is rendered

  })
</code>```

Body:
You can pass your child component a callback function that accepts two arguments, cellTop and cellLeft. In your child component pass cellTop and cellLeft values at the same time you are calling getMousePosition() function in your child component.

In your parent component create a function like this:

handleSizeChange: function(cellTop, cellLeft){
    this.setState({
        cellTop: cellTop,
        cellLeft: cellLeft
    })
},

In your Parent <Row> component pass a callback function as a prop like this:

<Row countRow={this.state.countRow}
     countCol={this.state.countCol}
     ref={(ref) => this.state}
     onSizeChange={this.handleSizeChange}
/>

In your Child component add this.props.handleSizeChange(top, left) to your getMousePostion() function:

getMousePosition: function(element){

    let coordinates = element.target.getBoundingClientRect();
    let top = coordinates.top;
    let left = coordinates.left;

    this.setState({
        cellTop: top,
        cellLeft: left
    })

    this.props.handleSizeChange(top, left)
},

Its also true that whenever possible its best for data to flow from Parent -> Child components, but callback functions are common for things like button events.  You could use something like Redux to handle state management, but that is fairly advanced and is probably overkill if this is a simple beginner application.

Also, you should be using the newest React syntax for components.  Create new classes like this:

import React, { Component } from 'react'

class App extends Component {
      constructor() {
          super()

          //getinitialstate
          this.state = {
            cellTop: 0,
            cellLeft: 0
          }
      }
}

and define class methods like this:

  componentWillMount() {
    // this runs right before the <App> is rendered

  })


问:
Is there a Java equivalent for Python's map function?
I would like to easily transform a collection (list) of objects of class A to a collection of objects of class B, just as Python's map function does it. Is there any "well-known" implementation of this (some kind of library)? I've already searched for it in Apache's commons-lang but with no luck. </p>

答:
You can try guava, but you are likely to find that if you use an anonymous class its will be more complicated and longer than just using a loop.

```<code>List<OldType> list1 =
List<NewType> list2 = new ArrayList<NewType>(list1.size());
for(OldType element: list1);
   list2.add(transform(element));
</code>```

Its worth remembering that Java is not a functional language and its often better to just use a loop. Perhaps when Java has closures .... sigh.

ContentLicense: CC BY-SA 2.5

Body:
You can try guava, but you are likely to find that if you use an anonymous class its will be more complicated and longer than just using a loop.

List<OldType> list1 =
List<NewType> list2 = new ArrayList<NewType>(list1.size());
for(OldType element: list1);
   list2.add(transform(element));

Its worth remembering that Java is not a functional language and its often better to just use a loop. Perhaps when Java has closures .... sigh.


问:
HTML Javascript dynamic changes to a button
Good morning everyone, I have been working on this all night and I need some assistance. I am trying to use JavaScript to dynamically change a log in button's color when I log in to my site. It seems that my code not only breaks the button when logged in, but has no effect on the background color of the button at all. Here is the code including the button:
As you can see, the "btnSignIn" calls the signin() method when clicked. Here is the javascript file I have:

var validUser;
function init() {
var loginCookie = loginWithCookie();
if(loginCookie === true) {
    validUser = true;
    document.getElementById("btnSignIn").outerHTML = "Sign out";
    document.getElementById("btnSignIn").style.backgroundColor = "pink";
    document.getElementById("results").innnerHTML = "Welcome " + user +"!";
    document.getElementById("txtUserName").style.visibility = "hidden";
    document.getElementById("txtPassword").style.visibility = "hidden";
}
else {
  validUser = false;
}
}

function signin() {

if (document.getElementById("btnSignIn").innerHTML == "Sign out") {

    validUser = false;
    document.getElementById("btnSignIn").innerHTML = "Sign in";
    document.getElementById("btnSignIn").style.backgroundColor = "orange";
    document.getElementById("results").innerHTML = "Welcome stranger";
    document.getElementById("txtUserName").style.visibility = "visible";
    document.getElementById("txtPassword").style.visibility = "visible";
    setCookie("txtUserName", null, "txtPassword", null, 365);
}
else {
    var user = document.getElementById("txtUserName").value;
    var pwd = document.getElementById("txtPassword").value;
    if (user.text === "" && user === null &&
        pwd.text === "" && pwd === null) {
        validUser = false;
    }

    else if (user === "john@me.com" && pwd === "snow") {
        validUser = true;
        document.getElementById("btnSignIn").style.backgroundColor = "pink";
        document.getElementById("btnSignIn").outerHTML = "Sign out";
        document.getElementById("results").innerHTML = "Welcome "+ user      + "!";
        document.getElementById("txtUserName").style.visibility = "hidden";
        document.getElementById("txtPassword").style.visibility = "hidden";
        var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
        if (!myCookie) {
             validUser = false;
        }
    }
    return false;
}
}

function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = uname + "=" + uvalue + "; " + expires;
    document.cookie = pname + "=" + pvalue + "; " + expires;
    return true;
}
else {
    return false;
}
}

function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
   var user = getCookie("username");
   if (user !== "") {
    return user;
   }else {
        return false;
    }
}
else {
    return false;
}
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
        return c.substring(name.length, c.length);
    }
}
return "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav navbar-nav navbar-right">
                <li>
                    <form id="loginform" class="navbar-form navbar-right">
                        <div class="form-group">
                            <input type="text"  id="txtUserName" placeholder="Email" class="form-control">
                        </div>
                        <div class="form-group">
                            <input type="password" id="txtPassword" placeholder="Password" class="form-control">
                        </div>
                        <button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();"  >Sign in</button>
                    </form>
                </li>
            </ul></code>```

The goal is, when I log in, it will say 'sign out' instead of 'sign in' and it will turn pink in the background. Right now, it signs in okay but it only says 'sign out' in white letters, with no button capability and no background color change.

答:
You're using outerHTML to set the text of #btnSignIn which replaces the node with just text, since all you provided was text. That removes the #btnSignIn element that you applied the background to. Use innerHTML instead.

You're also missing #results in this demo.

Note, I added return false to an inline onsubmit handler for the form, just for this demo so you can see the state of the button after submitting. You'll probably want to remove that in your actual code.

var validUser;

function init() {
    var loginCookie = loginWithCookie();
    if (loginCookie === true) {
        validUser = true;
        document.getElementById("btnSignIn").innerHTML = "Sign out";
        document.getElementById("btnSignIn").style.backgroundColor = "pink";
        document.getElementById("results").innnerHTML = "Welcome " + user + "!";
        document.getElementById("txtUserName").style.visibility = "hidden";
        document.getElementById("txtPassword").style.visibility = "hidden";
    } else {
        validUser = false;
    }
}

function signin() {

    if (document.getElementById("btnSignIn").innerHTML == "Sign out") {

        validUser = false;
        document.getElementById("btnSignIn").innerHTML = "Sign in";
        document.getElementById("btnSignIn").style.backgroundColor = "orange";
        document.getElementById("results").innerHTML = "Welcome stranger";
        document.getElementById("txtUserName").style.visibility = "visible";
        document.getElementById("txtPassword").style.visibility = "visible";
        setCookie("txtUserName", null, "txtPassword", null, 365);
    } else {
        var user = document.getElementById("txtUserName").value;
        var pwd = document.getElementById("txtPassword").value;
        if (user.text === "" && user === null &&
            pwd.text === "" && pwd === null) {
            validUser = false;
        } else if (user === "john@me.com" && pwd === "snow") {
            validUser = true;
            document.getElementById("btnSignIn").style.backgroundColor = "pink";
            document.getElementById("btnSignIn").innerHTML = "Sign out";
            document.getElementById("results").innerHTML = "Welcome " + user + "!";
            document.getElementById("txtUserName").style.visibility = "hidden";
            document.getElementById("txtPassword").style.visibility = "hidden";
            var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
            if (!myCookie) {
                validUser = false;
            }
        }
        return false;
    }
}

function setCookie(uname, uvalue, pname, pvalue, exdays) {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;
    if (cookieEnabled === true) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = uname + "=" + uvalue + "; " + expires;
        document.cookie = pname + "=" + pvalue + "; " + expires;
        return true;
    } else {
        return false;
    }
}

function loginWithCookie() {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;
    if (cookieEnabled === true) {
        var user = getCookie("username");
        if (user !== "") {
            return user;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="nav navbar-nav navbar-right">
  <li>
    <form id="loginform" class="navbar-form navbar-right" onsubmit="return false;">
      <div class="form-group">
        <input type="text" id="txtUserName" placeholder="Email" class="form-control">
      </div>
      <div class="form-group">
        <input type="password" id="txtPassword" placeholder="Password" class="form-control">
      </div>
      <button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();">Sign in</button>
    </form>
    <div id="results"></div>
  </li>
</ul></code>```

Body:
Good morning everyone, I have been working on this all night and I need some assistance. I am trying to use JavaScript to dynamically change a log in button's color when I log in to my site. It seems that my code not only breaks the button when logged in, but has no effect on the background color of the button at all. Here is the code including the button:
As you can see, the "btnSignIn" calls the signin() method when clicked. Here is the javascript file I have:

var validUser;
function init() {
var loginCookie = loginWithCookie();
if(loginCookie === true) {
    validUser = true;
    document.getElementById("btnSignIn").outerHTML = "Sign out";
    document.getElementById("btnSignIn").style.backgroundColor = "pink";
    document.getElementById("results").innnerHTML = "Welcome " + user +"!";
    document.getElementById("txtUserName").style.visibility = "hidden";
    document.getElementById("txtPassword").style.visibility = "hidden";
}
else {
  validUser = false;
}
}

function signin() {

if (document.getElementById("btnSignIn").innerHTML == "Sign out") {

    validUser = false;
    document.getElementById("btnSignIn").innerHTML = "Sign in";
    document.getElementById("btnSignIn").style.backgroundColor = "orange";
    document.getElementById("results").innerHTML = "Welcome stranger";
    document.getElementById("txtUserName").style.visibility = "visible";
    document.getElementById("txtPassword").style.visibility = "visible";
    setCookie("txtUserName", null, "txtPassword", null, 365);
}
else {
    var user = document.getElementById("txtUserName").value;
    var pwd = document.getElementById("txtPassword").value;
    if (user.text === "" && user === null &&
        pwd.text === "" && pwd === null) {
        validUser = false;
    }

    else if (user === "john@me.com" && pwd === "snow") {
        validUser = true;
        document.getElementById("btnSignIn").style.backgroundColor = "pink";
        document.getElementById("btnSignIn").outerHTML = "Sign out";
        document.getElementById("results").innerHTML = "Welcome "+ user      + "!";
        document.getElementById("txtUserName").style.visibility = "hidden";
        document.getElementById("txtPassword").style.visibility = "hidden";
        var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
        if (!myCookie) {
             validUser = false;
        }
    }
    return false;
}
}

function setCookie(uname, uvalue, pname, pvalue, exdays) {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = uname + "=" + uvalue + "; " + expires;
    document.cookie = pname + "=" + pvalue + "; " + expires;
    return true;
}
else {
    return false;
}
}

function loginWithCookie() {
var cookieEnabled = (navigator.cookieEnabled) ? true : false;
if (cookieEnabled === true) {
   var user = getCookie("username");
   if (user !== "") {
    return user;
   }else {
        return false;
    }
}
else {
    return false;
}
}

function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
        c = c.substring(1);
    }
    if (c.indexOf(name) === 0) {
        return c.substring(name.length, c.length);
    }
}
return "";
}

                    <form id="loginform" class="navbar-form navbar-right">

                            <input type="text"  id="txtUserName" placeholder="Email" class="form-control">

                            <input type="password" id="txtPassword" placeholder="Password" class="form-control">

                        <button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();"  >Sign in</button>
                    </form>

The goal is, when I log in, it will say 'sign out' instead of 'sign in' and it will turn pink in the background. Right now, it signs in okay but it only says 'sign out' in white letters, with no button capability and no background color change.

Body:
You're using outerHTML to set the text of #btnSignIn which replaces the node with just text, since all you provided was text. That removes the #btnSignIn element that you applied the background to. Use innerHTML instead.

You're also missing #results in this demo.

Note, I added return false to an inline onsubmit handler for the form, just for this demo so you can see the state of the button after submitting. You'll probably want to remove that in your actual code.

var validUser;

function init() {
    var loginCookie = loginWithCookie();
    if (loginCookie === true) {
        validUser = true;
        document.getElementById("btnSignIn").innerHTML = "Sign out";
        document.getElementById("btnSignIn").style.backgroundColor = "pink";
        document.getElementById("results").innnerHTML = "Welcome " + user + "!";
        document.getElementById("txtUserName").style.visibility = "hidden";
        document.getElementById("txtPassword").style.visibility = "hidden";
    } else {
        validUser = false;
    }
}

function signin() {

    if (document.getElementById("btnSignIn").innerHTML == "Sign out") {

        validUser = false;
        document.getElementById("btnSignIn").innerHTML = "Sign in";
        document.getElementById("btnSignIn").style.backgroundColor = "orange";
        document.getElementById("results").innerHTML = "Welcome stranger";
        document.getElementById("txtUserName").style.visibility = "visible";
        document.getElementById("txtPassword").style.visibility = "visible";
        setCookie("txtUserName", null, "txtPassword", null, 365);
    } else {
        var user = document.getElementById("txtUserName").value;
        var pwd = document.getElementById("txtPassword").value;
        if (user.text === "" && user === null &&
            pwd.text === "" && pwd === null) {
            validUser = false;
        } else if (user === "john@me.com" && pwd === "snow") {
            validUser = true;
            document.getElementById("btnSignIn").style.backgroundColor = "pink";
            document.getElementById("btnSignIn").innerHTML = "Sign out";
            document.getElementById("results").innerHTML = "Welcome " + user + "!";
            document.getElementById("txtUserName").style.visibility = "hidden";
            document.getElementById("txtPassword").style.visibility = "hidden";
            var myCookie = setCookie("txtUserName", user, "txtPassword", pwd, 365);
            if (!myCookie) {
                validUser = false;
            }
        }
        return false;
    }
}

function setCookie(uname, uvalue, pname, pvalue, exdays) {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;
    if (cookieEnabled === true) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = uname + "=" + uvalue + "; " + expires;
        document.cookie = pname + "=" + pvalue + "; " + expires;
        return true;
    } else {
        return false;
    }
}

function loginWithCookie() {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;
    if (cookieEnabled === true) {
        var user = getCookie("username");
        if (user !== "") {
            return user;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

<ul class="nav navbar-nav navbar-right">
  <li>
    <form id="loginform" class="navbar-form navbar-right" onsubmit="return false;">
      <div class="form-group">
        <input type="text" id="txtUserName" placeholder="Email" class="form-control">
      </div>
      <div class="form-group">
        <input type="password" id="txtPassword" placeholder="Password" class="form-control">
      </div>
      <button type="submit" id="btnSignIn" class="btn btn-warning" onclick="signin();">Sign in</button>&nbsp;
    </form>
    <div id="results"></div>
  </li>
</ul>


问:
Django CRUD operations for multiple records - transaction.atomic vs bulk_create
I have a Django 1.10 model, and a simple model:

I have a simple REST endpoint designed for testing purposes:

```<code>@api_view(['POST'])
@transaction.atomic
def r_test(request):
    for record in request.data:
        serializer = TestSerializer(data = record)
        if serializer.is_valid():
           serializer.save()
</code>```

...that takes 9 seconds (too slow) to execute for one 100 records.

If I rewrite it the following way, it executes instantly.

```<code>@api_view(['POST'])
def r_test(request):
    obj_list = []
    for record in request.data:
       obj = Test(field1 = record['field1'])
       obj_list.append(obj)
    Test.objects.bulk_create(obj_list)
</code>```

What bothers me is that I have read in many sources that wrapping function into a transaction (which I do by adding a decorator @transaction.atomic) would significantly improve insert operations in case of multiple operations. But I can't see this now.

So the question is, does only bulk_create() deliver super-fast speed for inserting big data, or there's something I am doing wrong with transaction.atomic?

Update: Moreover, I have ATOMIC_REQUESTS set to True in my settings. BTW, could it be that something is wrong in the settings? Like, say, Debug = True hinders Django from executing queries in a single transaction ?

Update 2 I have tried both ways with decorator and by wrapping the for loop in with transaction.atomic():. And still I observe instant execution only with bulk_create()

Update 3. My DB is MySQL

答:
djangorestframework, right? I think you should improve your api function first:

```<code>def r_test(request):
    serializer = TestSerializer(data=request.data, many=True)
    if serializer.is_valid():
       serializer.save()
</code>```

Try it again.

Body:
I have a Django 1.10 model, and a simple model:

I have a simple REST endpoint designed for testing purposes:

@api_view(['POST'])
@transaction.atomic
def r_test(request):
    for record in request.data:
        serializer = TestSerializer(data = record)
        if serializer.is_valid():
           serializer.save()

...that takes 9 seconds (too slow) to execute for one 100 records.

If I rewrite it the following way, it executes instantly.

@api_view(['POST'])
def r_test(request):
    obj_list = []
    for record in request.data:
       obj = Test(field1 = record['field1'])
       obj_list.append(obj)
    Test.objects.bulk_create(obj_list)

What bothers me is that I have read in many sources that wrapping function into a transaction (which I do by adding a decorator @transaction.atomic) would significantly improve insert operations in case of multiple operations. But I can't see this now.

So the question is, does only bulk_create() deliver super-fast speed for inserting big data, or there's something I am doing wrong with transaction.atomic?

Update: Moreover, I have ATOMIC_REQUESTS set to True in my settings. BTW, could it be that something is wrong in the settings? Like, say, Debug = True hinders Django from executing queries in a single transaction ?

Update 2 I have tried both ways with decorator and by wrapping the for loop in with transaction.atomic():. And still I observe instant execution only with bulk_create()

Update 3. My DB is MySQL

Body:
djangorestframework, right? I think you should improve your api function first:

def r_test(request):
    serializer = TestSerializer(data=request.data, many=True)
    if serializer.is_valid():
       serializer.save()

Try it again.


问:
Edit default .htaccess in wordpress docker
I have a wordpress container which gets generated by a docker-compose file. Wordpress container contains <code>.htaccess</code> file by default. I want to  edit that such that that the edit is performed only once when container is created. </p>

答:
For now I can think of two possible solutions for this problem:

We can use a static .htaccess file and mount that as a volume at the place where original .htaccess is copied, i.e, at /var/html/www inside container. From updates to this answer, I have verified that this .htaccess file will not get overwritten by default docker-entrypoint.sh.

We can use the docker-entrypoint.sh from wordpress docker at github and modify the part which creates the .htaccess file. This will keep the default behavior of entrypoint and .htaccess file will also be modified.

Update: Answer given by @Nazar is also correct. Having a closer look at default docker-entrypoint.sh in wordpress image, I found that there is a condition at line 35, which checks if .htaccess file already exists and creates a new file only if file does not exist. So, if I create my own file using RUN, it will not be overwritten.

Body: I have a wordpress container which gets generated by a docker-compose file. Wordpress container contains .htaccess file by default. I want to  edit that such that that the edit is performed only once when container is created.


问:
Using glyphicon-facebook from bootstrap 3
I would like to use glyphicon-facebook.  works but why doesn't  work? And also there is no option such as 'glyphicon glyphicon-facebook'.

答:
add in header file and <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

use

for different logo you have to use different name here is the list of icons and their code http://fontawesome.io/icons/

Body:
add in header file and <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

use <i class="fa fa-facebook"></i>

for different logo you have to use different name here is the list of icons and their code http://fontawesome.io/icons/


问:
How does React know the component is removed from the DOM?
Under Adding Lifecycle Methods to a Class in the official Facebook docs for React, it's mentioned:

5) If the Clock component is ever removed from the DOM, React calls the componentWillUnmount() lifecycle hook so the timer is stopped.

Just trying to understand how? I get that React knows when it's about to insert the component in the DOM, so it can callcomponentDidMount life cycle hook then.

But for componentWillUnmount it just says "ever removed from the DOM". Seems to suggest it's the real DOM not React DOM. One might as well remove the component with javaScript/jQuery and componentWillUnmount should fire.

How exactly does React know the component has been removed from the real DOM? Could there be a watcher?

Thanks

答:
This is not true. IF you do manually remove a component from the DOM it will not fire componentWillUnmount..
It happens only via Virtual DOM, level if the component is not present anymore:

```<code>// Unmount children that are no longer present.
for (name in prevChildren) {
  if (
    prevChildren.hasOwnProperty(name) &&
    !(nextChildren && nextChildren.hasOwnProperty(name))
  ) {
    prevChild = prevChildren[name];
    removedNodes[name] = ReactReconciler.getHostNode(prevChild);
    ReactReconciler.unmountComponent(
      prevChild,
      false /* safely */,
      false /* skipLifecycle */,
    );
  }
}
</code>```

https://github.com/facebook/react/blob/5c6a496d98b80d19d851c2ec3a56d760b7118a50/src/renderers/shared/stack/reconciler/ReactChildReconciler.js

unmountComponent will then call componentWillUnmount.

I manually tested componentWillUnmount by opening the devtools and removing some components that had componentWillUnmount lifecycle method.

Body:
This is not true. IF you do manually remove a component from the DOM it will not fire componentWillUnmount..
It happens only via Virtual DOM, level if the component is not present anymore:

// Unmount children that are no longer present.
for (name in prevChildren) {
  if (
    prevChildren.hasOwnProperty(name) &&
    !(nextChildren && nextChildren.hasOwnProperty(name))
  ) {
    prevChild = prevChildren[name];
    removedNodes[name] = ReactReconciler.getHostNode(prevChild);
    ReactReconciler.unmountComponent(
      prevChild,
      false /* safely */,
      false /* skipLifecycle */,
    );
  }
}

https://github.com/facebook/react/blob/5c6a496d98b80d19d851c2ec3a56d760b7118a50/src/renderers/shared/stack/reconciler/ReactChildReconciler.js

unmountComponent will then call componentWillUnmount.

I manually tested componentWillUnmount by opening the devtools and removing some components that had componentWillUnmount lifecycle method.


问:
Accuracy optimized in WEKA WrapperSubsetEval?
I'm using WEKA via the GUI. When running WrapperSubsetEval with J48 and BestFirst on a classification problem,I see that the tool optimizes by default for Accuracy in case of discrete class. How is this Accuracy  formally defined? </p>

答:
Accuracy is the number of instances the classifier classified correctly out of all instances it classified.

More formally:
(# of correct classifications)/(# of correct and wrong classifications)

I think you should read https://en.wikipedia.org/wiki/Precision_and_recall


问:
Resize byte[] of Image
After reading from file dialog I want to resize a picture. I have the done the following code. Now I want to resize the stream of picture. How do I do it?</p>

```<code>Stream stream = (Stream)openFileDialog.File.OpenRead();
byte[] bytes = new byte[stream.Length];
</code>```

答:
I have an picturebox. I load an image, resizing and conveting to byte at last sending to sqllite. Maybe it can be hlepfıull to you Code is below.</p>

```<code>private static byte[] byteResim = null;

    private void btnResimEkle_Click(object sender, EventArgs e)
    {
        openFileDialog1.Title = "Resimdosyası seçiniz.";
        openFileDialog1.Filter = "Resim files (*.jpg)|*.jpg|Tüm dosyalar(*.*)|*.*";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {

            string resimYol = openFileDialog1.FileName; // File name of the image

            picResim.Image = Image.FromFile(resimYol);// picResim is name of picturebox
            picResim.Image = YenidenBoyutlandir(new Bitmap(picResim.Image)); //this method resizing the image
            Image UyeResim = picResim.Image;   // and this four block converting to image to byte
            MemoryStream ms = new MemoryStream();
            UyeResim.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byteResim = ms.ToArray();  // byteResim  variable format  Byte[]

        }
    }

    Image YenidenBoyutlandir(Image resim)// resizing image method

    {
        Image yeniResim = new Bitmap(150, 156);
        using (Graphics abc = Graphics.FromImage((Bitmap)yeniResim))
        {
            abc.DrawImage(resim, new System.Drawing.Rectangle(0, 0, 150, 156));
        }
        return yeniResim;
    }
</code>```

Title: Resize byte[] of Image

Body:
After reading from file dialog I want to resize a picture. I have the done the following code. Now I want to resize the stream of picture. How do I do it?

Stream stream = (Stream)openFileDialog.File.OpenRead();
byte[] bytes = new byte[stream.Length];

Body:
I have an picturebox. I load an image, resizing and conveting to byte at last sending to sqllite. Maybe it can be hlepfıull to you Code is below.

private static byte[] byteResim = null;

    private void btnResimEkle_Click(object sender, EventArgs e)
    {
        openFileDialog1.Title = "Resimdosyası seçiniz.";
        openFileDialog1.Filter = "Resim files (*.jpg)|*.jpg|Tüm dosyalar(*.*)|*.*";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {

            string resimYol = openFileDialog1.FileName; // File name of the image

            picResim.Image = Image.FromFile(resimYol);// picResim is name of picturebox
            picResim.Image = YenidenBoyutlandir(new Bitmap(picResim.Image)); //this method resizing the image
            Image UyeResim = picResim.Image;   // and this four block converting to image to byte
            MemoryStream ms = new MemoryStream();
            UyeResim.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byteResim = ms.ToArray();  // byteResim  variable format  Byte[]

        }
    }

    Image YenidenBoyutlandir(Image resim)// resizing image method

    {
        Image yeniResim = new Bitmap(150, 156);
        using (Graphics abc = Graphics.FromImage((Bitmap)yeniResim))
        {
            abc.DrawImage(resim, new System.Drawing.Rectangle(0, 0, 150, 156));
        }
        return yeniResim;
    }


问:
Inserting element into array using c#
```<code>        int[] arr = {4,3,6,7,9,12};

        int n = arr.Length;
        n = n + 1;

        for (int i =n;i>2;i--) {
        arr[i-1] = arr[i-2];

        }

        arr[0] = 4;
</code>```

The above code returning

indexOutOfRangeexception.

答:
Your array is of Length 6 starting from 0.

In for loop i becomes 7 and arr[7-1] = arr[6] is out of range, maximum is arr[5] ie:

```<code>arr[0]
arr[1]
arr[2]
arr[3]
arr[4]
arr[5]
</code>```

Title: Inserting element into array using c#

Body:
        int[] arr = {4,3,6,7,9,12};

        int n = arr.Length;
        n = n + 1;

        for (int i =n;i>2;i--) {
        arr[i-1] = arr[i-2];

        }

        arr[0] = 4;

The above code returning

indexOutOfRangeexception.

Body:
Your array is of Length 6 starting from 0.

In for loop i becomes 7 and arr[7-1] = arr[6] is out of range, maximum is arr[5] ie:

arr[0]
arr[1]
arr[2]
arr[3]
arr[4]
arr[5]


问:
Mysql subselect extremely slow (doesn't seem to be using indexes)
This query doesn't complete in a reasonable amount of time:

```<code>mysql> select * from prices where symbol='GOOG' and date in
(select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001
 group by yearweek(date));
</code>```

'prices' is keyed off id, and has a secondary unique index of (symbol, date):

```<code>mysql> show index from prices;
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table  | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| prices |          0 | PRIMARY         |            1 | id          | A         |      468915 |     NULL | NULL   |      | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            1 | date        | A         |       10905 |     NULL | NULL   | YES  | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            2 | symbol      | A          |      468915 |     NULL | NULL   | YES  | BTREE      |         |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
3 rows in set (0.00 sec)
</code>```

From looking at the EXPLAIN output, it seems as though MySql is not using the index on (date, symbol).  Does the combination of WHERE symbol='GOOG' and date IN (...)) require a full table scan and not use the secondary unique index?

```<code>mysql> EXPLAIN select * from prices where symbol='GOOG' and date in (select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001 group by yearweek(date));
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
| id | select_type        | table  | type  | possible_keys | key             | key_len | ref  | rows   | Extra                                                     |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
|  1 | PRIMARY            | prices | ALL   | NULL          | NULL            | NULL    | NULL | 468915 | Using where                                               |
|  2 | DEPENDENT SUBQUERY | prices | index | NULL          | SECONDARY_INDEX | 17      | NULL | 468915 | Using where; Using index; Using temporary; Using filesort |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
2 rows in set (0.00 sec)
</code>```

答:
The yearweek() disables the index on column date.

Try changing it to:

```<code>and date > date'2010-01-09'
</code>```

...where 2010-01-09 is the last day in week 201001. Beware of timestamps in the column though.

Body:
This query doesn't complete in a reasonable amount of time:

mysql> select * from prices where symbol='GOOG' and date in
(select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001
 group by yearweek(date));

'prices' is keyed off id, and has a secondary unique index of (symbol, date):

mysql> show index from prices;
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| Table  | Non_unique | Key_name        | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
| prices |          0 | PRIMARY         |            1 | id          | A         |      468915 |     NULL | NULL   |      | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            1 | date        | A         |       10905 |     NULL | NULL   | YES  | BTREE      |         |
| prices |          0 | SECONDARY_INDEX |            2 | symbol      | A          |      468915 |     NULL | NULL   | YES  | BTREE      |         |
+--------+------------+-----------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
3 rows in set (0.00 sec)

From looking at the EXPLAIN output, it seems as though MySql is not using the index on (date, symbol).  Does the combination of WHERE symbol='GOOG' and date IN (...)) require a full table scan and not use the secondary unique index?

mysql> EXPLAIN select * from prices where symbol='GOOG' and date in (select max(date) from prices where symbol='GOOG' and yearweek(date) > 201001 group by yearweek(date));
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
| id | select_type        | table  | type  | possible_keys | key             | key_len | ref  | rows   | Extra                                                     |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
|  1 | PRIMARY            | prices | ALL   | NULL          | NULL            | NULL    | NULL | 468915 | Using where                                               |
|  2 | DEPENDENT SUBQUERY | prices | index | NULL          | SECONDARY_INDEX | 17      | NULL | 468915 | Using where; Using index; Using temporary; Using filesort |
+----+--------------------+--------+-------+---------------+-----------------+---------+------+--------+-----------------------------------------------------------+
2 rows in set (0.00 sec)

Body:
The yearweek() disables the index on column date.

Try changing it to:

and date > date'2010-01-09'

...where 2010-01-09 is the last day in week 201001. Beware of timestamps in the column though.


问:
Rolling subtraction to a column
I want to do a rolling subtraction to a column within a data frame. Line 2 will subtract from line 1 column.

The goal here is to subtract line 2 from line 1 in the value column... and roll it down the data.frame

Excel is simply =sum(B2-B1)

An example data frame is below

```<code>    Date    Value       Diff
1   19280103    17.76   NA
2   19280104    17.72   -0.04
3   19280105    17.55   -0.17
4   19280106    17.66   0.11
5   19280107    17.68   0.02
6   19280109    17.5    -0.18
7   19280110    17.37   -0.13
</code>```

Title: Rolling subtraction to a column

Body:
I want to do a rolling subtraction to a column within a data frame. Line 2 will subtract from line 1 column.

The goal here is to subtract line 2 from line 1 in the value column... and roll it down the data.frame

Excel is simply =sum(B2-B1)

An example data frame is below

    Date    Value       Diff
1   19280103    17.76   NA
2   19280104    17.72   -0.04
3   19280105    17.55   -0.17
4   19280106    17.66   0.11
5   19280107    17.68   0.02
6   19280109    17.5    -0.18
7   19280110    17.37   -0.13

Body:
With dplyr it is easy, you can use lag function.

> library('dplyr')
> x <- c(1,3,5,6,7,8,9,10,5,4)
> y <- 1:length(x)
>
> dt <- data.frame('x' = x, 'y' = y)
>
> dt %>% mutate(diffx = x - lag(x, 1), diffy = y - lag(y, 1))
    x  y diffx diffy
1   1  1    NA    NA
2   3  2     2     1
3   5  3     2     1
4   6  4     1     1
5   7  5     1     1
6   8  6     1     1
7   9  7     1     1
8  10  8     1     1
9   5  9    -5     1
10  4 10    -1     1

you could also just do:

> cbind(dt, 'diffx' = c(NA, diff(x)), 'diffy' = c(NA, diff(y)))
    x  y diffx diffy
1   1  1    NA    NA
2   3  2     2     1
3   5  3     2     1
4   6  4     1     1
5   7  5     1     1
6   8  6     1     1
7   9  7     1     1
8  10  8     1     1
9   5  9    -5     1
10  4 10    -1     1


问:
SQL - CONCAT with an IF statement returning 1583 error
Is there a limitation with the CONCAT function so that it cannot handle an IF statement?  I have this query, that works if it is not a part of a CONCAT but as soon as I put it inside a CONCAT function it gives this error: #1583 - Incorrect parameters in the call to native function 'CONCAT'

```<code>SELECT CONCAT((IF(DAYOFYEAR(`deathdatetr`) and DAYOFYEAR(`birthdatetr`),TO_DAYS(`deathdatetr`) - TO_DAYS(`birthdatetr`),(YEAR(`deathdatetr`) - YEAR(`birthdatetr`)) * 365))/365.25 as totaldays, " years old") from tng_people order by totaldays limit 1;
</code>```

This query should return the oldest person in the database (age in years). The table I am querying contains among other things, birth- and deathdates in the format "1860-07-30".

Can someone help me figure this out?

答:
Your parentheses are messed up.  You have a column alias in the middle of the expression.  It is not surprising that MySQL is confused, because you seem to be as well.

It is fine to use if() where any expression is expected.  I much prefer CASE (it is standard), but because you started with IF():

```<code>SELECT CONCAT(IF(DAYOFYEAR(`deathdatetr`) = DAYOFYEAR(`birthdatetr`),
                 TO_DAYS(`deathdatetr`) - TO_DAYS(`birthdatetr`),
                 (YEAR(`deathdatetr`) - YEAR(`birthdatetr`)) * 365)
                ) /365.25, ' years old') as total_years
from tng_people
order by totaldays
limit 1;
</code>```

I have no idea what this logic is supposed to be doing.  It doesn't seem useful, but that is another matter.

If you want the days between to dates:

```<code>select (to_days(deathdatetr) - to_days(birthdatetr)) as total_days
</code>```

Body:
Is there a limitation with the CONCAT function so that it cannot handle an IF statement?  I have this query, that works if it is not a part of a CONCAT but as soon as I put it inside a CONCAT function it gives this error: #1583 - Incorrect parameters in the call to native function 'CONCAT'

SELECT CONCAT((IF(DAYOFYEAR(`deathdatetr`) and DAYOFYEAR(`birthdatetr`),TO_DAYS(`deathdatetr`) - TO_DAYS(`birthdatetr`),(YEAR(`deathdatetr`) - YEAR(`birthdatetr`)) * 365))/365.25 as totaldays, " years old") from tng_people order by totaldays limit 1;

This query should return the oldest person in the database (age in years). The table I am querying contains among other things, birth- and deathdates in the format "1860-07-30".

Can someone help me figure this out?

Body:
Your parentheses are messed up.  You have a column alias in the middle of the expression.  It is not surprising that MySQL is confused, because you seem to be as well.

It is fine to use if() where any expression is expected.  I much prefer CASE (it is standard), but because you started with IF():

SELECT CONCAT(IF(DAYOFYEAR(`deathdatetr`) = DAYOFYEAR(`birthdatetr`),
                 TO_DAYS(`deathdatetr`) - TO_DAYS(`birthdatetr`),
                 (YEAR(`deathdatetr`) - YEAR(`birthdatetr`)) * 365)
                ) /365.25, ' years old') as total_years
from tng_people
order by totaldays
limit 1;

I have no idea what this logic is supposed to be doing.  It doesn't seem useful, but that is another matter.

If you want the days between to dates:

select (to_days(deathdatetr) - to_days(birthdatetr)) as total_days


问:
Angular issue on exisiting project
I'm on Windows 7.

I imported an Angular project started by a friend, but I had some issue after installing node and angular, I was able to run the project with this command:

```<code>C:\NG\projectName>npm start
</code>```

But when I try to generate a new component with this command I get an error:

```<code>C:\NG\projectName\app\components>ng g c myNewComponentName
installing component
Unable to find any apps in `.angular-cli.json`
</code>```

The angular-cli.json file is located here: C:\NG\projectName\node_modules\@angular\cli\blueprints\ng\files\ and contains this code:

```<code>{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "<%= htmlComponentName %>"
  },
  "apps": [
    {
      "root": "<%= sourceDir %>",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "<%= prefix %>",
      "styles": [
        "styles.<%= styleExt %>"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "<%= sourceDir %>/tsconfig.app.json"
    },
    {
      "project": "<%= sourceDir %>/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "<%= styleExt %>",<% if (!minimal) { %>
    "component": {}<% } else { %>
    "component": {
      "spec": false,
      "inlineStyle": true,
      "inlineTemplate": true
    },
    "directive": {
      "spec": false
    },
    "class": {
      "spec": false
    },
    "guard": {
      "spec": false
    },
    "module": {
      "spec": false
    },
    "pipe": {
      "spec": false
    },
    "service": {
      "spec": false
    } <% } %>
  }
}
</code>```

How can I fix that?

For information:

```<code>C:\NG\projectName\app\components>ng -v
@angular/cli: 1.2.0
node: 6.11.0
os: win32 x64
@angular/animations: 4.2.5
@angular/common: 4.2.5
@angular/compiler: 4.2.5
@angular/compiler-cli: 4.2.5
@angular/core: 4.2.5
@angular/forms: 4.2.5
@angular/http: 4.2.5
@angular/platform-browser: 4.2.5
@angular/platform-browser-dynamic: 4.2.5
@angular/platform-server: error
@angular/router: 4.2.5
@angular/tsc-wrapped: 4.0.3
@angular/upgrade: error
@angular/cli: 1.2.0

C:\NG\projectName\app\components>npm -v
3.10.10
</code>```

thank you for your help.

答:
The problem is most likely that the project was not initialized with the angular cli.

Running ng init in C:\NG\projectName> should solve the problem¹

Title: Angular issue on exisiting project

Body:
I'm on Windows 7.

I imported an Angular project started by a friend, but I had some issue after installing node and angular, I was able to run the project with this command:

C:\NG\projectName>npm start

But when I try to generate a new component with this command I get an error:

C:\NG\projectName\app\components>ng g c myNewComponentName
installing component
Unable to find any apps in `.angular-cli.json`

The angular-cli.json file is located here: C:\NG\projectName\node_modules\@angular\cli\blueprints\ng\files\ and contains this code:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "<%= htmlComponentName %>"
  },
  "apps": [
    {
      "root": "<%= sourceDir %>",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "<%= prefix %>",
      "styles": [
        "styles.<%= styleExt %>"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "<%= sourceDir %>/tsconfig.app.json"
    },
    {
      "project": "<%= sourceDir %>/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "<%= styleExt %>",<% if (!minimal) { %>
    "component": {}<% } else { %>
    "component": {
      "spec": false,
      "inlineStyle": true,
      "inlineTemplate": true
    },
    "directive": {
      "spec": false
    },
    "class": {
      "spec": false
    },
    "guard": {
      "spec": false
    },
    "module": {
      "spec": false
    },
    "pipe": {
      "spec": false
    },
    "service": {
      "spec": false
    } <% } %>
  }
}

How can I fix that?

For information:

C:\NG\projectName\app\components>ng -v
@angular/cli: 1.2.0
node: 6.11.0
os: win32 x64
@angular/animations: 4.2.5
@angular/common: 4.2.5
@angular/compiler: 4.2.5
@angular/compiler-cli: 4.2.5
@angular/core: 4.2.5
@angular/forms: 4.2.5
@angular/http: 4.2.5
@angular/platform-browser: 4.2.5
@angular/platform-browser-dynamic: 4.2.5
@angular/platform-server: error
@angular/router: 4.2.5
@angular/tsc-wrapped: 4.0.3
@angular/upgrade: error
@angular/cli: 1.2.0

C:\NG\projectName\app\components>npm -v
3.10.10

thank you for your help.


问:
If cell is touched - move on the another VC [SWIFT]
If cell is touched - move on the another VC, how can i do it?
I tried to do it, but i didn't work.
Here is my code

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData" {
        let destination = segue.destination as! WinnerViewController

        let cell = sender as? UITableViewCell

        if cell == cell {
            let indexPath = tableView.indexPath(for: cell!)
            if indexPath == indexPath {
                let productName = users[(indexPath?.row)!]
                destination.winner = productName.name
            }
        }
    }
</code>```

When i touch each cell - it isn't moving.
Please help

答:
There are two options to perform a segue when a cell is tapped.

The segue is connected from the table view cell to the destination controller

In this case the cell is passed as the sender parameter

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData", let cell = sender as? UITableViewCell {
         let destination = segue.destination as! WinnerViewController
         let indexPath = tableView.indexPath(for: cell)!
         let productName = users[indexPath.row]
         destination.winner = productName.name
    }
}
</code>```

The segue is connected from the source controller to the destination controller

In this case you have to implement didSelectRowAt, call performSegue(withIdentifier and pass the index path as sender parameter

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "transData", sender: indexPath)
 }
</code>```

Then prepare(for has to be

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData", let indexPath = sender as? IndexPath {
         let destination = segue.destination as! WinnerViewController
         let productName = users[indexPath.row]
         destination.winner = productName.name
    }
}
</code>```

Body:
If cell is touched - move on the another VC, how can i do it?
I tried to do it, but i didn't work.
Here is my code

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData" {
        let destination = segue.destination as! WinnerViewController

        let cell = sender as? UITableViewCell

        if cell == cell {
            let indexPath = tableView.indexPath(for: cell!)
            if indexPath == indexPath {
                let productName = users[(indexPath?.row)!]
                destination.winner = productName.name
            }
        }
    }

When i touch each cell - it isn't moving.
Please help

Body:
There are two options to perform a segue when a cell is tapped.

The segue is connected from the table view cell to the destination controller

In this case the cell is passed as the sender parameter

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData", let cell = sender as? UITableViewCell {
         let destination = segue.destination as! WinnerViewController
         let indexPath = tableView.indexPath(for: cell)!
         let productName = users[indexPath.row]
         destination.winner = productName.name
    }
}

The segue is connected from the source controller to the destination controller

In this case you have to implement didSelectRowAt, call performSegue(withIdentifier and pass the index path as sender parameter

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "transData", sender: indexPath)
 }

Then prepare(for has to be

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "transData", let indexPath = sender as? IndexPath {
         let destination = segue.destination as! WinnerViewController
         let productName = users[indexPath.row]
         destination.winner = productName.name
    }
}


问:
Differences between dependencyManagement and dependencies in maven for "provided" scope
I referred to this thread differences between dependencymanagement and dependencies in maven but this question is specific.

Parent POM:

```<code><dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.company.rtdp.rtds</groupId>
      <artifactId>rtds-client</artifactId>
      <version>${rtdp.rtds-client.version}</version>
      <!-- SCENARIO 1 : Either give scope here in parent POM -->
      <!-- <scope>provided</scope> -->
    </dependency>
  </dependencies>
</dependencyManagement>

<rtdp.rtds-client.version>1.4.6</rtdp.rtds-client.version>
</code>```

Child POM:

```<code> <dependencies>
    <!-- SCENARIO 2
    <dependency>
        <groupId>com.company.rtdp.rtds</groupId>
        <artifactId>realtimedataserv-client</artifactId>
        <version>1.4.6</version>
        <scope>provided</scope>
    </dependency>
    -->

    <dependency>
        <groupId>com.company.idi</groupId>
        <artifactId>idi-persistence</artifactId>
        <version>3.3</version>
        <!--  has a dependency of com.company.rtdp.rtds:rtds-client:jar:1.4.6:compile -->
    </dependency>
 </dependencies>

<!-- SCENARIO 1: OR give scope here in child POM
<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.company.rtdp.rtds</groupId>
      <artifactId>rtds-client</artifactId>
      <version>1.4.6</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>
</dependencyManagement>
-->
</code>```

rtds-client is a transitive dependency of many artifacts out of which idi-persistence is one of them. I want to exclude 1.4.6 in all of the transitive dependencies since I am going to include a different artifact rtds-framework-client (different artifact name) explicitly which is backward compatible to 1.4.6 with <dependency> in child POM.

If have to use <exclusion> I have to explicitly give this in all the dependencies. So, I have decided to go <scope>provided</scope> way.

Known info of Maven based on which my question follows:

If I include the following in child POM (with a version higher than 1.4.6, then rtds-client in all transitive dependencies gets shifted to 1.8. I could see this from 'Dependency Hierarchy' of Eclipse which says 'omitted for conflict with 1.8' [compile]) which means it considers/overrides the version specified in child POM (idi-persistence now gets 1.8).

```<code><dependency>
    <groupId>com.company.rtdp.rtds</groupId>
    <artifactId>rtds-client</artifactId>
    <version>1.8</version>
</dependency>
</code>```

Question:

If I include the following in child POM without <dependencyManagement> around:

```<code><dependency>
    <groupId>com.company.rtdp.rtds</groupId>
    <artifactId>rtds-client</artifactId>
    <version>1.4.6</version>
    <scope>provided<scope>
</dependency>
</code>```

None of the rtds-client which comes as transitive dependency considers provided scope whereas I mention the same in a <dependencyManagement> tag either in parent or child POM, provided scope gets applied.

Why version gets affected but not scope given inside <dependency> tag and for scope (for this kind of use case) I have to go for <dependencyManagement> ?

Say if this is allowed, what problem it would lead us into ?

EDIT:

i) <scope>provided with <dependencyManagement>/<dependencies>/<dependency> either in child or parent POM:

Though the longer path is omitted, it says [provided],here.

```<code>[INFO] +- com.company.idi:idi-persistence:jar:3.3:compile
[INFO] |  +- com.company.rtdp.rtds:realtimedataserv-client:jar:1.4.6:provided
</code>```

ii) <scope>provided with direct <dependencies>/<dependency> in child POM without <dependencyManagement> around :

Though the longer path is omitted, it does not say provided and just compile alone.

```<code>[INFO] --- maven-dependency-plugin:2.3:tree (default-cli) @ read-rest-service ---
[INFO] +- com.company.rtdp.rtds:realtimedataserv-client:jar:1.4.6:provided (scope not updated to compile)
</code>```

答:
I can't comprehend your <scope>provided in <dependencyManagement> vs. <dependency.

If I declare a child POM, with no dependency[Management] in the parent whatsoever, like:

```<code><project ...>
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>igb.so</groupId>
        <artifactId>SO-44987444-parent</artifactId>
        <relativePath>../SO-44987444-parent</relativePath>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>SO-44987444-child</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.1</version>
            <!--  has a dependency of org.apache.commons:commons-lang3:jar:3.5:compile -->
        </dependency>
    </dependencies>

</project>
</code>```

the dependency:tree looks like:

```<code>[INFO] ------------------------------------------------------------------------
[INFO] Building SO-44987444-child 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ SO-44987444-child ---
[INFO] igb.so:SO-44987444-child:jar:0.0.1-SNAPSHOT
[INFO] \- org.apache.commons:commons-text:jar:1.1:compile
[INFO]    \- org.apache.commons:commons-lang3:jar:3.5:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

If I add commons-lang3 as direct dependency with <scope>provided:

```<code>        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
            <scope>provided</scope>
        </dependency>
</code>```

the dependency:tree looks like:

```<code>[INFO] ------------------------------------------------------------------------
[INFO] Building SO-44987444-child 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ SO-44987444-child ---
[INFO] igb.so:SO-44987444-child:jar:0.0.1-SNAPSHOT
[INFO] +- org.apache.commons:commons-text:jar:1.1:compile
[INFO] \- org.apache.commons:commons-lang3:jar:3.5:provided
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
</code>```

Even if I add to the parent POM:

```<code>    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
                <version>3.5</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</code>```

the dependency:tree results aren't any different.

Body:
I referred to this thread differences between dependencymanagement and dependencies in maven but this question is specific.

Parent POM:

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.company.rtdp.rtds</groupId>
      <artifactId>rtds-client</artifactId>
      <version>${rtdp.rtds-client.version}</version>

    </dependency>
  </dependencies>
</dependencyManagement>

<rtdp.rtds-client.version>1.4.6</rtdp.rtds-client.version>

Child POM:

 <dependencies>

    <dependency>
        <groupId>com.company.idi</groupId>
        <artifactId>idi-persistence</artifactId>
        <version>3.3</version>

    </dependency>
 </dependencies>

rtds-client is a transitive dependency of many artifacts out of which idi-persistence is one of them. I want to exclude 1.4.6 in all of the transitive dependencies since I am going to include a different artifact rtds-framework-client (different artifact name) explicitly which is backward compatible to 1.4.6 with <dependency> in child POM.

If have to use <exclusion> I have to explicitly give this in all the dependencies. So, I have decided to go <scope>provided</scope> way.

Known info of Maven based on which my question follows:

If I include the following in child POM (with a version higher than 1.4.6, then rtds-client in all transitive dependencies gets shifted to 1.8. I could see this from 'Dependency Hierarchy' of Eclipse which says 'omitted for conflict with 1.8' [compile]) which means it considers/overrides the version specified in child POM (idi-persistence now gets 1.8).

<dependency>
    <groupId>com.company.rtdp.rtds</groupId>
    <artifactId>rtds-client</artifactId>
    <version>1.8</version>
</dependency>

Question:

If I include the following in child POM without <dependencyManagement> around:

<dependency>
    <groupId>com.company.rtdp.rtds</groupId>
    <artifactId>rtds-client</artifactId>
    <version>1.4.6</version>
    <scope>provided<scope>
</dependency>

None of the rtds-client which comes as transitive dependency considers provided scope whereas I mention the same in a <dependencyManagement> tag either in parent or child POM, provided scope gets applied.

Why version gets affected but not scope given inside <dependency> tag and for scope (for this kind of use case) I have to go for <dependencyManagement> ?

Say if this is allowed, what problem it would lead us into ?

EDIT:

i) <scope>provided with <dependencyManagement>/<dependencies>/<dependency> either in child or parent POM:

Though the longer path is omitted, it says [provided],here.

[INFO] +- com.company.idi:idi-persistence:jar:3.3:compile
[INFO] |  +- com.company.rtdp.rtds:realtimedataserv-client:jar:1.4.6:provided

ii) <scope>provided with direct <dependencies>/<dependency> in child POM without <dependencyManagement> around :

Though the longer path is omitted, it does not say provided and just compile alone.

[INFO] --- maven-dependency-plugin:2.3:tree (default-cli) @ read-rest-service ---
[INFO] +- com.company.rtdp.rtds:realtimedataserv-client:jar:1.4.6:provided (scope not updated to compile)

Body:
I can't comprehend your <scope>provided in <dependencyManagement> vs. <dependency.

If I declare a child POM, with no dependency[Management] in the parent whatsoever, like:

<project ...>
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>igb.so</groupId>
        <artifactId>SO-44987444-parent</artifactId>
        <relativePath>../SO-44987444-parent</relativePath>
        <version>0.0.1-SNAPSHOT</version>
    </parent>

    <artifactId>SO-44987444-child</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.1</version>
            <!--  has a dependency of org.apache.commons:commons-lang3:jar:3.5:compile -->
        </dependency>
    </dependencies>

</project>

the dependency:tree looks like:

[INFO] ------------------------------------------------------------------------
[INFO] Building SO-44987444-child 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ SO-44987444-child ---
[INFO] igb.so:SO-44987444-child:jar:0.0.1-SNAPSHOT
[INFO] \- org.apache.commons:commons-text:jar:1.1:compile
[INFO]    \- org.apache.commons:commons-lang3:jar:3.5:compile
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

If I add commons-lang3 as direct dependency with <scope>provided:

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
            <scope>provided</scope>
        </dependency>

the dependency:tree looks like:

[INFO] ------------------------------------------------------------------------
[INFO] Building SO-44987444-child 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ SO-44987444-child ---
[INFO] igb.so:SO-44987444-child:jar:0.0.1-SNAPSHOT
[INFO] +- org.apache.commons:commons-text:jar:1.1:compile
[INFO] \- org.apache.commons:commons-lang3:jar:3.5:provided
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

Even if I add to the parent POM:

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-lang3</artifactId>
                <version>3.5</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

the dependency:tree results aren't any different.


问:
How to disable class in a particular table column?
i am not sure if this is possible or not.
Anyway i want to disable .sorting class from one column, the class is of bootstrap. Please check the URL image for more.

http://prntscr.com/ftebsr

Thank you.

答:
Based on your screenshot I assume this is in reference to a table enhanced by Bootstrap DataTables.  That being the case, a more comprehensive solution might be to make use of the columnDefs option in your JS configuration:

https://datatables.net/reference/option/columns.orderable

```<code>$('#example').dataTable( {
  "columnDefs": [
    { "orderable": false, "targets": 0 }
  ]
});
</code>```

Body:
Based on your screenshot I assume this is in reference to a table enhanced by Bootstrap DataTables.  That being the case, a more comprehensive solution might be to make use of the columnDefs option in your JS configuration:

https://datatables.net/reference/option/columns.orderable

$('#example').dataTable( {
  "columnDefs": [
    { "orderable": false, "targets": 0 }
  ]
});


问:
Embed multiple view controllers in a container view
I have a base view controller which is like my "blueprint" to create more view controllers to show the user (register/login/reset password/etc.). This base view controller has a container view.

I have many little view controllers that I would like for the container view of my base view controller, like so:

How do I use different view controllers for the container view? How do I specify which mini view controller I can use in my container view? I could probably use the storyboard ID/segues but I don't know how. Any tips?

答:
Hi cesare the problem can be resolve by taking the containerView in baseClass where you can take three different viewControllers.

Please find these simple tutorial where you can add or remove the child viewController programmatically

```<code>        private func add(asChildViewController viewController: UIViewController) {
            // Add Child View Controller
            addChildViewController(viewController)

            // Add Child View as Subview
            view.addSubview(viewController.view)

            // Configure Child View
            viewController.view.frame = view.bounds
            viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

            // Notify Child View Controller
            viewController.didMove(toParentViewController: self)
        }

        private func remove(asChildViewController viewController: UIViewController) {
            // Notify Child View Controller
            viewController.willMove(toParentViewController: nil)

            // Remove Child View From Superview
            viewController.view.removeFromSuperview()

            // Notify Child View Controller
            viewController.removeFromParentViewController()
        }
</code>```

For reference you can find this github project

https://github.com/bartjacobs/ManagingViewControllersWithContainerViewControllers/blob/master/ViewControllerContainment/MasterViewController.swift

Body:
Hi cesare the problem can be resolve by taking the containerView in baseClass where you can take three different viewControllers.

Please find these simple tutorial where you can add or remove the child viewController programmatically

        private func add(asChildViewController viewController: UIViewController) {
            // Add Child View Controller
            addChildViewController(viewController)

            // Add Child View as Subview
            view.addSubview(viewController.view)

            // Configure Child View
            viewController.view.frame = view.bounds
            viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]

            // Notify Child View Controller
            viewController.didMove(toParentViewController: self)
        }

        private func remove(asChildViewController viewController: UIViewController) {
            // Notify Child View Controller
            viewController.willMove(toParentViewController: nil)

            // Remove Child View From Superview
            viewController.view.removeFromSuperview()

            // Notify Child View Controller
            viewController.removeFromParentViewController()
        }

For reference you can find this github project

https://github.com/bartjacobs/ManagingViewControllersWithContainerViewControllers/blob/master/ViewControllerContainment/MasterViewController.swift

ContentLicense: CC BY-SA 4.0