问:
QML add buttons dynamically
i wrote a simple code and the question is how to add button to first page and not the second page. i've got three calsses (main.qml, componentCreation.js, ButtonD.qml)

```<code>import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import "componentCreation.js" as MyScript

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    property var position: 0

    Rectangle{
        id: main
        color: "#FFFFFF"
        width: parent.width
        height: parent.height
        x:200
        y:0
        focus: true

        StackView{
            id: stack
            initialItem: firstPage
            Component{
                id: firstPage
                Rectangle{
                    id:firstRect
                    Label{
                        text: "firstPage"
                        x:100
                    }
                    Button{
                        text: "next"
                        onClicked:{
                            MyScript.createSpriteObjects(position)
                            position+=50
                            stack.push(secondPage)
                        }
                    }
                }
            }
            Component{
                id: secondPage
                Rectangle{
                    id:secondRect
                    Label{
                        text: "secondPage"
                        x:100
                    }
                    Button{
                        text: "back"
                        onClicked: stack.push(firstPage)
                    }
                }
            }
        }
    }
}
</code>```

javaScript code as described in qt website(componentCreation.js)

```<code>    var component;
    var sprite;
    function createSpriteObjects(number) {
        component = Qt.createComponent("ButtonD.qml");
        if (component.status == Component.Ready)
            finishCreation(number);
        else
            component.statusChanged.connect(finishCreation);
    }
    function finishCreation(number) {
        if (component.status == Component.Ready) {
            sprite = component.createObject(main, {"x": 50, "y": number});
            number += 50
            if (sprite == null) {
                console.log("Error creating object");
            }
        } else if (component.status == Component.Error) {
            console.log("Error loading component:", component.errorString());
        }
    }
</code>```

the button i want to add

```<code>import QtQuick 2.0
import QtQuick.Controls 1.4
Button{
    text: "created"
}
</code>```

答:
Well, like Mitch already pointed out your example code is not complete.

However, I think the problem is that finishCreation() function does not know about 'main' id.

```<code>var component;
var sprite;

    function createSpriteObjects() {
        component = Qt.createComponent("ButtonD.qml");
        if (component.status == Component.Ready)
            finishCreation();
        else
            component.statusChanged.connect(finishCreation);
    }

    function finishCreation() {
        if (component.status == Component.Ready) {
            sprite = component.createObject(main, {"x": 100, "y": 500});
            if (sprite == null) {
                // Error Handling
                console.log("Error creating object");
            }
        } else if (component.status == Component.Error) {
            // Error Handling
            console.log("Error loading component:", component.errorString());
        }
    }
</code>```

So maybe you should pass the reference to the functions above (untested):

```<code>    var component;
    var sprite;

        function createSpriteObjects(parentId) {
            component = Qt.createComponent("ButtonD.qml");
            if (component.status == Component.Ready) {
              if (component.status == Component.Ready) {
               sprite = component.createObject(parentId, {"x": 100, "y": 500});
               if (sprite == null) {
                 // Error Handling
                console.log("Error creating object");
               }
             } else if (component.status == Component.Error) {
                // Error Handling
                console.log("Error loading component:", component.errorString());
             }
          } else {
                var thatParentId = parentId;
                component.statusChanged.connect(function() {
                  if (component.status == Component.Ready) {
                   sprite = component.createObject(thatParentId, {"x": 100, "y": 500});
                    if (sprite == null) {
                      // Error Handling
                      console.log("Error creating object");
                    }
                  } else if (component.status == Component.Error) {
                     // Error Handling
                     console.log("Error loading component:", component.errorString());
                  }
                });
         }
     }
</code>```

After that you can call MyScripts.createSpriteObjects(secondRect);

Title: QML add buttons dynamically

Body:
i wrote a simple code and the question is how to add button to first page and not the second page. i've got three calsses (main.qml, componentCreation.js, ButtonD.qml)

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import "componentCreation.js" as MyScript

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    property var position: 0

    Rectangle{
        id: main
        color: "#FFFFFF"
        width: parent.width
        height: parent.height
        x:200
        y:0
        focus: true

        StackView{
            id: stack
            initialItem: firstPage
            Component{
                id: firstPage
                Rectangle{
                    id:firstRect
                    Label{
                        text: "firstPage"
                        x:100
                    }
                    Button{
                        text: "next"
                        onClicked:{
                            MyScript.createSpriteObjects(position)
                            position+=50
                            stack.push(secondPage)
                        }
                    }
                }
            }
            Component{
                id: secondPage
                Rectangle{
                    id:secondRect
                    Label{
                        text: "secondPage"
                        x:100
                    }
                    Button{
                        text: "back"
                        onClicked: stack.push(firstPage)
                    }
                }
            }
        }
    }
}

javaScript code as described in qt website(componentCreation.js)

    var component;
    var sprite;
    function createSpriteObjects(number) {
        component = Qt.createComponent("ButtonD.qml");
        if (component.status == Component.Ready)
            finishCreation(number);
        else
            component.statusChanged.connect(finishCreation);
    }
    function finishCreation(number) {
        if (component.status == Component.Ready) {
            sprite = component.createObject(main, {"x": 50, "y": number});
            number += 50
            if (sprite == null) {
                console.log("Error creating object");
            }
        } else if (component.status == Component.Error) {
            console.log("Error loading component:", component.errorString());
        }
    }

the button i want to add

import QtQuick 2.0
import QtQuick.Controls 1.4
Button{
    text: "created"
}

Body:
Well, like Mitch already pointed out your example code is not complete.

However, I think the problem is that finishCreation() function does not know about 'main' id.

var component;
var sprite;

    function createSpriteObjects() {
        component = Qt.createComponent("ButtonD.qml");
        if (component.status == Component.Ready)
            finishCreation();
        else
            component.statusChanged.connect(finishCreation);
    }

    function finishCreation() {
        if (component.status == Component.Ready) {
            sprite = component.createObject(main, {"x": 100, "y": 500});
            if (sprite == null) {
                // Error Handling
                console.log("Error creating object");
            }
        } else if (component.status == Component.Error) {
            // Error Handling
            console.log("Error loading component:", component.errorString());
        }
    }

So maybe you should pass the reference to the functions above (untested):

    var component;
    var sprite;

        function createSpriteObjects(parentId) {
            component = Qt.createComponent("ButtonD.qml");
            if (component.status == Component.Ready) {
              if (component.status == Component.Ready) {
               sprite = component.createObject(parentId, {"x": 100, "y": 500});
               if (sprite == null) {
                 // Error Handling
                console.log("Error creating object");
               }
             } else if (component.status == Component.Error) {
                // Error Handling
                console.log("Error loading component:", component.errorString());
             }
          } else {
                var thatParentId = parentId;
                component.statusChanged.connect(function() {
                  if (component.status == Component.Ready) {
                   sprite = component.createObject(thatParentId, {"x": 100, "y": 500});
                    if (sprite == null) {
                      // Error Handling
                      console.log("Error creating object");
                    }
                  } else if (component.status == Component.Error) {
                     // Error Handling
                     console.log("Error loading component:", component.errorString());
                  }
                });
         }
     }

After that you can call MyScripts.createSpriteObjects(secondRect);


来源: stackexchange

问:
How to create bean by double reference?
I do not know how to articulate/search the issue in the first place.

So the bean initialized are :

```<code><bean id='domain' factory-bean='appConfig' factory-method='getDomain'/
<bean id='prod' class='java.lang.String'> <constructor-arg value='Base.Prod'/> </bean>
<bean id='test' class='java.lang.String'> <constructor-arg value='Base.Beta' /> </bean>
</code>```

Now I need to create a bean "X" using the value of Prod or Test depending on the value of domain. If domain is Prod,use the bean of Prod to initialize bean X else use Test.

${${domain}} does not work. I tried searching but was not able to find a question that meant this.

答:
@EssexBoy's answer in XML would look something like this:</p>

```<code><bean id="domain" class="java-lang.String">
    <constructor-arg>
        <value>${domain}</value>
    </construcotr-arg>
</bean>
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to create bean by double reference?

Body:
I do not know how to articulate/search the issue in the first place.

So the bean initialized are :

<bean id='domain' factory-bean='appConfig' factory-method='getDomain'/
<bean id='prod' class='java.lang.String'> <constructor-arg value='Base.Prod'/> </bean>
<bean id='test' class='java.lang.String'> <constructor-arg value='Base.Beta' /> </bean>

Now I need to create a bean "X" using the value of Prod or Test depending on the value of domain. If domain is Prod,use the bean of Prod to initialize bean X else use Test.

${${domain}} does not work. I tried searching but was not able to find a question that meant this.

Body:
@EssexBoy's answer in XML would look something like this:

<bean id="domain" class="java-lang.String">
    <constructor-arg>
        <value>${domain}</value>
    </construcotr-arg>
</bean>


问:
Convert SQL with multiple join into LINQ
I would like to know how can i change the following sql statement into Linq or Lambda Extension in C#

```<code>SELECT m.mdes as AgeGroup,COUNT(DISTINCT(mbcd))as "No.of Member" FROM mageg m
LEFT JOIN  (select distinct(mbcd) ,mage
FROMtevtl
JOIN mvipm
ON tevtl.mbcd = mvipm.mvip
WHERE datm >= '2014-04-01'
AND datm <= '2014-04-30'
)vip
ON m.tage >= vip.mage AND m.fage <= vip.mage
GROUP BY m.mdes
</code>```

I manage to do the first half of the LINQ statement. Not sure If it is correct
here is the first half. I do not know how to connect with the left join.

```<code>(from mem in mvipms
from log in tevtls
from grp in magegs
where mem.mage >=grp.fage && mem.mage <=grp.tage && mem.mvip.Equals(log.mbcd)
&& log.datm >= DateTime.Parse("2014-04-01") && log.datm <= DateTime.Parse("2014-04-30")
select new {mem.mvip,grp.mdes}).Distinct()
</code>```

Pls advice. I am using the MSSQL 2008 and VS2010.

Thanks a million.

答:
I am no expert on LINQ, but since no-one else has answered, here goes!

Firstly you cannot (AFAIK) do a LINQ join on anything other than equals so the structure of your LEFT JOIN has to change. Partly for debugging purposes, but also for readability, I prefer to layout my LINQ in bite-size chunks, so what I would do in your case is something like this (assuming I have understood your data structure correctly):

```<code>    var vip = (from t in tevtl
               join v in mvipl
               on t.mbcd equals v.mvip
               where t.datm >= new DateTime(2014, 4, 1) && t.datm <= new DateTime(2014, 4, 30)
               select new { t.mbcd, v.mage }).Distinct();
    var mv = from m in magegl
             from v in vip
             where m.tage >= v.mage && m.fage <= v.mage
             select new
             {
                 m.mdes,
                 v.mbcd
             };
    var gmv = from m in mv
              group m by new { m.mdes } into grp
              select new
              {
                  mdes = grp.Key.mdes,
                  CountMBCD = grp.Count()
              };
    var lj = from m in magegl
             join v in gmv
             on m.mdes equals v.mdes into lhs
             from x in lhs.DefaultIfEmpty()
             select new
             {
                 AgeGroup = m.mdes,
                 CountMBCD = x != null ? x.CountMBCD : 0
             };
</code>```

By way of explanation. mv is the equivalent structure for your left join in that it has the relevant where clause, but obviously it does not contain any nulls - it is equivalent to an INNER JOIN.  gmv is a group on mv, so is still effectively an INNER JOIN.  Then to pick up the missing mdes (if any) I re-join on magel with the added syntax DefaultIfEmpty() - this converts the join into the equivalent of a LEFT OUTER JOIN.

Without any sample data, I haven't been able to test this, but I hope it gives you enough to point you in the right direction!

Body:
I would like to know how can i change the following sql statement into Linq or Lambda Extension in C#

SELECT m.mdes as AgeGroup,COUNT(DISTINCT(mbcd))as "No.of Member" FROM mageg m
LEFT JOIN  (select distinct(mbcd) ,mage
FROMtevtl
JOIN mvipm
ON tevtl.mbcd = mvipm.mvip
WHERE datm >= '2014-04-01'
AND datm <= '2014-04-30'
)vip
ON m.tage >= vip.mage AND m.fage <= vip.mage
GROUP BY m.mdes

I manage to do the first half of the LINQ statement. Not sure If it is correct
here is the first half. I do not know how to connect with the left join.

(from mem in mvipms
from log in tevtls
from grp in magegs
where mem.mage >=grp.fage && mem.mage <=grp.tage && mem.mvip.Equals(log.mbcd)
&& log.datm >= DateTime.Parse("2014-04-01") && log.datm <= DateTime.Parse("2014-04-30")
select new {mem.mvip,grp.mdes}).Distinct()

Pls advice. I am using the MSSQL 2008 and VS2010.

Thanks a million.

Body:
I am no expert on LINQ, but since no-one else has answered, here goes!

Firstly you cannot (AFAIK) do a LINQ join on anything other than equals so the structure of your LEFT JOIN has to change. Partly for debugging purposes, but also for readability, I prefer to layout my LINQ in bite-size chunks, so what I would do in your case is something like this (assuming I have understood your data structure correctly):

    var vip = (from t in tevtl
               join v in mvipl
               on t.mbcd equals v.mvip
               where t.datm >= new DateTime(2014, 4, 1) && t.datm <= new DateTime(2014, 4, 30)
               select new { t.mbcd, v.mage }).Distinct();
    var mv = from m in magegl
             from v in vip
             where m.tage >= v.mage && m.fage <= v.mage
             select new
             {
                 m.mdes,
                 v.mbcd
             };
    var gmv = from m in mv
              group m by new { m.mdes } into grp
              select new
              {
                  mdes = grp.Key.mdes,
                  CountMBCD = grp.Count()
              };
    var lj = from m in magegl
             join v in gmv
             on m.mdes equals v.mdes into lhs
             from x in lhs.DefaultIfEmpty()
             select new
             {
                 AgeGroup = m.mdes,
                 CountMBCD = x != null ? x.CountMBCD : 0
             };

By way of explanation. mv is the equivalent structure for your left join in that it has the relevant where clause, but obviously it does not contain any nulls - it is equivalent to an INNER JOIN.  gmv is a group on mv, so is still effectively an INNER JOIN.  Then to pick up the missing mdes (if any) I re-join on magel with the added syntax DefaultIfEmpty() - this converts the join into the equivalent of a LEFT OUTER JOIN.

Without any sample data, I haven't been able to test this, but I hope it gives you enough to point you in the right direction!


问:
Excel custom number format complex conditions
I need following:

My numbers are to be divided by 1000 and rounded, negative in brackets, zeroes as "-":

```<code>  1500 ->  2
  499  ->  -
  0    ->  -
 -499  ->  -
 -1500 -> (2)
</code>```

I cannot find how to transform values [-499;499] to "-", everything else is fine.

Currently (simplified) I have smth like this:
"#,##0, ;(#,##0,);- "

It displays my numbers as:

```<code>  1500 ->  2
  499  ->  0 (I need "-" here)
  0    ->  -
 -499  -> (0)(I need "-" here)
 -1500 -> (2)
</code>```

Any ideas?
Thanks!

Body:
I need following:

My numbers are to be divided by 1000 and rounded, negative in brackets, zeroes as "-":

  1500 ->  2
  499  ->  -
  0    ->  -
 -499  ->  -
 -1500 -> (2)

I cannot find how to transform values [-499;499] to "-", everything else is fine.

Currently (simplified) I have smth like this:
"#,##0, ;(#,##0,);- "

It displays my numbers as:

  1500 ->  2
  499  ->  0 (I need "-" here)
  0    ->  -
 -499  -> (0)(I need "-" here)
 -1500 -> (2)

Any ideas?
Thanks!

Body:
Found the solution:

 [>=500]_(* #,##0,_);[<=-500]_(* (#,##0,);_(* #,_ "-"_);_(@_)

Displays my numbers as:

 1500       ->  2
 499        ->  -
 0          ->  -
-499        ->  -
-1500       -> (2)
 blank cell -> blank cell
 text       -> text

Main problem was how to display -499 as "-"

as Jeeped posted

  [>=500]#,##0, ;[<=-500](#,##0,);-;[color3]@

did this:

 1500       ->  2
 499        ->  -
 0          ->  -
-499        ->  -- (here was the problem)
-1500       -> (2)
 blank cell -> blank cell
 text       -> text


问:
NSUnderlineStyleAttributeName Underline spacing
I want the underline to be below the text like any other normal underlining mechanism. However, with NSAttributed string it leaves holes with "g's" and "y's"

example:

How it should look:

How can I increase the spacing between the underline and label?

答:
I added a line (UIView) with height 1 and width like label, aligned to the bottom of the UILabel.</p>

```<code>    let label = UILabel()
    label.text = "underlined text"

    let spacing = 2 // will be added as negative bottom margin for more spacing between label and line

    let line = UIView()
    line.translatesAutoresizingMaskIntoConstraints = false
    line.backgroundColor = label.textColor
    label.addSubview(line)
    label.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[line]|", metrics: nil, views: ["line":line]))
    label.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[line(1)]-(\(-spacing))-|", metrics: nil, views: ["line":line]))
</code>```

Body:
I added a line (UIView) with height 1 and width like label, aligned to the bottom of the UILabel.

    let label = UILabel()
    label.text = "underlined text"

    let spacing = 2 // will be added as negative bottom margin for more spacing between label and line

    let line = UIView()
    line.translatesAutoresizingMaskIntoConstraints = false
    line.backgroundColor = label.textColor
    label.addSubview(line)
    label.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[line]|", metrics: nil, views: ["line":line]))
    label.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[line(1)]-(\(-spacing))-|", metrics: nil, views: ["line":line]))


问:
Python error message io.UnsupportedOperation: not readable
I have this code:

```<code>line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")

file = open("File.txt","w")
for i in range(3):
    file.write(line1[i])
    file.write("\n")

for line in file:
    print(line)
file.close()
</code>```

But when I try it, I get an error message like:

```<code>  File "...", line 18, in <module>
     for line in file:

UnsupportedOperation: not readable
</code>```

Why? How do I fix it?

答:
There are few modes to open file (read, write etc..)

If you want to read from file you should type file = open("File.txt","r"), if write than file = open("File.txt","w"). You need to give the right permission regarding your usage.

more modes:

r. Opens a file for reading only.

rb. Opens a file for reading only in binary format.

r+ Opens a file for both reading and writing.

rb+ Opens a file for both reading and writing in binary format.

w. Opens a file for writing only.

you can find more modes in here

ContentLicense: CC BY-SA 4.0

Body:
I have this code:

line1 = []
line1.append("xyz ")
line1.append("abc")
line1.append("mno")

file = open("File.txt","w")
for i in range(3):
    file.write(line1[i])
    file.write("\n")

for line in file:
    print(line)
file.close()

But when I try it, I get an error message like:

  File "...", line 18, in <module>
     for line in file:

UnsupportedOperation: not readable

Why? How do I fix it?


问:
passing variable value from controller to view in AngularJS
I am developing an application where i popup a window and when it gets popup the next time i will try to open it should not be opened. Next time it should open When i will close the popup then it should open.

Now for that i am using count variable and whenever it will be 1 the popup opens and whenever it is greater than or equal to 2 it shows alert. But now when i close the popup it is not resetting the value of count to 0 in view.
In JSfiddle i tried using var self = this; it works fine but when i tried it on my code it says Uncaught Exception Typeerror cannot find property 'count' defined at line self.count = 0;
How to achieve this? or any alternate solution for this?

```<code><a ui-sref-active="active" ng-click="count=count+1; connectMachine(machine, count)" ng-init="count=0" ><span><i class="fa fa-desktop fa-5x"></i></span></a>

$scope.connectMachine = function(machine, count) {
    var promise = restAPIService.connectMachineService(
            $scope.thisStudentThisBatch.guacProfileId,
            machine.connectionId, $stateParams.batchID).get();
    promise.$promise.then(function(response) {
        var json = JSON.parse(response.data);
        console.log(json.id);
        var dnsUrl = $location.absUrl().split('/');
        dnsUrl = dnsUrl[0] + '//' + dnsUrl[2];
        var apiUrl = dnsUrl + $rootScope.apiUrl + "guacamole/disconnect/"
                + json.id;
        var conn_params = $http.defaults.headers.common.Authorization
                + "++" + apiUrl;
        $scope.machineURL = response.headers.url + "&conn_params="
                + conn_params;
        var params = "height=" + screen.availHeight + ",width="
                + screen.availWidth;

        var NewWin;
        var self = this;
        if ($scope.count == 1) {
            NewWin = window.open($scope.machineURL);
        } else if ($scope.count >= 2) {
            alert("Back Off Back Off");
        }
        function checkWindow() {
            if (NewWin && NewWin.closed) {
                window.clearInterval(intervalID);
                self.count = 0;
            }
        }
        var intervalID = window.setInterval(checkWindow, 500);
    }, function(error) {
        dialogs.error("Error", error.data.error, {
            'size' : 'sm'
        });
    });
}
</code>```

答:
You can use a variable defined on $scope to trigger the value of button instead of using ng-init

HTML:

```<code><div ng-app="myApp">
    <ul ng-controller="TodoCtrl">
        <li class="list-group-item" ng-repeat="todo in todos">{{todo.text}}
            <button class="btn btn-default" ng-click="addLike($index)">value- {{count[$index]}}</button>
        </li>
    </ul>
</div>
</code>```

JS:

```<code>var myApp = angular.module('myApp', []);

function TodoCtrl($scope) {
    $scope.todos = [{
        text: 'todo one'
    }, {
        text: 'todo two',
        done: false
    }];
    $scope.count = [0, 0];
    $scope.addLike = function(index) {
        var NewWin;
        $scope.count[index] ++;
        if ($scope.count[index] == 1) {
            NewWin = window.open('https://www.google.com');
        } else if ($scope.count >= 2) {
            alert("Back Off Back Off");
        }

        function checkWindow() {
            if (NewWin && NewWin.closed) {
                window.clearInterval(intervalID);
                $scope.count[index] = 0;
                $scope.$apply();
            }
        }
        var intervalID = window.setInterval(checkWindow, 500);
    };
};
</code>```

JS Fiddle :https://jsfiddle.net/p41dLjmn/

Body:
I am developing an application where i popup a window and when it gets popup the next time i will try to open it should not be opened. Next time it should open When i will close the popup then it should open.

Now for that i am using count variable and whenever it will be 1 the popup opens and whenever it is greater than or equal to 2 it shows alert. But now when i close the popup it is not resetting the value of count to 0 in view.
In JSfiddle i tried using var self = this; it works fine but when i tried it on my code it says Uncaught Exception Typeerror cannot find property 'count' defined at line self.count = 0;
How to achieve this? or any alternate solution for this?

$scope.connectMachine = function(machine, count) {
    var promise = restAPIService.connectMachineService(
            $scope.thisStudentThisBatch.guacProfileId,
            machine.connectionId, $stateParams.batchID).get();
    promise.$promise.then(function(response) {
        var json = JSON.parse(response.data);
        console.log(json.id);
        var dnsUrl = $location.absUrl().split('/');
        dnsUrl = dnsUrl[0] + '//' + dnsUrl[2];
        var apiUrl = dnsUrl + $rootScope.apiUrl + "guacamole/disconnect/"
                + json.id;
        var conn_params = $http.defaults.headers.common.Authorization
                + "++" + apiUrl;
        $scope.machineURL = response.headers.url + "&conn_params="
                + conn_params;
        var params = "height=" + screen.availHeight + ",width="
                + screen.availWidth;

        var NewWin;
        var self = this;
        if ($scope.count == 1) {
            NewWin = window.open($scope.machineURL);
        } else if ($scope.count >= 2) {
            alert("Back Off Back Off");
        }
        function checkWindow() {
            if (NewWin && NewWin.closed) {
                window.clearInterval(intervalID);
                self.count = 0;
            }
        }
        var intervalID = window.setInterval(checkWindow, 500);
    }, function(error) {
        dialogs.error("Error", error.data.error, {
            'size' : 'sm'
        });
    });
}

Body:
You can use a variable defined on $scope to trigger the value of button instead of using ng-init

HTML:

<div ng-app="myApp">
    <ul ng-controller="TodoCtrl">
        <li class="list-group-item" ng-repeat="todo in todos">{{todo.text}}
            <button class="btn btn-default" ng-click="addLike($index)">value- {{count[$index]}}</button>
        </li>
    </ul>
</div>

JS:

var myApp = angular.module('myApp', []);

function TodoCtrl($scope) {
    $scope.todos = [{
        text: 'todo one'
    }, {
        text: 'todo two',
        done: false
    }];
    $scope.count = [0, 0];
    $scope.addLike = function(index) {
        var NewWin;
        $scope.count[index] ++;
        if ($scope.count[index] == 1) {
            NewWin = window.open('https://www.google.com');
        } else if ($scope.count >= 2) {
            alert("Back Off Back Off");
        }

        function checkWindow() {
            if (NewWin && NewWin.closed) {
                window.clearInterval(intervalID);
                $scope.count[index] = 0;
                $scope.$apply();
            }
        }
        var intervalID = window.setInterval(checkWindow, 500);
    };
};

JS Fiddle :https://jsfiddle.net/p41dLjmn/


问:
Pikaday.js: How to disbale days in calendar?
I have a calendar and I want to set a few days to disable. Does anyone have experience with this? On github it says: </p>

```<code>disableDayFn: callback function that gets passed a Date object for each day in view. Should return true to disable selection of that day.
</code>```

<p>But how can I use this? </p>

```<code>var bookingPicker = new Pikaday(
            {
                field: $(self.options.calendarInput, container)[0],
                container: $(self.options.calendarContainer, container)[0],
                minDate: new Date(),
                bound: false,
                firstDay: 1,
            onOpen: function () {
                this.disableDayFn(23); //<--- ???
            },
            onSelect: function (date) {

            },
            onDraw: function (date) {
                console.log("NEW MONTH")
            }
        }
    );
</code>```

答:
So every date you can see on the picker is passed, just do whatever checks you want in the function against that date.  Here's an example using a string array of dates that uses moment.js to qualify equality.

```<code>var validDateArray = ["2017-JAN-01", "2017-JAN-02", "2017-JAN-03"]
</code>```

in the picker:

```<code>disableDayFn: (dateToCheck: Date) => {

  if (validDateArray == undefined) {
    console.log("...validDateArray == undefined");
    return true;
  }

  let d1 = Moment(dateToCheck).format("YYYY-MMM-DD");

  for (let d2 of validDateArray) {
    if (d1 == d2) {
      console.log("...date is valid");
      return false;
    }
  }

  console.log("...date is not valid");
  return true;
}
</code>```

Body:
I have a calendar and I want to set a few days to disable. Does anyone have experience with this? On github it says:

disableDayFn: callback function that gets passed a Date object for each day in view. Should return true to disable selection of that day.

But how can I use this?

var bookingPicker = new Pikaday(
            {
                field: $(self.options.calendarInput, container)[0],
                container: $(self.options.calendarContainer, container)[0],
                minDate: new Date(),
                bound: false,
                firstDay: 1,
            onOpen: function () {
                this.disableDayFn(23); //<--- ???
            },
            onSelect: function (date) {

            },
            onDraw: function (date) {
                console.log("NEW MONTH")
            }
        }
    );

Body:
So every date you can see on the picker is passed, just do whatever checks you want in the function against that date.  Here's an example using a string array of dates that uses moment.js to qualify equality.

var validDateArray = ["2017-JAN-01", "2017-JAN-02", "2017-JAN-03"]

in the picker:

disableDayFn: (dateToCheck: Date) => {

  if (validDateArray == undefined) {
    console.log("...validDateArray == undefined");
    return true;
  }

  let d1 = Moment(dateToCheck).format("YYYY-MMM-DD");

  for (let d2 of validDateArray) {
    if (d1 == d2) {
      console.log("...date is valid");
      return false;
    }
  }

  console.log("...date is not valid");
  return true;
}


问:
Connection to local server via shell refused (Neo4j 2.1.6)
follow up to http://goo.gl/RSluPw

Can't connect to local server via the shell.

I installed neo4j-community-2.1.6 (without any modifications), started the server, and then wanted to connect via the shell (as stated here http://goo.gl/jI12RO). What am I missing?

Here is my console output:

```<code>[~/bin/neo4j]
$ ls
CHANGES.txt   NOTICE.txt    bin/          lib/
LICENSE.txt   README.txt    conf/         plugins/
LICENSES.txt  UPGRADE.txt   data/         system/

[~/bin/neo4j]
$ java -version
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)

[~/bin/neo4j]
$ ./bin/neo4j start
Using additional JVM arguments:  -server -XX:+DisableExplicitGC -Dorg.neo4j.server.properties=conf/neo4j-server.properties -Djava.util.logging.config.file=conf/logging.properties -Dlog4j.configuration=file:conf/log4j.properties -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:-OmitStackTraceInFastThrow
Starting Neo4j Server...WARNING: not changing user
process [5481]... waiting for server to be ready............................................................................... OK.
http://localhost:7474/ is ready.

[~/bin/neo4j]
$ neo4j-shell
ERROR (-v for expanded information):
    Exception creating connection to: 172.24.46.19; nested exception is:
    java.net.SocketException: Host is down

 -host      Domain name or IP of host to connect to (default: localhost)
 ...

[~/bin/neo4j]
$ neo4j-shell -v
ERROR (-v for expanded information):
    Connection refused
java.rmi.ConnectException: Connection refused to host: 172.24.46.19; nested exception is:
    java.net.ConnectException: Operation timed out
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129)
    at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
    at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
    at com.sun.proxy.$Proxy1.welcome(Unknown Source)
    at org.neo4j.shell.impl.AbstractClient.sayHi(AbstractClient.java:215)
    at org.neo4j.shell.impl.RemoteClient.findRemoteServer(RemoteClient.java:63)
    at org.neo4j.shell.impl.RemoteClient.<init>(RemoteClient.java:55)
    at org.neo4j.shell.impl.RemoteClient.<init>(RemoteClient.java:43)
    at org.neo4j.shell.ShellLobby.newClient(ShellLobby.java:165)
    at org.neo4j.shell.StartClient.startRemote(StartClient.java:297)
    at org.neo4j.shell.StartClient.start(StartClient.java:175)
    at org.neo4j.shell.StartClient.main(StartClient.java:120)
Caused by: java.net.ConnectException: Operation timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at java.net.Socket.<init>(Socket.java:425)
    at java.net.Socket.<init>(Socket.java:208)
    at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
    at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
    ... 14 more

 -host      Domain name or IP of host to connect to (default: localhost)
 -port      Port of host to connect to (default: 1337)
 ...

[~/bin/neo4j]
$
</code>```

Why is the shell trying to connect to host 172.24.46.19? The suggestions on http://goo.gl/R3iSzK also don't help.

Update 1:

I activated remote shell in neo4j.properties:

```<code># Enable shell server so that remote clients can connect via Neo4j shell.
remote_shell_enabled=true
# The network interface IP the shell will listen on (use 0.0.0 for all interfaces)
remote_shell_host=127.0.0.1
# The port the shell will listen on, default is 1337
remote_shell_port=1337
</code>```

Still no success:

```<code>$ neo4j start
Using additional JVM arguments:  -server -XX:+DisableExplicitGC -Dorg.neo4j.server.properties=conf/neo4j-server.properties -Djava.util.logging.config.file=conf/logging.properties -Dlog4j.configuration=file:conf/log4j.properties -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:-OmitStackTraceInFastThrow
Starting Neo4j Server...WARNING: not changing user
process [7104]... waiting for server to be ready............................................................................... OK.
http://localhost:7474/ is ready.
[~]
$ neo4j-shell
ERROR (-v for expanded information):
    Exception creating connection to: 172.24.46.19; nested exception is:
    java.net.SocketException: Host is down

 ...

[~]
$ neo4j-shell -host 127.0.0.1 -port 1337
ERROR (-v for expanded information):
    Exception creating connection to: 172.24.46.19; nested exception is:
    java.net.SocketException: Host is down
</code>```

Still trying to connect to 172.24.46.19.

答:
I had a similar issue, change of port from 1337 to 1338 (you can choose a  different port number) fixed it.</p>

```<code>1. Stop neo4j server
2. Enable shell properties in neo4j.conf file
   # Enable a remote shell server which Neo4j Shell clients can log in to.
   dbms.shell.enabled=true
   # The network interface IP the shell will listen on (use 0.0.0.0 for all interfaces).
   dbms.shell.host=0.0.0.0
   # The port the shell will listen on, default is 1337.
   dbms.shell.port=1338
3. start neo4j server
4. Start shell
   root@ubuntu:/etc/neo4j# neo4j-shell -port 1338
   Welcome to the Neo4j Shell! Enter 'help' for a list of commands. Please note that neo4j-shell is deprecated and to be replaced by cypher-shell.
NOTE: Remote Neo4j graph database service 'shell' at port 1338

neo4j-sh (?)$
</code>```

Body:
follow up to http://goo.gl/RSluPw

Can't connect to local server via the shell.

I installed neo4j-community-2.1.6 (without any modifications), started the server, and then wanted to connect via the shell (as stated here http://goo.gl/jI12RO). What am I missing?

Here is my console output:

[~/bin/neo4j]
$ ls
CHANGES.txt   NOTICE.txt    bin/          lib/
LICENSE.txt   README.txt    conf/         plugins/
LICENSES.txt  UPGRADE.txt   data/         system/

[~/bin/neo4j]
$ java -version
java version "1.7.0_67"
Java(TM) SE Runtime Environment (build 1.7.0_67-b01)
Java HotSpot(TM) 64-Bit Server VM (build 24.65-b04, mixed mode)

[~/bin/neo4j]
$ ./bin/neo4j start
Using additional JVM arguments:  -server -XX:+DisableExplicitGC -Dorg.neo4j.server.properties=conf/neo4j-server.properties -Djava.util.logging.config.file=conf/logging.properties -Dlog4j.configuration=file:conf/log4j.properties -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:-OmitStackTraceInFastThrow
Starting Neo4j Server...WARNING: not changing user
process [5481]... waiting for server to be ready............................................................................... OK.
http://localhost:7474/ is ready.

[~/bin/neo4j]
$ neo4j-shell
ERROR (-v for expanded information):
    Exception creating connection to: 172.24.46.19; nested exception is:
    java.net.SocketException: Host is down

 -host      Domain name or IP of host to connect to (default: localhost)
 ...

[~/bin/neo4j]
$ neo4j-shell -v
ERROR (-v for expanded information):
    Connection refused
java.rmi.ConnectException: Connection refused to host: 172.24.46.19; nested exception is:
    java.net.ConnectException: Operation timed out
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
    at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
    at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
    at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:129)
    at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:194)
    at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:148)
    at com.sun.proxy.$Proxy1.welcome(Unknown Source)
    at org.neo4j.shell.impl.AbstractClient.sayHi(AbstractClient.java:215)
    at org.neo4j.shell.impl.RemoteClient.findRemoteServer(RemoteClient.java:63)
    at org.neo4j.shell.impl.RemoteClient.<init>(RemoteClient.java:55)
    at org.neo4j.shell.impl.RemoteClient.<init>(RemoteClient.java:43)
    at org.neo4j.shell.ShellLobby.newClient(ShellLobby.java:165)
    at org.neo4j.shell.StartClient.startRemote(StartClient.java:297)
    at org.neo4j.shell.StartClient.start(StartClient.java:175)
    at org.neo4j.shell.StartClient.main(StartClient.java:120)
Caused by: java.net.ConnectException: Operation timed out
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at java.net.Socket.<init>(Socket.java:425)
    at java.net.Socket.<init>(Socket.java:208)
    at sun.rmi.transport.proxy.RMIDirectSocketFactory.createSocket(RMIDirectSocketFactory.java:40)
    at sun.rmi.transport.proxy.RMIMasterSocketFactory.createSocket(RMIMasterSocketFactory.java:147)
    at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:613)
    ... 14 more

 -host      Domain name or IP of host to connect to (default: localhost)
 -port      Port of host to connect to (default: 1337)
 ...

[~/bin/neo4j]
$

Why is the shell trying to connect to host 172.24.46.19? The suggestions on http://goo.gl/R3iSzK also don't help.

Update 1:

I activated remote shell in neo4j.properties:

# Enable shell server so that remote clients can connect via Neo4j shell.
remote_shell_enabled=true
# The network interface IP the shell will listen on (use 0.0.0 for all interfaces)
remote_shell_host=127.0.0.1
# The port the shell will listen on, default is 1337
remote_shell_port=1337

Still no success:

$ neo4j start
Using additional JVM arguments:  -server -XX:+DisableExplicitGC -Dorg.neo4j.server.properties=conf/neo4j-server.properties -Djava.util.logging.config.file=conf/logging.properties -Dlog4j.configuration=file:conf/log4j.properties -XX:+UseConcMarkSweepGC -XX:+CMSClassUnloadingEnabled -XX:-OmitStackTraceInFastThrow
Starting Neo4j Server...WARNING: not changing user
process [7104]... waiting for server to be ready............................................................................... OK.
http://localhost:7474/ is ready.
[~]
$ neo4j-shell
ERROR (-v for expanded information):
    Exception creating connection to: 172.24.46.19; nested exception is:
    java.net.SocketException: Host is down

 ...

[~]
$ neo4j-shell -host 127.0.0.1 -port 1337
ERROR (-v for expanded information):
    Exception creating connection to: 172.24.46.19; nested exception is:
    java.net.SocketException: Host is down

Still trying to connect to 172.24.46.19.

Body:
I had a similar issue, change of port from 1337 to 1338 (you can choose a  different port number) fixed it.

1. Stop neo4j server
2. Enable shell properties in neo4j.conf file
   # Enable a remote shell server which Neo4j Shell clients can log in to.
   dbms.shell.enabled=true
   # The network interface IP the shell will listen on (use 0.0.0.0 for all interfaces).
   dbms.shell.host=0.0.0.0
   # The port the shell will listen on, default is 1337.
   dbms.shell.port=1338
3. start neo4j server
4. Start shell
   root@ubuntu:/etc/neo4j# neo4j-shell -port 1338
   Welcome to the Neo4j Shell! Enter 'help' for a list of commands. Please note that neo4j-shell is deprecated and to be replaced by cypher-shell.
NOTE: Remote Neo4j graph database service 'shell' at port 1338

neo4j-sh (?)$


问:
CSS center columns of text
I have some song lyrics in a
 with the following class:

```<code>.lyrics
{
    /* position */
    margin: 40px;

    /* text */
    font-size: 18px;
    text-align: center;
    column-width: 300px;
    column-gap: 0;
    column-fill: auto;
    height: 420px;
    max-height: 420px;
}
</code>```

Width of the entire div is constrained to 1120px, and height to 520px.

If lyrics fill 3 columns, it looks fine. However, if lyrics fill 2 columns, space for a third column is left empty.

Is there a way to leave 3-column lyrics as they are, but to center 2-column lyrics, keeping column spacing the same, without resorting to slicing lyrics in javascript and processing the layout myself?

Examples

Correct behaviour with 3-columns: https://jsfiddle.net/udc9d1go/2/

Incorrect behaviour with 2-columns: https://jsfiddle.net/45f23o82/

答:
I ended up writing some ES to increase left and right margins for the div in case text has a certain number of lines. This seems a fine work-around.

```<code>calculateMarginForLyrics = function(lyrics)
{
    // count <br /> tags and count </p> tags twice (except last one)
    var nLines = lyrics.match(/<br \/>/g || []).length + (lyrics.match(/<\/p>/g || []).length - 1) * 2;

    if (nLines <= 12) // fits in one column
        return 350;
    else if (nLines <= 24) // fits in two columns
        return 200;

    // fits in three columns
    return 40;
}
</code>```

Result: JSFiddle

Title: CSS center columns of text

Body:
I have some song lyrics in a
 with the following class:

.lyrics
{
    /* position */
    margin: 40px;

    /* text */
    font-size: 18px;
    text-align: center;
    column-width: 300px;
    column-gap: 0;
    column-fill: auto;
    height: 420px;
    max-height: 420px;
}

Width of the entire div is constrained to 1120px, and height to 520px.

If lyrics fill 3 columns, it looks fine. However, if lyrics fill 2 columns, space for a third column is left empty.

Is there a way to leave 3-column lyrics as they are, but to center 2-column lyrics, keeping column spacing the same, without resorting to slicing lyrics in javascript and processing the layout myself?

Examples

Correct behaviour with 3-columns: https://jsfiddle.net/udc9d1go/2/

Incorrect behaviour with 2-columns: https://jsfiddle.net/45f23o82/

Body:
I ended up writing some ES to increase left and right margins for the div in case text has a certain number of lines. This seems a fine work-around.

calculateMarginForLyrics = function(lyrics)
{
    // count <br /> tags and count </p> tags twice (except last one)
    var nLines = lyrics.match(/<br \/>/g || []).length + (lyrics.match(/<\/p>/g || []).length - 1) * 2;

    if (nLines <= 12) // fits in one column
        return 350;
    else if (nLines <= 24) // fits in two columns
        return 200;

    // fits in three columns
    return 40;
}

Result: JSFiddle


问:
Push specific row values to result array if row column value matches search string
I have an array with a lot of different $keys and $values

What I did is create a form that allows the user to insert an emailadres.

Then a foreach loop start running and saves the values of every found emailaddress to a new array

This is the outcome of that array:

```<code><?php
Array
(
    [0] => email@email.com
    [1] => 103646
    [2] => Company
    [3] => 1140
    [4] => email@email.com
    [5] => 103689
    [6] => Company
    [7] => 3400
)
?>
</code>```

What I would like it that every $value has it's own $key

I don't really know how to accomplish that.

This is my array making script:

```<code><?php
$saved = array();
$input = $_GET['emailaddress'];
foreach ($data as $files){
    $bedrijf = $files['Name'];
    $bill = $files['Bill'];
    $amount = $files['Amount'];
    $email = $files['email'];
    if ($email == $input){
        foreach($files as $values){
            $saved[] = $values;
        }

    }
}
echo'```';
print_r($saved);
echo'```';
?>
</code>```

答:
This will provide the desired multi-dimensional associative array without the code bloat of manually incrementing indexes or declaring one-time-use variables:</p>
```<code>foreach ($data as $files) {
    if ($files['email'] === $input) {
        $saved[] = [
            'Email' => $files['email'],
            'Amount' => $files['Amount'],
            'Bill' => $files['Bill'],
            'Name' => $files['Name']
        ];
    }
}
</code>```

Body:
I have an array with a lot of different $keys and $values

What I did is create a form that allows the user to insert an emailadres.

Then a foreach loop start running and saves the values of every found emailaddress to a new array

This is the outcome of that array:

<?php
Array
(
    [0] => email@email.com
    [1] => 103646
    [2] => Company
    [3] => 1140
    [4] => email@email.com
    [5] => 103689
    [6] => Company
    [7] => 3400
)
?>

What I would like it that every $value has it's own $key

I don't really know how to accomplish that.

This is my array making script:

<?php
$saved = array();
$input = $_GET['emailaddress'];
foreach ($data as $files){
    $bedrijf = $files['Name'];
    $bill = $files['Bill'];
    $amount = $files['Amount'];
    $email = $files['email'];
    if ($email == $input){
        foreach($files as $values){
            $saved[] = $values;
        }

    }
}
echo'
';
print_r($saved);
echo'
';
?>

Body:
This will provide the desired multi-dimensional associative array without the code bloat of manually incrementing indexes or declaring one-time-use variables:

foreach ($data as $files) {
    if ($files['email'] === $input) {
        $saved[] = [
            'Email' => $files['email'],
            'Amount' => $files['Amount'],
            'Bill' => $files['Bill'],
            'Name' => $files['Name']
        ];
    }
}


答:
You are opening the file as "w", which stands for writable.

Using "w" you won't be able to read the file. Use the following instead:

```<code>file = open("File.txt", "r")
</code>```

Additionally, here are the other options:

```<code>"r"   Opens a file for reading only.
"r+"  Opens a file for both reading and writing.
"rb"  Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w"   Opens a file for writing only.
"a"   Open for writing. The file is created if it does not exist.
"a+"  Open for reading and writing.  The file is created if it does not exist.
</code>```

Title: Python error message io.UnsupportedOperation: not readable

Body:
You are opening the file as "w", which stands for writable.

Using "w" you won't be able to read the file. Use the following instead:

file = open("File.txt", "r")

Additionally, here are the other options:

"r"   Opens a file for reading only.
"r+"  Opens a file for both reading and writing.
"rb"  Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w"   Opens a file for writing only.
"a"   Open for writing. The file is created if it does not exist.
"a+"  Open for reading and writing.  The file is created if it does not exist.


问:
Error: <Route> elements are for router configuration only and should not be rendered in react-router v4
Tried to upgrade react-router from 2 to 4 and broke it and now cant render my app.

getting various errors (the most recent is: <Route> elements are for router configuration only and should not be rendered)

I have also had the error where my ./ route renders fine but every other route blows up when I refresh and says Cannot GET /randomRoute

I am creating a react app and my main index.js file (where I include ReactDOM.render) also includes the routes and looks like so:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import { Route } from 'react-router';
import { BrowserRouter as Router, Match, HashRouter } from 'react-router-dom'
import Header from './components/header';

import './index.scss';

class App extends React.Component {

  render() {
    return (
      <Router  history={HashRouter}>
        <div>
          <Route path={"/"} component={Header} />
        </div>
      </Router>
    );
  }
}

ReactDOM.render(<App />,
    document.getElementById('content'));
</code>```

why would I be getting that current error and can anyone give me a simple start to the basics I need to include just to get routing working? it worked in version 2 but I wanted to upgrade and now cant get it working again

答:
Well, in react router v4 the API is different. You have to define it in your index.js file like this,

```<code>ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
      <div>
        <Switch>
            <Route path="/path/one" component={ComponentOne} />
            <Route path="/path/two" component={ComponentTwo} />
            <Route path="/" component={IndexComponent} />
        </Switch>
      </div>
    </BrowserRouter>
  </Provider>
  , document.querySelector('.container'));
</code>```

Make sure the order is important here. Put the most generic one at last. Hope this helps. Happy coding !

Body:
Tried to upgrade react-router from 2 to 4 and broke it and now cant render my app.

getting various errors (the most recent is: <Route> elements are for router configuration only and should not be rendered)

I have also had the error where my ./ route renders fine but every other route blows up when I refresh and says Cannot GET /randomRoute

I am creating a react app and my main index.js file (where I include ReactDOM.render) also includes the routes and looks like so:

import React from 'react';
import ReactDOM from 'react-dom';
import { Route } from 'react-router';
import { BrowserRouter as Router, Match, HashRouter } from 'react-router-dom'
import Header from './components/header';

import './index.scss';

class App extends React.Component {

  render() {
    return (
      <Router  history={HashRouter}>

          <Route path={"/"} component={Header} />

      </Router>
    );
  }
}

ReactDOM.render(<App />,
    document.getElementById('content'));

why would I be getting that current error and can anyone give me a simple start to the basics I need to include just to get routing working? it worked in version 2 but I wanted to upgrade and now cant get it working again

Body:
Well, in react router v4 the API is different. You have to define it in your index.js file like this,

ReactDOM.render(
  <Provider store={createStoreWithMiddleware(reducers)}>
    <BrowserRouter>
      <div>
        <Switch>
            <Route path="/path/one" component={ComponentOne} />
            <Route path="/path/two" component={ComponentTwo} />
            <Route path="/" component={IndexComponent} />
        </Switch>
      </div>
    </BrowserRouter>
  </Provider>
  , document.querySelector('.container'));

Make sure the order is important here. Put the most generic one at last. Hope this helps. Happy coding !


问:
My values are not being inserted into database using this command
```<code>$sql="INSERT INTO prescription
      (username,phone,procedure,address,emailid,reviews,followups,nextappointment)
      VALUES
      ("$username","$phone","$procedure","$address","$emailid","$reviews",$followups,"$nextappointment")";
</code>```

答:
You should change "" is there know that one should change single quote ''.

for example below:

```<code>$sql = 'INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)
    VALUES("$username","$phone","$procedure","$address","$emailid","$reviews",$followups,"$nextappointment")';
</code>```

Hope it will helps you

Body:
You should change "" is there know that one should change single quote ''.

for example below:

$sql = 'INSERT INTO prescription(username,phone,procedure,address,emailid,reviews,followups,nextappointment)
    VALUES("$username","$phone","$procedure","$address","$emailid","$reviews",$followups,"$nextappointment")';

Hope it will helps you


问:
Sonar analysis difference in two version(5.6 & 6.3)
We have two Environment of Sonar having versions (5.6 & 6.3).

We have set up all the sonar quality profiles,types,rules,severity identical in both environments.

But when we do analysis from both versions on the same repository, we are getting difference in the sonar analysis and its issues severities.

Please help us to find where the issue may persists.

答:
Generally speaking:

only because you have the same version of SonarQube, does not mean that you are using the same Plugins.

Even tough the plugins have the same rules, they are also differ from release to release. Plugin developers find bugs in the rules, or there is a big change of severity, and movement from category "bugs" to "code smell"

so, as long as your server is not running the same plugin versions - you can not compare the outcome of those two!


问:
Class 'Subject<T>' incorrectly extends base class 'Observable<T>'
For the sake of preventing downvotes, I will lorem-ipsum-elaborate on this error message:

I am using angular4 and out of the blue (well actually it's rather grey today) this error occured. Can anybody help? I already found similar issues on github, but no answers as to resolve the situation (I have tried "npm update" and "npm install")

Typescript version is 2.4.0

Additional error-messages are:

Class 'WebSocketSubject' incorrectly extends base class 'AnonymousSubject'

Types of property 'lift' are incompatible.

The location of the original error mnessage is given as
"./node_modules/rxjs/Subject.d.ts"

答:
Think I solved it by the help of Haseoh's comment:

in the compiler-options for typescript (tsconfig.json) set

```<code>    "skipLibCheck": true
</code>```

this is obviously a hack, but it solves my issue and I have grown accustomed to this kind of life since I started using angular2

Body:
Think I solved it by the help of Haseoh's comment:

in the compiler-options for typescript (tsconfig.json) set

    "skipLibCheck": true

this is obviously a hack, but it solves my issue and I have grown accustomed to this kind of life since I started using angular2


问:
HTML form - PHP not inserting into Database correctly
i'm only tring to make a form work.
Its a similar for than i am fillin now: question, text, tags.

Fine,

this is when i print the form

```<code>function imprimir_formulario_pregunta(){
    $html = '<form id="pregunta" name ="pregunta" method="post" action="preguntas.php">';
    $html .= '<h2>Pregunta</h2>';

    $html .= '<input name="q" id="q" type="text" value=" "></input>';
    $html .= '<h2>Explica tu duda</h2>';
    $html .= '<textarea name="texto" id="texto" /
                    ></textarea>';
    $html .= '<h2>Etiquetas (separadas por comas)</h2>';
    $html .= '<input name="tags" id="tags"/>';
    $html .= '<input name="responde_a" style="display:none;" id="responde_a" value="0"/>';

    $html .= '<button name="pregunta" id="pregunta" type="submit" >Publicar</button>';

    $html .= '</form>';

    echo $html;

}
</code>```

this is when i recive data

```<code>if(isset($_POST['pregunta'])){
    $p_title = $_POST['q'];
    $p_text = $_POST['texto'];
    $p_et = $_POST['etiquetas'];
    $p_resp = $_POST['responde_a'];
    post_pregunta($p_title,$p_text, $p_et, $p_resp);
</code>```

this is when i process data

```<code>function obtener_id_pregunta($p,$t){
    $consulta = mysql_query("SELECT * FROM preguntas WHERE pregunta='$p' && texto='$t'");
    while($item = mysql_fetch_array($consulta)){
        return $item['id'];
    }
}

function    post_pregunta($a,$t,$et,$r){
    mostrar_notificacion("hemos entrado");
    //// ******
    if($a != '' && $t != ''){
        $b = $a;
        guardar_pregunta($b,$t,$r);
        $id = obtener_id_pregunta($b,$t);
        $temp = new etiqueta(0, '');
        $basura = $temp->guardar_etiquetas($et, $id, $_SESSION['id']);

    }else
        mostrar_notificacion("hemos salido $a $t");
}

function guardar_pregunta($p,$t,$r){
    $id_tmp = $_SESSION['id'];
    $insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('$p','$t','$id_tmp',NOW(),'$r')";
    $qry = mysql_query($insert);
    if(mysql_affected_rows())
    {
        mostrar_notificacion("La pregunta $p ($t)($r) se guardo");
        return true;
    }
    else
    {
        mostrar_notificacion("Error Ingresando datos");
        return false;
    }
    return false;
}
</code>```

Result:

I get the insert in the database done, but the 'q' field has a '' value....

Notes:
It looses the value in the step ** because it enters in the condition, but it doesn't in the next one wich is the same question...

Please tell me you have my answer, been too long on this.. and i need it done this week for class

Thanks in advance

答: Use echo to print out the value of the troublesome variable ($_POST['q'], $p_title, $a) at every stage. Then you will see when it gets a value you weren't expecting.

ContentLicense: CC BY-SA 2.5

Body:
i'm only tring to make a form work.
Its a similar for than i am fillin now: question, text, tags.

Fine,

this is when i print the form

function imprimir_formulario_pregunta(){
    $html = '<form id="pregunta" name ="pregunta" method="post" action="preguntas.php">';
    $html .= '
Pregunta
';

    $html .= '<input name="q" id="q" type="text" value=" "></input>';
    $html .= '
Explica tu duda
';
    $html .= '<textarea name="texto" id="texto" /
                    ></textarea>';
    $html .= '
Etiquetas (separadas por comas)
';
    $html .= '<input name="tags" id="tags"/>';
    $html .= '<input name="responde_a" style="display:none;" id="responde_a" value="0"/>';

    $html .= '<button name="pregunta" id="pregunta" type="submit" >Publicar</button>';

    $html .= '</form>';

    echo $html;

}

this is when i recive data

if(isset($_POST['pregunta'])){
    $p_title = $_POST['q'];
    $p_text = $_POST['texto'];
    $p_et = $_POST['etiquetas'];
    $p_resp = $_POST['responde_a'];
    post_pregunta($p_title,$p_text, $p_et, $p_resp);

this is when i process data

function obtener_id_pregunta($p,$t){
    $consulta = mysql_query("SELECT * FROM preguntas WHERE pregunta='$p' && texto='$t'");
    while($item = mysql_fetch_array($consulta)){
        return $item['id'];
    }
}

function    post_pregunta($a,$t,$et,$r){
    mostrar_notificacion("hemos entrado");
    //// ******
    if($a != '' && $t != ''){
        $b = $a;
        guardar_pregunta($b,$t,$r);
        $id = obtener_id_pregunta($b,$t);
        $temp = new etiqueta(0, '');
        $basura = $temp->guardar_etiquetas($et, $id, $_SESSION['id']);

    }else
        mostrar_notificacion("hemos salido $a $t");
}

function guardar_pregunta($p,$t,$r){
    $id_tmp = $_SESSION['id'];
    $insert = "INSERT INTO preguntas (pregunta,texto,id_usuario,fecha,responde_a) VALUES ('$p','$t','$id_tmp',NOW(),'$r')";
    $qry = mysql_query($insert);
    if(mysql_affected_rows())
    {
        mostrar_notificacion("La pregunta $p ($t)($r) se guardo");
        return true;
    }
    else
    {
        mostrar_notificacion("Error Ingresando datos");
        return false;
    }
    return false;
}

Result:

I get the insert in the database done, but the 'q' field has a '' value....

Notes:
It looses the value in the step ** because it enters in the condition, but it doesn't in the next one wich is the same question...

Please tell me you have my answer, been too long on this.. and i need it done this week for class

Thanks in advance


问:
How To redirect after i loggin to curl script
```<code><?php
$username = "";
$password = "";
$url = "https://wordpress.com/wp-login.php";
$cookie = dirname(__FILE__)."/cookie.txt";

$postdata = "log=".$username."&pwd=".$password."&rememberme=forever&wp-submit=Log+In&redirect_to=https%3A%2F%2Fwordpress.com%2F&testcookie=1
";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url );

curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, "https://wordpress.com/wp-login.php?redirect_to=https%3A%2F%2Fwordpress.com%2F");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);

$result = curl_exec ($ch);
if(!$result) {
    echo "erro".curl_error($ch);
}
if($result) {

    {

    curl_setopt($ch, CURLOPT_POST, 1); // change back to GET
    curl_setopt($ch, CURLOPT_URL, 'https://wordpress.com/me'); // set url for next request

    $exec = curl_exec($ch); // make request to buy on the same handle with the current login session
}
}
curl_close($ch);
unset($ch);
?>
</code>```

<p>i want to be redirected to a new url after i login successfully to curl script (https://wordpress.com/me). am getting nothing on the screen after i run the code on a localhost. also i am not able to view anything on the browser but the cookies are been inserted to cookie.txt file </p>

答:
```<code>$result = curl_exec ($ch);
if(!$result) {
    echo "erro".curl_error($ch);
}
if($result) {
curl_setopt ($ch, CURLOPT_URL, "https://wordpress.com/me" );
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
echo $resulttwo = curl_exec ($ch);

if(!$resulttwo) {
    echo "erro".curl_error($ch);
}
    //header("Location: https://wordpress.com/me");
//exit();
}
curl_close($ch);
unset($ch);

?>
</code>```

i have tried this but when i reload the browser tab i get only wordpress icon  at the top left . Any ideas on how to display full wordpress user profile on the browser?

Body:
<?php
$username = "";
$password = "";
$url = "https://wordpress.com/wp-login.php";
$cookie = dirname(__FILE__)."/cookie.txt";

$postdata = "log=".$username."&pwd=".$password."&rememberme=forever&wp-submit=Log+In&redirect_to=https%3A%2F%2Fwordpress.com%2F&testcookie=1
";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url );

curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, "https://wordpress.com/wp-login.php?redirect_to=https%3A%2F%2Fwordpress.com%2F");
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);

$result = curl_exec ($ch);
if(!$result) {
    echo "erro".curl_error($ch);
}
if($result) {

    {

    curl_setopt($ch, CURLOPT_POST, 1); // change back to GET
    curl_setopt($ch, CURLOPT_URL, 'https://wordpress.com/me'); // set url for next request

    $exec = curl_exec($ch); // make request to buy on the same handle with the current login session
}
}
curl_close($ch);
unset($ch);
?>

i want to be redirected to a new url after i login successfully to curl script (https://wordpress.com/me). am getting nothing on the screen after i run the code on a localhost. also i am not able to view anything on the browser but the cookies are been inserted to cookie.txt file

Body:
$result = curl_exec ($ch);
if(!$result) {
    echo "erro".curl_error($ch);
}
if($result) {
curl_setopt ($ch, CURLOPT_URL, "https://wordpress.com/me" );
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
echo $resulttwo = curl_exec ($ch);

if(!$resulttwo) {
    echo "erro".curl_error($ch);
}
    //header("Location: https://wordpress.com/me");
//exit();
}
curl_close($ch);
unset($ch);

?>

i have tried this but when i reload the browser tab i get only wordpress icon  at the top left . Any ideas on how to display full wordpress user profile on the browser?


问:
Creating own mail provider for Laravel 5.4
Sometimes we have to integrate custom mail provider. But Laravel has a fixed list of them. Here they are:

SMTP

sendmail

ses

Mailgun

Mandrill

Sparkpost

Instructions for these drivers you can find in framework/src/Illuminate/Mail/TransportManager.php

The problem is that those instructions are fixed. Of course you can modify vendor-file but will be a dirty hack. So In the answer I'll provide some instruction how to implement your own custom mail driver in right way.

答:
First of all we have to create custom Transport for our mailer.

Our mailer will communicate with another server by some API interface. File bellow is a model so I've put it to my Model's folder. If you haven't separate folder for models you can just put the file into app directory.

Lets call it SmithTransport.php:

```<code><?php

use GuzzleHttp\ClientInterface;
use Illuminate\Mail\Transport\Transport;

class SmithTransport extends Transport
{
    protected $client;

    protected $key;

    protected $domain;

    protected $url;

    public function __construct(ClientInterface $client, $key, $domain)
    {
        $this->key = $key;
        $this->client = $client;
        $this->setDomain($domain);
    }

    public function send(Swift_Mime_Message $message, &$failedRecipients = null)
    {
        $this->beforeSendPerformed($message);

        $options = ['auth' => ['api', $this->key]];

        $message->setBcc([]);

        $from_email = '';
        $from_name = '';
        $to_email = '';
        $to_name = '';

        foreach ($message->getFrom() as $email => $name) {
            $from_email = $email;
            $from_name = $name;
        }

        foreach ($message->getTo() as $email => $name) {
            $to_email = $email;
            $to_name = $name;
        }

        $options['form_params'] = [
            'from_email' => $from_email,
            'from_name'  => $from_name,
            'to_email'   => $to_email,
            'to_name'    => $to_name,
            'subject'    => $message->getSubject(),
            'body'       => $message->getBody()
        ];

        return $this->client->post($this->url, $options);
    }

    public function getKey()
    {
        return $this->key;
    }

    public function setKey($key)
    {
        return $this->key = $key;
    }

    public function getDomain()
    {
        return $this->domain;
    }

    public function setDomain($domain)
    {
        $this->url = 'https://api.mymailer.com/send?key=' . $this->key;

        return $this->domain = $domain;
    }
}
</code>```

Next step is extending TransportManager. Because we have to add instructions for our custom Transport.

So it will be SmithTransportManager.php in model's directory or in app directory if you haven't separate directory for models.

```<code><?php

use Illuminate\Mail\TransportManager;

class SmithTransportManager extends TransportManager
{
    protected function createSmithDriver()
    {
        $config = $this->app['config']->get('services.smith', []);

        return new SmithTransport(
            $this->guggle($config),
            $config['secret'], $config['domain']
        );
    }

}
</code>```

Next step is extending existing MailServiceProvider.

So our provider will be in app/Providers/MailServiceProvider.php

```<code><?php namespace App\Providers;

use Illuminate\Mail\MailServiceProvider as MailProvider;

class MailServiceProvider extends MailProvider
{
    protected function registerSwiftTransport()
    {
        $this->app->singleton('swift.transport', function ($app) {
            return new \SmithTransportManager($app);
        });
    }

}
</code>```

And the final step is modifying config files.

In the config/app.php

you have to remove (or comment line) standard Illuminate\Mail\MailServiceProvider::class,

And add App\Providers\MailServiceProvider::class, to the providers section.

In the config/services.php we have to add config getters:

```<code>'smith' => [
    'domain' => env('SMITH_DOMAIN'),
    'secret' => env('SMITH_SECRET'),
],
</code>```

That's all! Hope it helps 'cause I didn't find any information in the docs of somewhere else about custom MailTransport.

Body:
First of all we have to create custom Transport for our mailer.

Our mailer will communicate with another server by some API interface. File bellow is a model so I've put it to my Model's folder. If you haven't separate folder for models you can just put the file into app directory.

Lets call it SmithTransport.php:

<?php

use GuzzleHttp\ClientInterface;
use Illuminate\Mail\Transport\Transport;

class SmithTransport extends Transport
{
    protected $client;

    protected $key;

    protected $domain;

    protected $url;

    public function __construct(ClientInterface $client, $key, $domain)
    {
        $this->key = $key;
        $this->client = $client;
        $this->setDomain($domain);
    }

    public function send(Swift_Mime_Message $message, &$failedRecipients = null)
    {
        $this->beforeSendPerformed($message);

        $options = ['auth' => ['api', $this->key]];

        $message->setBcc([]);

        $from_email = '';
        $from_name = '';
        $to_email = '';
        $to_name = '';

        foreach ($message->getFrom() as $email => $name) {
            $from_email = $email;
            $from_name = $name;
        }

        foreach ($message->getTo() as $email => $name) {
            $to_email = $email;
            $to_name = $name;
        }

        $options['form_params'] = [
            'from_email' => $from_email,
            'from_name'  => $from_name,
            'to_email'   => $to_email,
            'to_name'    => $to_name,
            'subject'    => $message->getSubject(),
            'body'       => $message->getBody()
        ];

        return $this->client->post($this->url, $options);
    }

    public function getKey()
    {
        return $this->key;
    }

    public function setKey($key)
    {
        return $this->key = $key;
    }

    public function getDomain()
    {
        return $this->domain;
    }

    public function setDomain($domain)
    {
        $this->url = 'https://api.mymailer.com/send?key=' . $this->key;

        return $this->domain = $domain;
    }
}

Next step is extending TransportManager. Because we have to add instructions for our custom Transport.

So it will be SmithTransportManager.php in model's directory or in app directory if you haven't separate directory for models.

<?php

use Illuminate\Mail\TransportManager;

class SmithTransportManager extends TransportManager
{
    protected function createSmithDriver()
    {
        $config = $this->app['config']->get('services.smith', []);

        return new SmithTransport(
            $this->guggle($config),
            $config['secret'], $config['domain']
        );
    }

}

Next step is extending existing MailServiceProvider.

So our provider will be in app/Providers/MailServiceProvider.php

<?php namespace App\Providers;

use Illuminate\Mail\MailServiceProvider as MailProvider;

class MailServiceProvider extends MailProvider
{
    protected function registerSwiftTransport()
    {
        $this->app->singleton('swift.transport', function ($app) {
            return new \SmithTransportManager($app);
        });
    }

}

And the final step is modifying config files.

In the config/app.php

you have to remove (or comment line) standard Illuminate\Mail\MailServiceProvider::class,

And add App\Providers\MailServiceProvider::class, to the providers section.

In the config/services.php we have to add config getters:

'smith' => [
    'domain' => env('SMITH_DOMAIN'),
    'secret' => env('SMITH_SECRET'),
],

That's all! Hope it helps 'cause I didn't find any information in the docs of somewhere else about custom MailTransport.


问:
Parallel programming with threads in Java

Parallel programming was possible in Java only from Java 7 with the
  advent of Join/Fork framework.

Let's say in Java, using ExecutorService I create a thread pool of say 4 threads and submit to it say 10 tasks which means 4 threads will start executing the 4 tasks and other 6 tasks will be picked up by threads as and when any thread finishes its task.

Let's assume I have a quad processor having 4 cores, I know a thread can be run on a single core(not taking hyper-threading concept here) so will all my 4 threads work in parallel, 1 thread running on 1 core? Isn't it a parallel programming?

EDIT: Source of reading  - This is the Java 8 playlist where in chapter 1 it was referred that parallel programming was possible from Java 7 onwards.

答:
There is a misconception on your end.

I read that parallel programming was possible in Java only from Java 7 with the advent of Join/Fork framework.

That is wrong. The Join/Fork statement is simply yet another abstraction layer that gives you more powerful concepts to work with - compared to "bare metal" threads.

Isn't it a parallel programming?

You have outlined clearly that your tasks will go into a pool that supports 4 threads; and that your hardware should support 4 threads as well. So that work will happen in parallel. And please not: Fork/Join is not the same as ExecutorService. Instead, both are advanced concepts; intended to make "parallel programming" easier for you.

After briefly listening into the video linked in the question: the tutorial  is about the fact that Java8 added streams, and on top of that parallel streams (which use the Fork/Join framework underneath - that one was introduced with Java 7).

In any case, that video emphasizes that parallel program gets much much simpler compared to earlier versions of Java. So it is not at all about introducing something that wasn't possible before - but about providing new more powerful abstractions that make it easier to do such things.


问:
Single piece of content, multiple URLs?
I have a use case that I could use some advice on.

We publish multiple products, each of which has it's own subtree on the site. Generally, a piece of content gets published to just a single product, e.g. a news article gets published to product A and can be accessed at one URL.

However, sometimes we have content that we want to publish to multiple products, e.g. a single news article gets published to products A, B, and C and will be available at 3 different URLs.

With our current CMS we end up doing this by copying and pasting the content, which is a hassle for editors, especially if the content needs to be updated.

An ideal scenario would be where and editor edits the content in one place, specifies the products to publish to, and the content is served by more than one URL and with a template that is product-specific.

It seems that RoutablePageMixin could be useful here, but I'm not sure how to handle letting the editor specify the destination products and making the routing aware of that choice.

Has anyone solved a similar problem using Wagtail?

答:
I have solved a similar problem in Wagtail, the RoutablePageMixin is the key to solving this problem.

If you have /blog/A/slug-product/, /blog/B/slug-product/, /blog/C/slug-product/ , then you can get the slug value slug-product here, then use this value to search the distinct content in your db.

```<code>class BlogPage(RoutablePageMixin, Page):
    def get_posts(self):
        return PostPage.objects.descendant_of(self).live()
    @route(r'^(\d{4})/(\d{2})/(\d{2})/(.+)/$')
    def post_by_date_slug(self, request, year, month, day, slug, *args, **kwargs):
        post_page = self.get_posts().filter(slug=slug).first()
        return Page.serve(post_page, request, *args, **kwargs)
</code>```

As you can see, I did not use the date info of the url but the slug value to get the blog post object, you can follow the pattern here to use regex to match the url you want.

If the slug values in urls are also different, this solution might not work very well, but in most cases, this solution can work fine.

I have written a blog post talking about how to use RoutablePageMixin to make the page routable, you can check this link if you wang to get more about RoutablePageMixin.

Routable Page

Title: Single piece of content, multiple URLs?

Body:
I have solved a similar problem in Wagtail, the RoutablePageMixin is the key to solving this problem.

If you have /blog/A/slug-product/, /blog/B/slug-product/, /blog/C/slug-product/ , then you can get the slug value slug-product here, then use this value to search the distinct content in your db.

class BlogPage(RoutablePageMixin, Page):
    def get_posts(self):
        return PostPage.objects.descendant_of(self).live()
    @route(r'^(\d{4})/(\d{2})/(\d{2})/(.+)/$')
    def post_by_date_slug(self, request, year, month, day, slug, *args, **kwargs):
        post_page = self.get_posts().filter(slug=slug).first()
        return Page.serve(post_page, request, *args, **kwargs)

As you can see, I did not use the date info of the url but the slug value to get the blog post object, you can follow the pattern here to use regex to match the url you want.

If the slug values in urls are also different, this solution might not work very well, but in most cases, this solution can work fine.

I have written a blog post talking about how to use RoutablePageMixin to make the page routable, you can check this link if you wang to get more about RoutablePageMixin.

Routable Page


问:
IdentityServer 4 and sso
I try to implement sso using IdentityServer4. I use standard examples from its docs.
I have three applications.

Application A -- identityserver implementation that configured using asp.net identity and entity framework.

Application B, C -- web-applications as clients.

Flow:

I go to an secured action of application A and next I redirect to sign in form of identityserver, enter my credential and i redirect back to my client -- it's ok. When next i open any secured action of application B i again redirect to sign in form of idenityserver.

So my question

Is it correct behavior? I just think that sso developed as signing in one place and then automatically login from other related. So if i am wrong please correct me but if not please give me any help what could I missed?

Thanks!

答:
It is the correct behavior.The token is given for an application
  specific and will only work for that application only.

When you define your client,your each client will have it's own client id and secret and allowed scopes. So for any client ,it will be different client ID  and secret. And then there is different flow based on grant types

Title: IdentityServer 4 and sso


问:
Synchronous Call in WSO2 ESB in iterator mediator
Is there any way to make synchronous call of all the codes written inside the iterator mediator in esb wso2?</p>

答: Are you using send mediator? If yes, use call mediator instead, which is synchronous. </p>


问:
Verify interactions in rxjava subscribers
Picture the situation in an MVP pattern where your presenter subscribes to a service returning an observer:

```<code>public void gatherData(){
   service.doSomeMagic()
      .observeOn(Schedulers.io())
      .subscribeOn(AndroidSchedulers.mainThread())
      .subscribe(new TheSubscriber());
}
</code>```

Now the class TheSubscriber calls onNext a method from the view, say:

```<code>@Override public void onNext(ReturnValue value) {
  view.displayWhatever(value);
}
</code>```

Now, in my unit test I would like to verify that when the method gatherData() is called on a non-erroneous situation, the view's method displayWhatever(value) is called.

The question:

Is there a clean way to do this?

Background:

I'm using mockito to verify the interactions and a lot more of course

Dagger is injecting the entire presenter except for TheSubscriber

What have I tried:

Inject the subscriber and mock it in the tests. Looks a bit dirty to me, because if I want to change the way the presenter interacts with the service (Say not Rx) then I need to change a lot of tests and code.

Mock the entire service. This was not so bad, but requires me to mock a lot of methods and I didn't quite reach what I wanted.

Looked up around the internet, but no one seems to have a clean straight way of doing this

Thanks for the help

答:
I know its pretty late but may it helps someone, cause i searched pretty long for a solution to your question :D

For me it worked out to add a Observable.Transformer<T, T> as followed:

```<code>    void gatherData() {
        service.doSomeMagic()
          .compose(getSchedulerTransformer())
          .subscribe(view::displayValue);
    }

    private <T> Observable.Transformer<T, T> getSchedulerTransformer() {
        if (mTransformer == null) {
            mTransformer = (Observable.Transformer<T, T>) observable -> observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

        return mTransformer;
    }

    void setSchedulerTransformer(Observable.Transformer<Observable<?>, Observable<?>> transformer) {
        mTransformer = transformer;
    }
</code>```

And to set the Transformer just I just passed this:

```<code>setSchedulerTransformer(observable -> {
            if (observable instanceof Observable) {
                Observable observable1 = (Observable) observable;
                return observable1.subscribeOn(Schedulers.immediate())
                        .observeOn(Schedulers.immediate());
            }
            return null;
        });
</code>```

So just add a @Before method in your test and call presenter.setSchedulerTransformer and it should be able to test this :)

hope this helps and is somehow understandable :D

Body:
Picture the situation in an MVP pattern where your presenter subscribes to a service returning an observer:

public void gatherData(){
   service.doSomeMagic()
      .observeOn(Schedulers.io())
      .subscribeOn(AndroidSchedulers.mainThread())
      .subscribe(new TheSubscriber());
}

Now the class TheSubscriber calls onNext a method from the view, say:

@Override public void onNext(ReturnValue value) {
  view.displayWhatever(value);
}

Now, in my unit test I would like to verify that when the method gatherData() is called on a non-erroneous situation, the view's method displayWhatever(value) is called.

The question:

Is there a clean way to do this?

Background:

I'm using mockito to verify the interactions and a lot more of course

Dagger is injecting the entire presenter except for TheSubscriber

What have I tried:

Inject the subscriber and mock it in the tests. Looks a bit dirty to me, because if I want to change the way the presenter interacts with the service (Say not Rx) then I need to change a lot of tests and code.

Mock the entire service. This was not so bad, but requires me to mock a lot of methods and I didn't quite reach what I wanted.

Looked up around the internet, but no one seems to have a clean straight way of doing this

Thanks for the help

Body:
I know its pretty late but may it helps someone, cause i searched pretty long for a solution to your question :D

For me it worked out to add a Observable.Transformer<T, T> as followed:

    void gatherData() {
        service.doSomeMagic()
          .compose(getSchedulerTransformer())
          .subscribe(view::displayValue);
    }

    private <T> Observable.Transformer<T, T> getSchedulerTransformer() {
        if (mTransformer == null) {
            mTransformer = (Observable.Transformer<T, T>) observable -> observable.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

        return mTransformer;
    }

    void setSchedulerTransformer(Observable.Transformer<Observable<?>, Observable<?>> transformer) {
        mTransformer = transformer;
    }

And to set the Transformer just I just passed this:

setSchedulerTransformer(observable -> {
            if (observable instanceof Observable) {
                Observable observable1 = (Observable) observable;
                return observable1.subscribeOn(Schedulers.immediate())
                        .observeOn(Schedulers.immediate());
            }
            return null;
        });

So just add a @Before method in your test and call presenter.setSchedulerTransformer and it should be able to test this :)

hope this helps and is somehow understandable :D


问:
Converting pandas dataframe to a dictionary with a new key name
I know how to convert a dataframe to a dictionary but I'm not sure how I can create a dictionary with an arbitrary key name added.

Let's say I have a dataframe like the following.

```<code>raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])

df.head()
Out[96]:
     regiment company      name  preTestScore  postTestScore
0  Nighthawks     1st    Miller             4             25
1  Nighthawks     1st  Jacobson            24             94
2  Nighthawks     2nd       Ali            31             57
3  Nighthawks     2nd    Milner             2             62
4    Dragoons     1st     Cooze             3             70
</code>```

I want to groupby 'name' and compute maximum in 'preTestScore' and finally create a dictionary as following.

```<code>{'Miller': {'maxTestScore': 4},
 'Jacobson': {'maxTestScore': 24}, ...}
</code>```

Here, I added a new key name 'maxTestScore'. How could I achieve this with any arbitrary key name? Thank you so much in advance.

答:
You can use dict comprehension with groupby:

```<code>d = {k:{'maxTestScore':v.max()} for k,v in df.groupby('name')['preTestScore']}
print (d)

{'Piger':   {'maxTestScore': 3},
 'Milner':  {'maxTestScore': 2},
 'Sone':    {'maxTestScore': 31},
 'Jacon':   {'maxTestScore': 4},
 'Cooze':   {'maxTestScore': 3},
 'Sloan':   {'maxTestScore': 2},
 'Riani':   {'maxTestScore': 2},
 'Miller':  {'maxTestScore': 4},
 'Ali':     {'maxTestScore': 31},
 'Ryaner':  {'maxTestScore': 24},
 'Jacobson':{'maxTestScore': 24}}
</code>```

Another solution:

```<code>d = {k:{'maxTestScore':v} for k,v in df.groupby('name')['preTestScore'].max().iteritems()}
print (d)

{'Piger':   {'maxTestScore': 3},
 'Milner':  {'maxTestScore': 2},
 'Sone':    {'maxTestScore': 31},
 'Jacon':   {'maxTestScore': 4},
 'Cooze':   {'maxTestScore': 3},
 'Sloan':   {'maxTestScore': 2},
 'Riani':   {'maxTestScore': 2},
 'Miller':  {'maxTestScore': 4},
 'Ali':     {'maxTestScore': 31},
 'Ryaner':  {'maxTestScore': 24},
 'Jacobson':{'maxTestScore': 24}}
</code>```

Body:
I know how to convert a dataframe to a dictionary but I'm not sure how I can create a dictionary with an arbitrary key name added.

Let's say I have a dataframe like the following.

raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}

df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])

df.head()
Out[96]:
     regiment company      name  preTestScore  postTestScore
0  Nighthawks     1st    Miller             4             25
1  Nighthawks     1st  Jacobson            24             94
2  Nighthawks     2nd       Ali            31             57
3  Nighthawks     2nd    Milner             2             62
4    Dragoons     1st     Cooze             3             70

I want to groupby 'name' and compute maximum in 'preTestScore' and finally create a dictionary as following.

{'Miller': {'maxTestScore': 4},
 'Jacobson': {'maxTestScore': 24}, ...}

Here, I added a new key name 'maxTestScore'. How could I achieve this with any arbitrary key name? Thank you so much in advance.

Body:
You can use dict comprehension with groupby:

d = {k:{'maxTestScore':v.max()} for k,v in df.groupby('name')['preTestScore']}
print (d)

{'Piger':   {'maxTestScore': 3},
 'Milner':  {'maxTestScore': 2},
 'Sone':    {'maxTestScore': 31},
 'Jacon':   {'maxTestScore': 4},
 'Cooze':   {'maxTestScore': 3},
 'Sloan':   {'maxTestScore': 2},
 'Riani':   {'maxTestScore': 2},
 'Miller':  {'maxTestScore': 4},
 'Ali':     {'maxTestScore': 31},
 'Ryaner':  {'maxTestScore': 24},
 'Jacobson':{'maxTestScore': 24}}

Another solution:

d = {k:{'maxTestScore':v} for k,v in df.groupby('name')['preTestScore'].max().iteritems()}
print (d)

{'Piger':   {'maxTestScore': 3},
 'Milner':  {'maxTestScore': 2},
 'Sone':    {'maxTestScore': 31},
 'Jacon':   {'maxTestScore': 4},
 'Cooze':   {'maxTestScore': 3},
 'Sloan':   {'maxTestScore': 2},
 'Riani':   {'maxTestScore': 2},
 'Miller':  {'maxTestScore': 4},
 'Ali':     {'maxTestScore': 31},
 'Ryaner':  {'maxTestScore': 24},
 'Jacobson':{'maxTestScore': 24}}


问:
SQL: How to return any Part that occurs more than Once
I have the following query which returns the following error:
An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

SELECT Part from Parts Where count(Part) > 1

How could i rewrite it to return the part that appears more than once.

答:
A perfect opportunity for the rarely used HAVING clause:</p>

```<code>SELECT Part, Count(Part) as PartCount
FROM Parts
GROUP BY Part
HAVING Count(Parts) > 1
</code>```

Body:
A perfect opportunity for the rarely used HAVING clause:

SELECT Part, Count(Part) as PartCount
FROM Parts
GROUP BY Part
HAVING Count(Parts) > 1


问:
Comparing two dictionaries and checking how many (key, value) pairs are equal
I have two dictionaries, but for simplification, I will take these two:

```<code>>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)
</code>```

Now, I want to compare whether each key, value pair in x has the same corresponding value in y. So I wrote this:

```<code>>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
        if x_values == y_values:
            print 'Ok', x_values, y_values
        else:
            print 'Not', x_values, y_values
</code>```

And it works since a tuple is returned and then compared for equality.

My questions:

Is this correct? Is there a better way to do this? Better not in speed, I am talking about code elegance.

UPDATE: I forgot to mention that I have to check how many key, value pairs are equal.

答:
In Python 3.6, It can be done as:-

```<code>if (len(dict_1)==len(dict_2):
  for i in dict_1.items():
        ret=bool(i in dict_2.items())
</code>```

ret variable will be true if all the items of dict_1 in present in dict_2

Body:
I have two dictionaries, but for simplification, I will take these two:

>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)

Now, I want to compare whether each key, value pair in x has the same corresponding value in y. So I wrote this:

>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
        if x_values == y_values:
            print 'Ok', x_values, y_values
        else:
            print 'Not', x_values, y_values

And it works since a tuple is returned and then compared for equality.

My questions:

Is this correct? Is there a better way to do this? Better not in speed, I am talking about code elegance.

UPDATE: I forgot to mention that I have to check how many key, value pairs are equal.

Body:
In Python 3.6, It can be done as:-

if (len(dict_1)==len(dict_2):
  for i in dict_1.items():
        ret=bool(i in dict_2.items())

ret variable will be true if all the items of dict_1 in present in dict_2