问:
how to add all the numbers together and only display one line in a display text box?
```<code>Option Explicit On
Option Strict On
Option Infer Off
Public Class Form1

    Private strDeskSold(3) As String

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim intQtySold As Integer

        If rbtnEast.Checked Then
            strDeskSold(0) = "East"
        Else
            strDeskSold(0) = "West"
        End If

        If rbtnLarge.Checked Then
            strDeskSold(1) = "Large L Shape"
        ElseIf rbtnSmall.Checked Then
            strDeskSold(1) = "Small L Shape"
        ElseIf rbtnExec.Checked Then
            strDeskSold(1) = "Executive"
        Else
            strDeskSold(1) = "Presidential"
        End If

        If rbtnEast.Checked Then
            If lstBoxManagers.Text = "Anna Banes" Then
                strDeskSold(2) = "Anna Banes"
            ElseIf lstBoxManagers.Text = "Charlie Deer" Then
                strDeskSold(2) = "Charlie Deer"
            End If
        End If

        If rbtnWest.Checked Then
            If lstBoxManagers.Text = "Dan Easom" Then
                strDeskSold(2) = "Dan Easom"
            ElseIf lstBoxManagers.Text = "Fran Granger" Then
                strDeskSold(2) = "Fran Granger"
            ElseIf lstBoxManagers.Text = "Hamp Ideal" Then
                strDeskSold(2) = "Hamp Ideal"
            End If
        End If

        Integer.TryParse(txtNumberSold.Text, intQtySold)

        strDeskSold(3) = intQtySold.ToString
        txtDisplay.Text = txtDisplay.Text & strDeskSold(0) & ControlChars.Tab & strDeskSold(1) & ControlChars.Tab & strDeskSold(2) & ControlChars.Tab & strDeskSold(3) & ControlChars.NewLine
    End Sub
</code>```

<p>The program allows a user to select a region, then the manager for that region, then the desk type, then the number of desks ordered. I want to display all the information in one line and then another line as they press add again if the information is different in a display only text box. I have no clue where to even begin to add the different quantities ordered to display the total desks that have been ordered for each different desk type. </p>

答:
If I'm right, you want to display separate lines for each sale added unless the same item is sold by the same manager. In which case, you want to add the last sale to quantity to the existing sales in the list?

In which case, you need to go about it a slightly different way ..

Create a sale class like this

```<code>Private Class Sale
    Public Property Item As String
    Public Property Quantity As Integer
    Public Property ManagerName As String
End Class
</code>```

And a manager class like this. Each manager will have their own list of sales.

```<code>Private Class Manager
    Public Property Name As String
    Public Property Region As String
    Public Property Sales As New List(Of Sale)
End Class
</code>```

And create a list of managers

```<code>Dim Managers As New List(Of Manager)
</code>```

This form load event will add all the managers to the list. You can include it of you wish or write your own code depending on how you store the managers.

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim manager1 As New Manager With {.Name = "Anna Barnes", .Region = "West"}
    Dim manager2 As New Manager With {.Name = "Charlie Deer", .Region = "West"}
    Dim manager3 As New Manager With {.Name = "Dan Easom", .Region = "East"}
    Dim manager4 As New Manager With {.Name = "Fran Granger", .Region = "East"}
    Dim manager5 As New Manager With {.Name = "Hamp Ideal", .Region = "East"}
    Managers = New List(Of Manager) From {manager1, manager2, manager3, manager4, manager5}
End Sub
</code>```

These two events repopulate the ListBox when you change the east/west checkbox selection

```<code>Private Sub RbtnEast_CheckedChanged(sender As Object, e As EventArgs) Handles RbtnEast.CheckedChanged
    If RbtnEast.Checked Then
        lstBoxManagers.DataSource = Managers.FindAll(Function(x) x.Region = "East").ToArray
        lstBoxManagers.DisplayMember = "Name"
        lstBoxManagers.Update()
    End If
End Sub

Private Sub RbtnWest_CheckedChanged(sender As Object, e As EventArgs) Handles RbtnWest.CheckedChanged
    If RbtnWest.Checked Then
        lstBoxManagers.DataSource = Managers.FindAll(Function(x) x.Region = "West").ToArray
        lstBoxManagers.DisplayMember = "Name"
        lstBoxManagers.Update()
    End If
End Sub
</code>```

When you click the add button, the code creates a temporary sale item with all the details and if everything apart from the sales quantity matches a previous sale by a manager. If so, it will add the quantity of that sale to the preveious one. If there is no previous sale, it will be added to the manager's list of sales. Finally the richTextBox is updated to show a total sales of each item by each manager.

```<code>Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
    Dim tempSale As New Sale
    If rbtnLarge.Checked Then
        tempSale.Item = "Large L Shape"
    ElseIf rbtnSmall.Checked Then
        tempSale.Item = "Small L Shape"
    ElseIf rbtnExec.Checked Then
        tempSale.Item = "Executive"
    Else
        tempSale.Item = "Presidential"
    End If
    Integer.TryParse(TxtNumberSold.Text, tempSale.Quantity)
    Dim mgr As Manager = Managers.Find(Function(x) x.Name = CType(lstBoxManagers.SelectedItem, Manager).Name)
    'If Not IsNothing(mgr.Sales) Then
    Dim matchingSale As Sale = mgr.Sales.Find(Function(x) x.Item = tempSale.Item)
    If Not IsNothing(matchingSale) Then
        matchingSale.Quantity += tempSale.Quantity
    Else
        mgr.Sales.Add(tempSale)
    End If
    UpdateSalesTextBox()
End Sub
</code>```

This is the update code. It iterates through all the managers and all of their sales totals for each unique item they've sold.

```<code>Private Sub UpdateSalesTextBox()
    rtbDisplay.SuspendLayout()
    rtbDisplay.Clear()
    For Each mgr As Manager In Managers
        For Each [sale] As Sale In mgr.Sales
            rtbDisplay.AppendText(mgr.Region & vbTab & [sale].Item & vbTab & mgr.Name & vbTab & [sale].Quantity & vbCrLf)
        Next
    Next
    rtbDisplay.ResumeLayout()
End Sub
</code>```

If an answer sorts out your problem, don't forget to click the tick next to the answer - It makes sure that the user gets reputation points and makes it easier for anyone else who has the same problem to see that your question has an accepted answer that might work for them as well. (And the person answering the question gets reputation points btw)

Body:
Option Explicit On
Option Strict On
Option Infer Off
Public Class Form1

    Private strDeskSold(3) As String

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim intQtySold As Integer

        If rbtnEast.Checked Then
            strDeskSold(0) = "East"
        Else
            strDeskSold(0) = "West"
        End If

        If rbtnLarge.Checked Then
            strDeskSold(1) = "Large L Shape"
        ElseIf rbtnSmall.Checked Then
            strDeskSold(1) = "Small L Shape"
        ElseIf rbtnExec.Checked Then
            strDeskSold(1) = "Executive"
        Else
            strDeskSold(1) = "Presidential"
        End If

        If rbtnEast.Checked Then
            If lstBoxManagers.Text = "Anna Banes" Then
                strDeskSold(2) = "Anna Banes"
            ElseIf lstBoxManagers.Text = "Charlie Deer" Then
                strDeskSold(2) = "Charlie Deer"
            End If
        End If

        If rbtnWest.Checked Then
            If lstBoxManagers.Text = "Dan Easom" Then
                strDeskSold(2) = "Dan Easom"
            ElseIf lstBoxManagers.Text = "Fran Granger" Then
                strDeskSold(2) = "Fran Granger"
            ElseIf lstBoxManagers.Text = "Hamp Ideal" Then
                strDeskSold(2) = "Hamp Ideal"
            End If
        End If

        Integer.TryParse(txtNumberSold.Text, intQtySold)

        strDeskSold(3) = intQtySold.ToString
        txtDisplay.Text = txtDisplay.Text & strDeskSold(0) & ControlChars.Tab & strDeskSold(1) & ControlChars.Tab & strDeskSold(2) & ControlChars.Tab & strDeskSold(3) & ControlChars.NewLine
    End Sub

The program allows a user to select a region, then the manager for that region, then the desk type, then the number of desks ordered. I want to display all the information in one line and then another line as they press add again if the information is different in a display only text box. I have no clue where to even begin to add the different quantities ordered to display the total desks that have been ordered for each different desk type.

Body:
If I'm right, you want to display separate lines for each sale added unless the same item is sold by the same manager. In which case, you want to add the last sale to quantity to the existing sales in the list?

In which case, you need to go about it a slightly different way ..

Create a sale class like this

Private Class Sale
    Public Property Item As String
    Public Property Quantity As Integer
    Public Property ManagerName As String
End Class

And a manager class like this. Each manager will have their own list of sales.

Private Class Manager
    Public Property Name As String
    Public Property Region As String
    Public Property Sales As New List(Of Sale)
End Class

And create a list of managers

Dim Managers As New List(Of Manager)

This form load event will add all the managers to the list. You can include it of you wish or write your own code depending on how you store the managers.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim manager1 As New Manager With {.Name = "Anna Barnes", .Region = "West"}
    Dim manager2 As New Manager With {.Name = "Charlie Deer", .Region = "West"}
    Dim manager3 As New Manager With {.Name = "Dan Easom", .Region = "East"}
    Dim manager4 As New Manager With {.Name = "Fran Granger", .Region = "East"}
    Dim manager5 As New Manager With {.Name = "Hamp Ideal", .Region = "East"}
    Managers = New List(Of Manager) From {manager1, manager2, manager3, manager4, manager5}
End Sub

These two events repopulate the ListBox when you change the east/west checkbox selection

Private Sub RbtnEast_CheckedChanged(sender As Object, e As EventArgs) Handles RbtnEast.CheckedChanged
    If RbtnEast.Checked Then
        lstBoxManagers.DataSource = Managers.FindAll(Function(x) x.Region = "East").ToArray
        lstBoxManagers.DisplayMember = "Name"
        lstBoxManagers.Update()
    End If
End Sub

Private Sub RbtnWest_CheckedChanged(sender As Object, e As EventArgs) Handles RbtnWest.CheckedChanged
    If RbtnWest.Checked Then
        lstBoxManagers.DataSource = Managers.FindAll(Function(x) x.Region = "West").ToArray
        lstBoxManagers.DisplayMember = "Name"
        lstBoxManagers.Update()
    End If
End Sub

When you click the add button, the code creates a temporary sale item with all the details and if everything apart from the sales quantity matches a previous sale by a manager. If so, it will add the quantity of that sale to the preveious one. If there is no previous sale, it will be added to the manager's list of sales. Finally the richTextBox is updated to show a total sales of each item by each manager.

Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles BtnAdd.Click
    Dim tempSale As New Sale
    If rbtnLarge.Checked Then
        tempSale.Item = "Large L Shape"
    ElseIf rbtnSmall.Checked Then
        tempSale.Item = "Small L Shape"
    ElseIf rbtnExec.Checked Then
        tempSale.Item = "Executive"
    Else
        tempSale.Item = "Presidential"
    End If
    Integer.TryParse(TxtNumberSold.Text, tempSale.Quantity)
    Dim mgr As Manager = Managers.Find(Function(x) x.Name = CType(lstBoxManagers.SelectedItem, Manager).Name)
    'If Not IsNothing(mgr.Sales) Then
    Dim matchingSale As Sale = mgr.Sales.Find(Function(x) x.Item = tempSale.Item)
    If Not IsNothing(matchingSale) Then
        matchingSale.Quantity += tempSale.Quantity
    Else
        mgr.Sales.Add(tempSale)
    End If
    UpdateSalesTextBox()
End Sub

This is the update code. It iterates through all the managers and all of their sales totals for each unique item they've sold.

Private Sub UpdateSalesTextBox()
    rtbDisplay.SuspendLayout()
    rtbDisplay.Clear()
    For Each mgr As Manager In Managers
        For Each [sale] As Sale In mgr.Sales
            rtbDisplay.AppendText(mgr.Region & vbTab & [sale].Item & vbTab & mgr.Name & vbTab & [sale].Quantity & vbCrLf)
        Next
    Next
    rtbDisplay.ResumeLayout()
End Sub

If an answer sorts out your problem, don't forget to click the tick next to the answer - It makes sure that the user gets reputation points and makes it easier for anyone else who has the same problem to see that your question has an accepted answer that might work for them as well. (And the person answering the question gets reputation points btw)


来源: stackexchange

问:
Cannot disable submit button by $invalid while page load
I am trying to invalidate and disable the submit button on the load of the page, as not entering text into textbox is invalid, but my code is not working, can someone please provide the solution.

```<code><div id="reg_bground">
    <div id="formdiv" ng-app="myApp" ng-controller="valCtrl">
        <form name="myForm" novalidate>
            <div style="font-family:calibri; font-size:30px; font-weight:bolder;">
                <span>Register:</span>
            </div>
            <div>
                <span>Name:</span><br>
                <input type="text" name="user" ng-model="user" required><br>
                <p ng-show="myForm.user.$dirty && myForm.user.$invalid">*Please insert the name</p>
            </div>
            <input type="number">
            <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
        </form>
    </div>
</div>
</code>```

答:
The field content is valid

$invalid working when you enter a input and input doesn't match your pattern .
you must use $error.required for your goal.

follwing will work

```<code><div id="reg_bground">
     <div id="formdiv" ng-app="myApp" ng-controller="valCtrl">
            <form name="myForm" novalidate>
                <div style="font-family:calibri; font-size:30px; font-
        weight:bolder;">
                    <span>Register:</span>
                </div>
                <div>
                    <span>Name:</span><br>
                    <input type="text" name="user" ng-model="user" required><br>
                    <p ng-show="myForm.user.$dirty &&
      myForm.user.$error.required">*Please insert the name</p>
                </div>
                <input type="number">
                <input type="submit" ng-disabled="myForm.user.$dirty &&
     myForm.user.$error.required">
            </form>
         </div>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to invalidate and disable the submit button on the load of the page, as not entering text into textbox is invalid, but my code is not working, can someone please provide the solution.

        <form name="myForm" novalidate>

                Register:

                Name:

                <input type="text" name="user" ng-model="user" required>

*Please insert the name

            <input type="number">
            <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid">
        </form>

Body:
The field content is valid

$invalid working when you enter a input and input doesn't match your pattern .
you must use $error.required for your goal.

follwing will work

<div id="reg_bground">
     <div id="formdiv" ng-app="myApp" ng-controller="valCtrl">
            <form name="myForm" novalidate>
                <div style="font-family:calibri; font-size:30px; font-
        weight:bolder;">
                    <span>Register:</span>
                </div>
                <div>
                    <span>Name:</span><br>
                    <input type="text" name="user" ng-model="user" required><br>
                    <p ng-show="myForm.user.$dirty &&
      myForm.user.$error.required">*Please insert the name</p>
                </div>
                <input type="number">
                <input type="submit" ng-disabled="myForm.user.$dirty &&
     myForm.user.$error.required">
            </form>
         </div>


问:
VBA - ADODB connect to remote Oracle db
I am developing an Excel VBA program that I want to connect to a remote Oracle 11g database, run a query, and return the data to Excel.

Connection strings and drivers are all OK as far as I know. (see below)

It was working perfectly for a while yesterday, connecting to db and returning with correct data. Then I saved and closed the workbook, opened it 20 minutes later (no changes made!) and when I ran the macro I got the following error:

Runtime error '-2147418113 (8000ffff)': Catastrophic failure

any ideas what could be causing the error?
Could it be something on the DB's side?

Thanks

```<code>Sub ExtractFromOracle(environment As String)

Dim cn As ADODB.connection
Dim recordSet As ADODB.recordSet
Set cn = CreateObject("ADODB.Connection")
Set recordSet = CreateObject("ADODB.recordset")

Dim SQLQuery As String
SQLQuery = "SELECT User_Id, Prof_Id FROM user_profile ORDER BY User_Id ASC"

Dim returnData As Variant
Dim returnedRowsCount As Integer

Dim connectionString As String
connectionString = ReturnConnectionString(environment)

cn.Open (connectionString) ------------> ERROR OCCURS HERE

Set recordSet = cn.Execute(SQLQuery)
returnData = Application.Transpose(recordSet.GetRows)
returnedRowsCount = UBound(returnData)

If Not SheetExist(environment) Then
CreateTab (environment)
End If

Worksheets(environment).Activate
ActiveSheet.Range("A1:B" & returnedRowsCount) = returnData

Set rs = Nothing
Set cn = Nothing

ConsolidateUsers (environment)

End Sub
</code>```

CONNECTION STRING :

```<code>"Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=GTU_APP)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxx)(PORT=xxxx)))(CONNECT_DATA=(SID=xxxxx)(SERVER=DEDICATED)));User Id=xxxxxx;Password=xxxxxxx;"
</code>```

答:
I fixed the error so I though I would update for anyone  with the same issue who finds this thread.

It turns out that the 'Catastrophic Failure' error was due to my Oracle ODBC driver (oraOLEDB.oracle) becoming somehow corrupted, I couldn't even reinstall it properly, the error only occurred on my machine.

In the end I did a system restore to a point from before the issue and all was fixed. Not the most elegant solution but it worked.

Title: VBA - ADODB connect to remote Oracle db

Body:
I am developing an Excel VBA program that I want to connect to a remote Oracle 11g database, run a query, and return the data to Excel.

Connection strings and drivers are all OK as far as I know. (see below)

It was working perfectly for a while yesterday, connecting to db and returning with correct data. Then I saved and closed the workbook, opened it 20 minutes later (no changes made!) and when I ran the macro I got the following error:

Runtime error '-2147418113 (8000ffff)': Catastrophic failure

any ideas what could be causing the error?
Could it be something on the DB's side?

Thanks

Sub ExtractFromOracle(environment As String)

Dim cn As ADODB.connection
Dim recordSet As ADODB.recordSet
Set cn = CreateObject("ADODB.Connection")
Set recordSet = CreateObject("ADODB.recordset")

Dim SQLQuery As String
SQLQuery = "SELECT User_Id, Prof_Id FROM user_profile ORDER BY User_Id ASC"

Dim returnData As Variant
Dim returnedRowsCount As Integer

Dim connectionString As String
connectionString = ReturnConnectionString(environment)

cn.Open (connectionString) ------------> ERROR OCCURS HERE

Set recordSet = cn.Execute(SQLQuery)
returnData = Application.Transpose(recordSet.GetRows)
returnedRowsCount = UBound(returnData)

If Not SheetExist(environment) Then
CreateTab (environment)
End If

Worksheets(environment).Activate
ActiveSheet.Range("A1:B" & returnedRowsCount) = returnData

Set rs = Nothing
Set cn = Nothing

ConsolidateUsers (environment)

End Sub

CONNECTION STRING :

"Provider=OraOLEDB.Oracle;Data Source=(DESCRIPTION=(CID=GTU_APP)(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxx)(PORT=xxxx)))(CONNECT_DATA=(SID=xxxxx)(SERVER=DEDICATED)));User Id=xxxxxx;Password=xxxxxxx;"


问:
Elements before FlatList are fixed on a page and doesn't scroll with FlatList
I have a flatlist element and another element before flatlist. When I scroll up, the element before flatlist doesn't go up and is fixed. Is there a way to make it go up when faltlist is scrolled up?

Example:

```<code>  render() {
    return (
<View style={styles.container}>
<View>THIS ELEMENT BEFORE CONTAINER STAYS FIXED WHEN SCROLLING FLATLIST</View>
      <FlatList
        data={this.props.data}
        extraData={this.state}
        keyExtractor={this._keyExtractor}
        renderItem={this._renderItem}
      />
<View>
    );
  }
</code>```

答:
If I do understand you correctly you want to have your view on top be a part of the scrollable area of your FlatList. So you may want to make the view on top the ListHeaderComponent

```<code> renderListHeader = () => {
    return (
      <View>
        <Text>Foo</Text>
      </View>
     );
 }

 render() {
   return (
     <FlatList
       data={this.props.data}
       extraData={this.state}
       keyExtractor={this._keyExtractor}
       renderItem={this._renderItem}
       ListHeaderComponent={this.renderListHeader}
     />
   );
}
</code>```

Body:
I have a flatlist element and another element before flatlist. When I scroll up, the element before flatlist doesn't go up and is fixed. Is there a way to make it go up when faltlist is scrolled up?

Example:

  render() {
    return (
<View style={styles.container}>
<View>THIS ELEMENT BEFORE CONTAINER STAYS FIXED WHEN SCROLLING FLATLIST</View>
      <FlatList
        data={this.props.data}
        extraData={this.state}
        keyExtractor={this._keyExtractor}
        renderItem={this._renderItem}
      />
<View>
    );
  }

Body:
If I do understand you correctly you want to have your view on top be a part of the scrollable area of your FlatList. So you may want to make the view on top the ListHeaderComponent

 renderListHeader = () => {
    return (
      <View>
        <Text>Foo</Text>
      </View>
     );
 }

 render() {
   return (
     <FlatList
       data={this.props.data}
       extraData={this.state}
       keyExtractor={this._keyExtractor}
       renderItem={this._renderItem}
       ListHeaderComponent={this.renderListHeader}
     />
   );
}


问:
Java version automatically change to java 1.5 after maven update
I am using eclipse as IDE. When I right click on the project and then click maven update my java version change to 1.5. Here is what I did so far, I followed all the steps listed here

http://qussay.com/2013/09/13/solving-dynamic-web-module-3-0-requires-java-1-6-or-newer-in-maven-projects/

I changed "Java build path" to "workspace default jre 1.8.0_25"

Then changed "java compiler" to 1.8

Then changed "project facets">java>1.8

Changed pom.xml java version to 1.8

    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.1.3.v20140225</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugin</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
```

After all this when I click on "Maven update" my java version change to 1.5 automatically. Also in above steps, first two step's version also change to 1.5 automatically. How can I fix this?

答:
The root-cause of this issue is that if for any reason Eclipse's cannot resolve a valid value for the maven.compiler.source property when generating/updating the .classpath file from the pom, it will simply default to using org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5.

As expertly answered by @jorge-campos, there are multiple ways to set that property.

However, Jorge's answer didn't appear to work for me. Here were my settings:

```<code><properties>
    <javaVersion>1.8</javaVersion>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
</code>```

...

Exactly. ${java.version} is never going to resolve to the (completely different) property javaVersion and Eclipse ignored the property and used the default.

Which brings me back to the "for any reason" part I opened with; developer stupidity can be one of those reasons.

Body:
I am using eclipse as IDE. When I right click on the project and then click maven update my java version change to 1.5. Here is what I did so far, I followed all the steps listed here

http://qussay.com/2013/09/13/solving-dynamic-web-module-3-0-requires-java-1-6-or-newer-in-maven-projects/

I changed "Java build path" to "workspace default jre 1.8.0_25"

Then changed "java compiler" to 1.8

Then changed "project facets">java>1.8

Changed pom.xml java version to 1.8

    <build>
        <plugins>
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.1.3.v20140225</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugin</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

After all this when I click on "Maven update" my java version change to 1.5 automatically. Also in above steps, first two step's version also change to 1.5 automatically. How can I fix this?

Body:
The root-cause of this issue is that if for any reason Eclipse's cannot resolve a valid value for the maven.compiler.source property when generating/updating the .classpath file from the pom, it will simply default to using org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5.

As expertly answered by @jorge-campos, there are multiple ways to set that property.

However, Jorge's answer didn't appear to work for me. Here were my settings:

<properties>
    <javaVersion>1.8</javaVersion>
    <maven.compiler.source>${java.version}</maven.compiler.source>
    <maven.compiler.target>${java.version}</maven.compiler.target>
</properties>

...

Exactly. ${java.version} is never going to resolve to the (completely different) property javaVersion and Eclipse ignored the property and used the default.

Which brings me back to the "for any reason" part I opened with; developer stupidity can be one of those reasons.


问:
How can I prevent from applying blur Filter Image on resize?
I am trying to resize an image in my app. The issue is that Android automatically applies a filter that blurs the pixels. How can I prevent that from happening and instead see the Individual Pixels. As in Pixelated. Im using the ValueAnimator to increase the size of RelativeLayout that has an image set as Background.

```<code>ValueAnimator animator = ValueAnimator.ofInt(2000, 200000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator valueAnimator) {

        int state = (Integer) valueAnimator.getAnimatedValue();
        screenX = state;
        screenY = state;

        myContent.setLayoutParams(new FrameLayout.LayoutParams(screenX, screenY));

    }
});
animator.setDuration(2000);
animator.start();
</code>```

Example of What I mean

答:
Hey guys after searching for a while I found a solution to this.

http://www.41post.com/4241/programming/android-disabling-anti-aliasing-for-pixel-art

The word I was missing that would have helped me find an answer faster was Anti-Aliasing which has to be dissabled

Body:
I am trying to resize an image in my app. The issue is that Android automatically applies a filter that blurs the pixels. How can I prevent that from happening and instead see the Individual Pixels. As in Pixelated. Im using the ValueAnimator to increase the size of RelativeLayout that has an image set as Background.

ValueAnimator animator = ValueAnimator.ofInt(2000, 200000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator valueAnimator) {

        int state = (Integer) valueAnimator.getAnimatedValue();
        screenX = state;
        screenY = state;

        myContent.setLayoutParams(new FrameLayout.LayoutParams(screenX, screenY));

    }
});
animator.setDuration(2000);
animator.start();

Example of What I mean


问:
How to gatherElementById starting with a specific word?
Using Prototype and Script.aculo.us, I am trying to make all tags with an ID starting with "idea" Droppable but I can't remember how to get all tags starting with a specific string.  Thank you in advance.</p>

答: Give them a class and do $$('div.idea');</p>

ContentLicense: CC BY-SA 2.5


问:
Priority/Cascading datetime without full table scan
```<code>SELECT IF(priority_date, priority_date, created_at) as created_at
FROM table
WHERE IF(priority_date , priority_date , created_at)
    BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59';
</code>```

What is the best way to execute this query, performance-wise?

I have a fairly large table that has two datetimes. created_at and priority_date.

priority_date doesn't always exist, but if it does, it should be what is queried upon, else it falls back to created_at. created_at is always generated upon creation of the row. The above query causes a (nearly) full table scan.

The explain plan for initial query:

```<code>+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
| id   | select_type | table           | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
|    1 | SIMPLE      | table           | ALL  | NULL          | NULL | NULL    | NULL | 444877 | Using where |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
</code>```

I should also note that priority_date or created_at may not necessarily both be within the time frame in question on a single row. So doing something like:

```<code>WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
</code>```

Could give bad results if priority_date was 2017-10-04 23:10:43 and created_at was 2017-10-10 01:23:45

My current rows for said table: 582739

Count of WHERE priority_date BETWEEN... : 3908

Count of WHERE created_at BETWEEN...: 3437

Example explain of just one of the columns queried in WHERE BETWEEN:

```<code>+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
| id   | select_type | table           | type  | possible_keys                    | key                              | key_len | ref  | rows | Extra                 |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
|    1 | SIMPLE      | table           | range | table_created_at_index           | table_created_at_index           | 5       | NULL | 3436 | Using index condition |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
</code>```

Clearly the IF is not the most efficient. The columns are indexed and the explains of individual rows are matching to their counts for rows on the explain plan. How can I leverage having a priority/fallback query without the wild performance loss?

EDIT

The best I've been able to figure (But WOW, is that verbose and copy/paste-y feeling)

```<code>SELECT IF(priority_date, priority_date, created_at) as created_at, priority_date
FROM table
WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
HAVING ((priority_date AND priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59')
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59');
</code>```

And its explain plan:

```<code>+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
| id   | select_type | table           | type        | possible_keys                                                         | key                                                                   | key_len | ref  | rows | Extra                                                                                |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
|    1 | SIMPLE      | table           | index_merge | table_priority_date_index,table_created_at_index                      | table_priority_date_index,table_created_at_index                      | 6,5     | NULL | 7343 | Using sort_union(table_priority_date_index,table_created_at_index); Using where                      |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
</code>```

答:
```<code>( SELECT  priority_date AS created_at
    FROM  table
    WHERE  priority_date >= '2017-10-10'
      AND  priority_date <  '2017-10-10' + INTERVAL 1 DAY )
UNION  DISTINCT
( SELECT  created_at
    FROM  table
    WHERE  created_at >= '2017-10-10'
      AND  created_at <  '2017-10-10' + INTERVAL 1 DAY
      AND  priority_date IS NULL )
</code>```

With

```<code>INDEX(priority_date, created_at)  -- in this order
</code>```

Notes:

This way to do BETWEEN works better for date ranges other than DATETIME, plus avoids computing leap days, etc.  (This is no performance difference.)

For each subquery, the one index is "covering" and optimal.  No ICP should be needed.

I chose DISTINCT on the UNION -- Though slower than ALL, it may be more to your app's liking.  Switch to ALL if there can't be dups, or if dups are OK.

Body:
SELECT IF(priority_date, priority_date, created_at) as created_at
FROM table
WHERE IF(priority_date , priority_date , created_at)
    BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59';

What is the best way to execute this query, performance-wise?

I have a fairly large table that has two datetimes. created_at and priority_date.

priority_date doesn't always exist, but if it does, it should be what is queried upon, else it falls back to created_at. created_at is always generated upon creation of the row. The above query causes a (nearly) full table scan.

The explain plan for initial query:

+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
| id   | select_type | table           | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+
|    1 | SIMPLE      | table           | ALL  | NULL          | NULL | NULL    | NULL | 444877 | Using where |
+------+-------------+-----------------+------+---------------+------+---------+------+--------+-------------+

I should also note that priority_date or created_at may not necessarily both be within the time frame in question on a single row. So doing something like:

WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'

Could give bad results if priority_date was 2017-10-04 23:10:43 and created_at was 2017-10-10 01:23:45

My current rows for said table: 582739

Count of WHERE priority_date BETWEEN... : 3908

Count of WHERE created_at BETWEEN...: 3437

Example explain of just one of the columns queried in WHERE BETWEEN:

+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
| id   | select_type | table           | type  | possible_keys                    | key                              | key_len | ref  | rows | Extra                 |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+
|    1 | SIMPLE      | table           | range | table_created_at_index           | table_created_at_index           | 5       | NULL | 3436 | Using index condition |
+------+-------------+-----------------+-------+----------------------------------+----------------------------------+---------+------+------+-----------------------+

Clearly the IF is not the most efficient. The columns are indexed and the explains of individual rows are matching to their counts for rows on the explain plan. How can I leverage having a priority/fallback query without the wild performance loss?

EDIT

The best I've been able to figure (But WOW, is that verbose and copy/paste-y feeling)

SELECT IF(priority_date, priority_date, created_at) as created_at, priority_date
FROM table
WHERE priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59'
HAVING ((priority_date AND priority_date BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59')
    OR created_at BETWEEN '2017-10-10 00:00:00' AND '2017-10-10 23:59:59');

And its explain plan:

+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
| id   | select_type | table           | type        | possible_keys                                                         | key                                                                   | key_len | ref  | rows | Extra                                                                                |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+
|    1 | SIMPLE      | table           | index_merge | table_priority_date_index,table_created_at_index                      | table_priority_date_index,table_created_at_index                      | 6,5     | NULL | 7343 | Using sort_union(table_priority_date_index,table_created_at_index); Using where                      |
+------+-------------+-----------------+-------------+-----------------------------------------------------------------------+-----------------------------------------------------------------------+---------+------+------+------------------------------------------------------------------------------------------------------+

Body:
( SELECT  priority_date AS created_at
    FROM  table
    WHERE  priority_date >= '2017-10-10'
      AND  priority_date <  '2017-10-10' + INTERVAL 1 DAY )
UNION  DISTINCT
( SELECT  created_at
    FROM  table
    WHERE  created_at >= '2017-10-10'
      AND  created_at <  '2017-10-10' + INTERVAL 1 DAY
      AND  priority_date IS NULL )

With

INDEX(priority_date, created_at)  -- in this order

Notes:

This way to do BETWEEN works better for date ranges other than DATETIME, plus avoids computing leap days, etc.  (This is no performance difference.)

For each subquery, the one index is "covering" and optimal.  No ICP should be needed.

I chose DISTINCT on the UNION -- Though slower than ALL, it may be more to your app's liking.  Switch to ALL if there can't be dups, or if dups are OK.


问:
How to set the setCheckedState of a QTreeWidget child's child?
I have a QTreeWidget that has a hidden root, 2 children as headers, and 2 children underneath those children.

```<code>ROOT (HIDDEN)
  |
  |- HEADER 1 (CHILD, NOT CHECKABLE)
  |     |
  |     |- ITEM 11 (CHILD, CHECKABLE)
  |     |- ITEM 12 (CHILD, CHECKABLE)
  |
  |- HEADER 2 (CHILD)
  |     |
  |     | - ITEM 21 (CHILD, CHECKABLE)
  |     | - ITEM 22 (CHILD, CHECKABLE)
</code>```

Using a variable from the item = {} dictionary I need to setCheckState of HEADER 1, ITEM 12. Currently I track the current selected label using self.CurrentIndexLabel, although that is probably irrelevant in this example. I have populated the tree like such:

```<code>TreeList = ({
    'Header1': (('Item11', 'Item12', )),
    'Header2': (('Item21', 'Item22', )),
})

item = {'Item12': {'ItemEnabled': 1}}  # 0 = No, 1 = Yes

for key, value in TreeList.items():
    parent = QTreeWidgetItem(self.ListTreeView, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)
</code>```

Initially, I need to set whether the item is checked, or unchecked based on the item = {} dictionary that tacks variables for each item, and when the user unchecks the item, I need to change the item = {} dictionary to reflect whether or not the item is enabled.

I assume I need to use signal and slots to detect the change, but I can't seem to figure out how to flag an item in the list as checked, and I'm not sure how to reflect a user checking or unchecking an item in TreeList.

It would be ideal if I can track the checking or unchecking using 1 and 0 to update the dictionary item = {} with it's current state.

What would be the best way to accomplish this? I'm new to python, so please bear with me. I'm using Python 3.6 and PyQt5

答:
When a QTreeWidgetItem is checked or unchecked, a QTreeWidget.itemChanged(item, column) signal is emitted. So you can use it and then update your item dict in the slot.

And as said in a comment, I think the structure of the item dict you use is inapropriate. Using QTreeWidgetItem text value as a key (or still better, the QTreeWidgetItem object itself) would be easier, so a dict like item = {'Item12': {'ItemEnabled': True}}

For example :

```<code>from PyQt4 import QtCore, QtGui
import sys

class MyApplication(QtGui.QMainWindow):
    def __init__(self):
        super(MyApplication, self).__init__()
        self.item = {'Item12': {'ItemEnabled': True}}
        self.setupUi()

        TreeList = ({
            'Header1': ('Item11', 'Item12',),
            'Header2': ('Item21', 'Item22',),
        })

        for key, value in TreeList.items():
            parent = QtGui.QTreeWidgetItem(self.treeWidget, [key])
            for val in value:
                child = QtGui.QTreeWidgetItem([val])
                child.setFlags(child.flags() | QtCore.Qt.ItemIsUserCheckable)
                child.setCheckState(0, QtCore.Qt.Checked if val in self.item else QtCore.Qt.Unchecked)
                parent.addChild(child)

        self.treeWidget.itemChanged.connect(self.treeWidgetItemChanged)

    def setupUi(self):
        self.centralwidget = QtGui.QWidget(self)
        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.treeWidget = QtGui.QTreeWidget(self.centralwidget)
        self.gridLayout.addWidget(self.treeWidget)
        self.setCentralWidget(self.centralwidget)

    def treeWidgetItemChanged(self, widgetItem, column):
        print("Item {} is checked: {}".format(widgetItem, widgetItem.checkState(column) == QtCore.Qt.Checked))
        itemName = str(widgetItem.text(column))
        try:
            self.item[itemName]['ItemEnabled'] = widgetItem.checkState(column) == QtCore.Qt.Checked
        except KeyError:
            self.item[itemName] = {'ItemEnabled': widgetItem.checkState(column) == QtCore.Qt.Checked}

        print(self.item)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = MyApplication()
    w.show()
    sys.exit(app.exec_())
</code>```

Body:
I have a QTreeWidget that has a hidden root, 2 children as headers, and 2 children underneath those children.

ROOT (HIDDEN)
  |
  |- HEADER 1 (CHILD, NOT CHECKABLE)
  |     |
  |     |- ITEM 11 (CHILD, CHECKABLE)
  |     |- ITEM 12 (CHILD, CHECKABLE)
  |
  |- HEADER 2 (CHILD)
  |     |
  |     | - ITEM 21 (CHILD, CHECKABLE)
  |     | - ITEM 22 (CHILD, CHECKABLE)

Using a variable from the item = {} dictionary I need to setCheckState of HEADER 1, ITEM 12. Currently I track the current selected label using self.CurrentIndexLabel, although that is probably irrelevant in this example. I have populated the tree like such:

TreeList = ({
    'Header1': (('Item11', 'Item12', )),
    'Header2': (('Item21', 'Item22', )),
})

item = {'Item12': {'ItemEnabled': 1}}  # 0 = No, 1 = Yes

for key, value in TreeList.items():
    parent = QTreeWidgetItem(self.ListTreeView, [key])
    for val in value:
        child = QTreeWidgetItem([val])
        child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
        child.setCheckState(0, Qt.Unchecked)
        parent.addChild(child)

Initially, I need to set whether the item is checked, or unchecked based on the item = {} dictionary that tacks variables for each item, and when the user unchecks the item, I need to change the item = {} dictionary to reflect whether or not the item is enabled.

I assume I need to use signal and slots to detect the change, but I can't seem to figure out how to flag an item in the list as checked, and I'm not sure how to reflect a user checking or unchecking an item in TreeList.

It would be ideal if I can track the checking or unchecking using 1 and 0 to update the dictionary item = {} with it's current state.

What would be the best way to accomplish this? I'm new to python, so please bear with me. I'm using Python 3.6 and PyQt5

Body:
When a QTreeWidgetItem is checked or unchecked, a QTreeWidget.itemChanged(item, column) signal is emitted. So you can use it and then update your item dict in the slot.

And as said in a comment, I think the structure of the item dict you use is inapropriate. Using QTreeWidgetItem text value as a key (or still better, the QTreeWidgetItem object itself) would be easier, so a dict like item = {'Item12': {'ItemEnabled': True}}

For example :

from PyQt4 import QtCore, QtGui
import sys

class MyApplication(QtGui.QMainWindow):
    def __init__(self):
        super(MyApplication, self).__init__()
        self.item = {'Item12': {'ItemEnabled': True}}
        self.setupUi()

        TreeList = ({
            'Header1': ('Item11', 'Item12',),
            'Header2': ('Item21', 'Item22',),
        })

        for key, value in TreeList.items():
            parent = QtGui.QTreeWidgetItem(self.treeWidget, [key])
            for val in value:
                child = QtGui.QTreeWidgetItem([val])
                child.setFlags(child.flags() | QtCore.Qt.ItemIsUserCheckable)
                child.setCheckState(0, QtCore.Qt.Checked if val in self.item else QtCore.Qt.Unchecked)
                parent.addChild(child)

        self.treeWidget.itemChanged.connect(self.treeWidgetItemChanged)

    def setupUi(self):
        self.centralwidget = QtGui.QWidget(self)
        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.treeWidget = QtGui.QTreeWidget(self.centralwidget)
        self.gridLayout.addWidget(self.treeWidget)
        self.setCentralWidget(self.centralwidget)

    def treeWidgetItemChanged(self, widgetItem, column):
        print("Item {} is checked: {}".format(widgetItem, widgetItem.checkState(column) == QtCore.Qt.Checked))
        itemName = str(widgetItem.text(column))
        try:
            self.item[itemName]['ItemEnabled'] = widgetItem.checkState(column) == QtCore.Qt.Checked
        except KeyError:
            self.item[itemName] = {'ItemEnabled': widgetItem.checkState(column) == QtCore.Qt.Checked}

        print(self.item)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = MyApplication()
    w.show()
    sys.exit(app.exec_())


问:
MKMapCamera pitch-altitude function
Неу all. I need some help.
I'm working with MapKit and of course my camera can go up and down (zoom in and zoom out).

I want to change MKMapCamera pitch while zooming.
So when the camera is low the pitch will be big (~80) and when camera is high the pitch will be small (0).

Here is the picture, showing what I want to do:

I tried to create function, that will monitor the altitude and automatically change the pitch:

```<code>cam_timer = [NSTimer scheduledTimerWithTimeInterval: 0.05 target: self selector: @selector (test) userInfo:nil repeats: YES];

- (void) test
{
    [debug_lbl_1 setText: [NSString stringWithFormat:@"%f", map.region.span.latitudeDelta]];

        map.camera.pitch = 45; // changing pitch
}
</code>```

But when I accessing camera in that function it stopped moving. I mean...I can't move, zoom or make anything with map if I trying to access camera from that function.

So my question is: how can I make function that will change pitch when altitude (zoom level)) changed? Please, I very need some help =(

答:
You can achieve this in iOS 10 and above by using MKMapCamera and UIView animation</p>

```<code>mapView.camera = MKMapCamera(lookingAtCenter: pinLocation, fromDistance: 2000, pitch: 0, heading: 0)

let pinLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

let rotationCamera = MKMapCamera(lookingAtCenter: pinLocation, fromDistance: 2000, pitch: 75, heading: 180)

UIView.animate(withDuration: 10, delay: 0, options: .curveEaseInOut, animations: {
            self.mapView.camera = rotationCamera
        }, completion: nil)
</code>```

Title: MKMapCamera pitch-altitude function

Body:
Неу all. I need some help.
I'm working with MapKit and of course my camera can go up and down (zoom in and zoom out).

I want to change MKMapCamera pitch while zooming.
So when the camera is low the pitch will be big (~80) and when camera is high the pitch will be small (0).

Here is the picture, showing what I want to do:

I tried to create function, that will monitor the altitude and automatically change the pitch:

cam_timer = [NSTimer scheduledTimerWithTimeInterval: 0.05 target: self selector: @selector (test) userInfo:nil repeats: YES];

- (void) test
{
    [debug_lbl_1 setText: [NSString stringWithFormat:@"%f", map.region.span.latitudeDelta]];

        map.camera.pitch = 45; // changing pitch
}

But when I accessing camera in that function it stopped moving. I mean...I can't move, zoom or make anything with map if I trying to access camera from that function.

So my question is: how can I make function that will change pitch when altitude (zoom level)) changed? Please, I very need some help =(

Body:
You can achieve this in iOS 10 and above by using MKMapCamera and UIView animation

mapView.camera = MKMapCamera(lookingAtCenter: pinLocation, fromDistance: 2000, pitch: 0, heading: 0)

let pinLocation = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)

let rotationCamera = MKMapCamera(lookingAtCenter: pinLocation, fromDistance: 2000, pitch: 75, heading: 180)

UIView.animate(withDuration: 10, delay: 0, options: .curveEaseInOut, animations: {
            self.mapView.camera = rotationCamera
        }, completion: nil)


问:
How can I parse two strings in a table row by using beautifulsoup?
```<code>html = '''
<div class="container">
 <h2>Countries & Capitals</h2>
  <table class="two-column td-red">
  <thead><tr><th>Country</th><th>Capital city</th></tr></thead><tbody>
   <tr class="grey"><td>Afghanistan</td><td>Kabul</td></tr>
   <tr><td>Albania</td><td>Tirana</td></tr>
</tbody>
</table>
</div>
</code>```

Given this HTML, I would like to specifically parse the country name and the capital city name and put them into a dictionary so that I can get

dict["Afghanistan] = 'Kabul'

I've started by doing

```<code>soup = BeautifulSoup(open(filename), 'lxml')
countries = {}
# YOUR CODE HERE
table = soup.find_all('table')
for each in table:
    if each.find('tr'):
        continue
    else:
        print(each.prettify())
return countries
</code>```

But it's confusing since it's the first time using it.

答:
How about this:

```<code>from bs4 import BeautifulSoup

element ='''
<div class="container">
    <h2>Countries & Capitals</h2>
    <table class="two-column td-red">
        <thead>
            <tr><th>Country</th><th>Capital city</th></tr>
        </thead>
        <tbody>
            <tr class="grey"><td>Afghanistan</td><td>Kabul</td></tr>
            <tr><td>Albania</td><td>Tirana</td></tr>
        </tbody>
    </table>
</div>
'''
soup = BeautifulSoup(element, 'lxml')

countries = {}
for data in soup.select("tr"):
    elem = [item.text for item in data.select("th,td")]
    countries[elem[0]] = elem[1]

print(countries)
</code>```

Output:

```<code>{'Afghanistan': 'Kabul', 'Country': 'Capital city', 'Albania': 'Tirana'}
</code>```

Body:
html = '''

Countries & Capitals

Country	Capital city

Afghanistan	Kabul

Albania	Tirana

Given this HTML, I would like to specifically parse the country name and the capital city name and put them into a dictionary so that I can get

dict["Afghanistan] = 'Kabul'

I've started by doing

soup = BeautifulSoup(open(filename), 'lxml')
countries = {}
# YOUR CODE HERE
table = soup.find_all('table')
for each in table:
    if each.find('tr'):
        continue
    else:
        print(each.prettify())
return countries

But it's confusing since it's the first time using it.

Body:
How about this:

from bs4 import BeautifulSoup

element ='''
<div class="container">
    <h2>Countries & Capitals</h2>
    <table class="two-column td-red">
        <thead>
            <tr><th>Country</th><th>Capital city</th></tr>
        </thead>
        <tbody>
            <tr class="grey"><td>Afghanistan</td><td>Kabul</td></tr>
            <tr><td>Albania</td><td>Tirana</td></tr>
        </tbody>
    </table>
</div>
'''
soup = BeautifulSoup(element, 'lxml')

countries = {}
for data in soup.select("tr"):
    elem = [item.text for item in data.select("th,td")]
    countries[elem[0]] = elem[1]

print(countries)

Output:

{'Afghanistan': 'Kabul', 'Country': 'Capital city', 'Albania': 'Tirana'}


问:
Javascript and PHPMySQL
```<code><?php
$host = 'localhost';
$dbusername ='root';
$dbpassword ='';
$database ='mp19';

$link =mysql_connect('localhost', 'root','12345678');
$db_selected = mysql_select_db('mp19', $link);

if (!$link)
  {exit("Connection Failed: " . $link);}

$sql="(SELECT * FROM 3-33)";
$result=mysql_query($sql, $link);

if (!$result)
  {exit("Error in SQL");}

echo "<table><tr>";
echo "<th>Date</th>";
while ($row=mysql_fetch_assoc($result))
  {
  var_dump($row);
  echo "<td>$row['date']</td></tr>";
  }
mysql_close($link);
?>
</code>```

The connection is successful but the data doesn't get fetched from phpmysql and neither does it print in a table. Why is this so?

答:
The query is invalid - try loading your mysql client at the command line and running it:</p>

```<code>mysql -uroot mp19 -p
(SELECT * FROM 3-33)
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3-33' at line 1
</code>```

Title: Javascript and PHPMySQL

Body:
<?php
$host = 'localhost';
$dbusername ='root';
$dbpassword ='';
$database ='mp19';

$link =mysql_connect('localhost', 'root','12345678');
$db_selected = mysql_select_db('mp19', $link);

if (!$link)
  {exit("Connection Failed: " . $link);}

$sql="(SELECT * FROM 3-33)";
$result=mysql_query($sql, $link);

if (!$result)
  {exit("Error in SQL");}

echo "

";
echo "Date	";
while ($row=mysql_fetch_assoc($result))
  {
  var_dump($row);
  echo "$row['date']
";
  }
mysql_close($link);
?>

The connection is successful but the data doesn't get fetched from phpmysql and neither does it print in a table. Why is this so?

Body:
The query is invalid - try loading your mysql client at the command line and running it:

mysql -uroot mp19 -p
(SELECT * FROM 3-33)
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '3-33' at line 1


问:
C++, catch user-defined exceptions in multiple blocks
Suppose the following example. There are classes A-C derived from std::exception:

```<code>#include <exception>
#include <string>
#include <iostream>

class A : public std::exception {
std::string a_text;

public:
 A(const std::string & a_text_) : a_text(a_text_) {}
 virtual ~A() throw() { }
};

class B : public A {
 const std::string b_text;

public:
 B(const std::string &a_text_, const std::string & b_text_) : A(a_text_), b_text(b_text_) {}
 virtual ~B() throw() {}
};

template <typename T>
class C : public B {
 T x;

public:
 C(const std::string & a_text_, const std::string & b_text_, const T x_) :
    B (b_text_, a_text_), x(x_) { }

 virtual ~C() throw() {};
};
</code>```

So far I have been convinced that generalizing pattern catches the exception of the derived class in multiple blocks.

```<code>int main() {
 try {
    throw C<double>("a", "b", 10);
 }

 catch (C<double> &c1) {
    std::cout << " C";
 }

 catch (B &b1) {
    std::cout << " B";
 }
}
</code>```

Unfortunately, the second block referring to B is skipped. Where is the problem? Thanks for your help.

答: Only the first catch block that matches is going to execute. You can re-throw the existing exception with the "throw;" statement but I am not sure if that will continue the search at the next catch block or only in a outer try-catch.</p>

Body:
Suppose the following example. There are classes A-C derived from std::exception:

#include <exception>
#include <string>
#include <iostream>

class A : public std::exception {
std::string a_text;

public:
 A(const std::string & a_text_) : a_text(a_text_) {}
 virtual ~A() throw() { }
};

class B : public A {
 const std::string b_text;

public:
 B(const std::string &a_text_, const std::string & b_text_) : A(a_text_), b_text(b_text_) {}
 virtual ~B() throw() {}
};

template <typename T>
class C : public B {
 T x;

public:
 C(const std::string & a_text_, const std::string & b_text_, const T x_) :
    B (b_text_, a_text_), x(x_) { }

 virtual ~C() throw() {};
};

So far I have been convinced that generalizing pattern catches the exception of the derived class in multiple blocks.

int main() {
 try {
    throw C<double>("a", "b", 10);
 }

 catch (C<double> &c1) {
    std::cout << " C";
 }

 catch (B &b1) {
    std::cout << " B";
 }
}

Unfortunately, the second block referring to B is skipped. Where is the problem? Thanks for your help.


问:
csrf token is missing or incorrect
followed a lot of the stuff recommended on StackOverflow. Also I tried to put {% csrf_token %} in the html in various places but none seemed to work. Any suggestions?

Here is my django templates input button

```<code> <input id=saveWaypoints type=button value='Save your Location' disabled=disabled>
</code>```

Which calls this javascript

```<code>$('#saveWaypoints').click(function () {
                var waypointStrings = [];
                for (id in waypointByID) {
                    waypoint = waypointByID[id];
                    waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat);
                };

                $.post("{% url 'waypoints-save' %}", {
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    waypointsPayload: waypointStrings.join('\n')
                }, function (data) {
                    if (data.isOk) {
                        $('#saveWaypoints').attr('disabled', 'disabled');
                    } else {
                        alert(data.message);
                    }
                });
            });
</code>```

My complete javascript code is

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Maps | {% block title %}{% endblock %}</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
    <script>
        var map, marker, waypointByID = {};
        var currentObject;
        var map;
        var geocoder;

        function initialize() {
            map = new google.maps.Map(document.getElementById('map'), {
                zoom: 5,
                center: new google.maps.LatLng(41.879535, -87.624333),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });
            geocoder = new google.maps.Geocoder();

        }

        $(function () {

        });

        {% for waypoint in waypoints %}
        waypointByID[{{waypoint.id}}] = {
            name: "{{waypoint.name}}",
            lat: {{waypoint.geometry.y}},
            lng: {{waypoint.geometry.x}}
        };
        {% endfor %}

        var currentObject;

        $(document).ready(function () {
            function activateWaypoints() {
                // Add waypoint click handler
                $('.waypoint').each(function () {
                    $(this).click(function() {
                        var waypoint = waypointByID[this.id];
                        var center = new google.maps.LatLng(waypoint.lat, waypoint.lng);
                        currentObject = $(this);
                        if (marker) marker.setMap();
                        marker = new google.maps.Marker({map: map, position: center, draggable: true});
                        google.maps.event.addListener(marker, 'dragend', function() {
                            var position = marker.getPosition();
                            waypoint.lat = position.lat();
                            waypoint.lng = position.lng();
                            currentObject.html(waypoint.name +
                                ' (' + waypoint.lat +
                                ', ' + waypoint.lng + ')');
                            $('#saveWaypoints').removeAttr('disabled');
                        });
                        map.panTo(center);
                    }).hover(
                        function () {this.className = this.className.replace('OFF', 'ON');},
                        function () {this.className = this.className.replace('ON', 'OFF');}
                    );
                });
            }
            $('#saveWaypoints').click(function () {
                var waypointStrings = [];
                for (id in waypointByID) {
                    waypoint = waypointByID[id];
                    waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat);
                };

                $.post("{% url 'waypoints-save' %}", {
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    waypointsPayload: waypointStrings.join('\n')
                }, function (data) {
                    if (data.isOk) {
                        $('#saveWaypoints').attr('disabled', 'disabled');
                    } else {
                        alert(data.message);
                    }
                });
            });
            activateWaypoints();
        });
    </script>

    <style>
        body {font-family: sans-serif}
        #map {width: 1000px; height: 500px}
        #waypoints {overflow: auto; width: 500px; height: 100px}
        .linkOFF {color: darkblue}
        .linkON {color: white; background-color: darkblue}
    </style>

    </head>

    <body>
        <div id="nav">
            <a href="/">home</a> |
        {% if user.is_authenticated %}
            welcome {{ user.username }}
            (<a href="/logout">logout</a>)
        {% else %}
            <a href="/login/">login</a> |
            <a href="/register/">register</a>
        {% endif %}
        </div>
        <h1>{% block head %}{% endblock %}</h1>
        {% block content %}{% endblock %}
    </body>

    <body onload='initialize()'>
        <div id=map></div>
        <div id=waypoints>
            {% for waypoint in waypoints %}
                <div id={{waypoint.id}} class='waypoint linkOFF'>
                    {{waypoint.name}} ({{waypoint.geometry.y}}, {{waypoint.geometry.x}})
                </div>
            {% endfor %}

        </div>
        <input id=saveWaypoints type=button value='Save your Location' disabled=disabled>
    </body>

</html>
</code>```

My views.py is

```<code>def save(request):
    'Save waypoints'

    for waypointString in request.POST.get('waypointsPayload', '').splitlines():
        waypointID, waypointX, waypointY = waypointString.split()
        waypoint = Waypoint.objects.get(id=int(waypointID))
        waypoint.geometry.set_x(float(waypointX))
        waypoint.geometry.set_y(float(waypointY))
        waypoint.save()
    return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')
</code>```

Any suggestions please . Thanks

答:
This worked for me:</p>

```<code>$.post("{% url 'waypoints-save' %}", {
  'csrfmiddlewaretoken': '{{ csrf_token }}',
}
</code>```

Title: csrf token is missing or incorrect

Body:
followed a lot of the stuff recommended on StackOverflow. Also I tried to put {% csrf_token %} in the html in various places but none seemed to work. Any suggestions?

Here is my django templates input button

 <input id=saveWaypoints type=button value='Save your Location' disabled=disabled>

Which calls this javascript

$('#saveWaypoints').click(function () {
                var waypointStrings = [];
                for (id in waypointByID) {
                    waypoint = waypointByID[id];
                    waypointStrings.push(id + ' ' + waypoint.lng + ' ' + waypoint.lat);
                };

                $.post("{% url 'waypoints-save' %}", {
                    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
                    waypointsPayload: waypointStrings.join('\n')
                }, function (data) {
                    if (data.isOk) {
                        $('#saveWaypoints').attr('disabled', 'disabled');
                    } else {
                        alert(data.message);
                    }
                });
            });

My complete javascript code is

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <title>Maps | {% block title %}{% endblock %}</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

            home |
        {% if user.is_authenticated %}
            welcome {{ user.username }}
            (logout)
        {% else %}
            login |
            register
        {% endif %}

{% block head %}{% endblock %}

        {% block content %}{% endblock %}

            {% for waypoint in waypoints %}

                    {{waypoint.name}} ({{waypoint.geometry.y}}, {{waypoint.geometry.x}})

            {% endfor %}

        <input id=saveWaypoints type=button value='Save your Location' disabled=disabled>

My views.py is

def save(request):
    'Save waypoints'

    for waypointString in request.POST.get('waypointsPayload', '').splitlines():
        waypointID, waypointX, waypointY = waypointString.split()
        waypoint = Waypoint.objects.get(id=int(waypointID))
        waypoint.geometry.set_x(float(waypointX))
        waypoint.geometry.set_y(float(waypointY))
        waypoint.save()
    return HttpResponse(simplejson.dumps(dict(isOk=1)), mimetype='application/json')

Any suggestions please . Thanks

Body:
This worked for me:

$.post("{% url 'waypoints-save' %}", {
  'csrfmiddlewaretoken': '{{ csrf_token }}',
}


问:
Fetch specific key from nested document in ArangoDB
```<code>"Alpha":
    {"ABC":
     {"DEF":
         {"2017":
             {"GHI JKL":
                 {"MNO":
                     ["ABCDEFGHIJKLMNOP"]}},
             {"TGY BUG":
                  {"MNO":
                      ["1234567891012456"]}}}}}
"Alpha1":
    {"XYZ":
        {"TUW":
           {"2014":
               {"QRS PQR":
                    {"MNO":
                       ["ZYXWUTSRQPONML"]}}}}}
"Alpha2":
    {"KJM":
       {"LKI":
           {"2005":
              {"MNO":
                 ["POLKIKJUMNHY"]}}}

"Alpha3":
    {"WWW":
       {"CCC DDD":
           {"2011":
               {"MNO":
                    {"POLKIKJUMNHY":"value"}}}}}
</code>```

I have four document Alpha,Alpha1, Alpha2 and Alpha3 in ArangoDB. I want to fetch data related to key "MNO" from each of document in single query.

答:
(cross-post from https://groups.google.com/forum/#!topic/arangodb/LshKkQMH7lg)

If I understand correctly, you want to retrieve all attribute values, with an attribute key of "MNO", at an arbitrary depth.

There is no function to flatten objects in some way, and recursion is not possible in AQL.

If it's always at the same level of nesting (if it exists), then it would be possible to hard-code.

```<code>LET doc = {
  "_id": "remove-me",

  "Alpha": {
    "ABC": {
      "DEF": {
        "2017": {
          "GHI JKL": {
            "MNO": ["ABCDEFGHIJKLMNOP"],

            "PQR": true
          },
          "TGY BUG": {
            "MNO": ["1234567891012456"],
            "WXY": 987
          }
        }
      }
    }
  }
}

FOR a1 IN ATTRIBUTES(doc, true)
  FOR a2 IN ATTRIBUTES(doc[a1], true) || []
    FOR a3 IN ATTRIBUTES(doc[a1][a2], true) || []
      FOR a4 IN ATTRIBUTES(doc[a1][a2][a3], true) || []
        FOR a5 IN ATTRIBUTES(doc[a1][a2][a3][a4], true) || []
          FOR a6 IN ATTRIBUTES(doc[a1][a2][a3][a4][a5], true) || []
            FILTER a6 == "MNO"
              RETURN doc[a1][a2][a3][a4][a5]["MNO"]
              // --or-- if you want to return an object {"MNO": value} for each match
              //RETURN KEEP(doc[a1][a2][a3][a4][a5], "MNO")
</code>```

I experimented with something like the following, but was unable to make it pick the "MNO" attribute from different levels. Maybe there's a logical flaw that you can work out.

```<code>LET doc = {
  "_id": "remove-me",

  "Alpha": {
    "ABC": {
      "DEF": {
        "2017": {
          "GHI JKL": {
            "MNO": ["ABCDEFGHIJKLMNOP"],

            "PQR": true
          },
          "TGY BUG": {
            "MNO": ["1234567891012456"],
            "WXY": 987
          }
        }
      }
    },
    "DEF2": {
      "MNO": 67
    }
  },
  "Beta": {
    "MNO": "Beta MNO",
    "XXX": false,
    "YYY": null
  }
}

LET v0 = []
FOR a1 IN ATTRIBUTES(doc, true)
  LET v1 = APPEND(v0, a1 == "MNO" ? doc["MNO"] : [])
  FOR a2 IN ATTRIBUTES(doc[a1], true) || []
    LET v2 = APPEND(v1, a2 == "MNO" ? doc[a1]["MNO"] : [])
    FOR a3 IN ATTRIBUTES(doc[a1][a2], true) || []
      LET v3 = APPEND(v2, a3 == "MNO" ? doc[a1][a2]["MNO"] : [])
      FOR a4 IN ATTRIBUTES(doc[a1][a2][a3], true) || []
        LET v4 = APPEND(v3, a4 == "MNO" ? doc[a1][a2][a3]["MNO"] : [])
        FOR a5 IN ATTRIBUTES(doc[a1][a2][a3][a4], true) || []
          LET v5 = APPEND(v4, a5 == "MNO" ? doc[a1][a2][a3][a4]["MNO"] : [])
          FOR a6 IN ATTRIBUTES(doc[a1][a2][a3][a4][a5], true) || []
            LET v6 = APPEND(v5, a6 == "MNO" ? doc[a1][a2][a3][a4][a5]["MNO"] : [])
            RETURN v6
</code>```

Body:
"Alpha":
    {"ABC":
     {"DEF":
         {"2017":
             {"GHI JKL":
                 {"MNO":
                     ["ABCDEFGHIJKLMNOP"]}},
             {"TGY BUG":
                  {"MNO":
                      ["1234567891012456"]}}}}}
"Alpha1":
    {"XYZ":
        {"TUW":
           {"2014":
               {"QRS PQR":
                    {"MNO":
                       ["ZYXWUTSRQPONML"]}}}}}
"Alpha2":
    {"KJM":
       {"LKI":
           {"2005":
              {"MNO":
                 ["POLKIKJUMNHY"]}}}

"Alpha3":
    {"WWW":
       {"CCC DDD":
           {"2011":
               {"MNO":
                    {"POLKIKJUMNHY":"value"}}}}}

I have four document Alpha,Alpha1, Alpha2 and Alpha3 in ArangoDB. I want to fetch data related to key "MNO" from each of document in single query.

Body:
(cross-post from https://groups.google.com/forum/#!topic/arangodb/LshKkQMH7lg)

If I understand correctly, you want to retrieve all attribute values, with an attribute key of "MNO", at an arbitrary depth.

There is no function to flatten objects in some way, and recursion is not possible in AQL.

If it's always at the same level of nesting (if it exists), then it would be possible to hard-code.

LET doc = {
  "_id": "remove-me",

  "Alpha": {
    "ABC": {
      "DEF": {
        "2017": {
          "GHI JKL": {
            "MNO": ["ABCDEFGHIJKLMNOP"],

            "PQR": true
          },
          "TGY BUG": {
            "MNO": ["1234567891012456"],
            "WXY": 987
          }
        }
      }
    }
  }
}

FOR a1 IN ATTRIBUTES(doc, true)
  FOR a2 IN ATTRIBUTES(doc[a1], true) || []
    FOR a3 IN ATTRIBUTES(doc[a1][a2], true) || []
      FOR a4 IN ATTRIBUTES(doc[a1][a2][a3], true) || []
        FOR a5 IN ATTRIBUTES(doc[a1][a2][a3][a4], true) || []
          FOR a6 IN ATTRIBUTES(doc[a1][a2][a3][a4][a5], true) || []
            FILTER a6 == "MNO"
              RETURN doc[a1][a2][a3][a4][a5]["MNO"]
              // --or-- if you want to return an object {"MNO": value} for each match
              //RETURN KEEP(doc[a1][a2][a3][a4][a5], "MNO")

I experimented with something like the following, but was unable to make it pick the "MNO" attribute from different levels. Maybe there's a logical flaw that you can work out.

LET doc = {
  "_id": "remove-me",

  "Alpha": {
    "ABC": {
      "DEF": {
        "2017": {
          "GHI JKL": {
            "MNO": ["ABCDEFGHIJKLMNOP"],

            "PQR": true
          },
          "TGY BUG": {
            "MNO": ["1234567891012456"],
            "WXY": 987
          }
        }
      }
    },
    "DEF2": {
      "MNO": 67
    }
  },
  "Beta": {
    "MNO": "Beta MNO",
    "XXX": false,
    "YYY": null
  }
}

LET v0 = []
FOR a1 IN ATTRIBUTES(doc, true)
  LET v1 = APPEND(v0, a1 == "MNO" ? doc["MNO"] : [])
  FOR a2 IN ATTRIBUTES(doc[a1], true) || []
    LET v2 = APPEND(v1, a2 == "MNO" ? doc[a1]["MNO"] : [])
    FOR a3 IN ATTRIBUTES(doc[a1][a2], true) || []
      LET v3 = APPEND(v2, a3 == "MNO" ? doc[a1][a2]["MNO"] : [])
      FOR a4 IN ATTRIBUTES(doc[a1][a2][a3], true) || []
        LET v4 = APPEND(v3, a4 == "MNO" ? doc[a1][a2][a3]["MNO"] : [])
        FOR a5 IN ATTRIBUTES(doc[a1][a2][a3][a4], true) || []
          LET v5 = APPEND(v4, a5 == "MNO" ? doc[a1][a2][a3][a4]["MNO"] : [])
          FOR a6 IN ATTRIBUTES(doc[a1][a2][a3][a4][a5], true) || []
            LET v6 = APPEND(v5, a6 == "MNO" ? doc[a1][a2][a3][a4][a5]["MNO"] : [])
            RETURN v6


问:
How can I convert Stream to IntStream
I want to implement a static method called youngWinners that given a Stream<Winner> returns a new Stream<Winner> containing the winners that are younger than 35, ordered alphabetically.

Inside my file I have : index, year, age, name, movie.

My problem is that I don't know how I can convert Stream into IntStream to compare the age with 35. I also got a bit confused, do I have to use comparators to do this or not ?

```<code>public static Stream<Winner> youngWinners(Stream<Winner> young) {
    //  Stream<Winner> youngWin = young;
    String[] toString = young.toArray(s -> new String[s]);
    Arrays.stream(toString).flatMap((<any> f) -> {
        try {
            return Files.lines(Paths.get(f))
                    .filter(age -> int (age) <= 35 )
                    .mapToInt(a -> a.getWinnerage())
                    .map(WinneropsDB::new);
        } catch (Exception e) {
            System.out.println("error");
            return null;
        }
    });
    return null;
}
</code>```

答:
you don't need an IntStream at all.

Simply do:

```<code>return young.filter(w -> w.getAge() < 35)
            .sorted(Comparator.comparing(Winner::getName));
</code>```

Title: How can I convert Stream to IntStream

Body:
I want to implement a static method called youngWinners that given a Stream<Winner> returns a new Stream<Winner> containing the winners that are younger than 35, ordered alphabetically.

Inside my file I have : index, year, age, name, movie.

My problem is that I don't know how I can convert Stream into IntStream to compare the age with 35. I also got a bit confused, do I have to use comparators to do this or not ?

public static Stream<Winner> youngWinners(Stream<Winner> young) {
    //  Stream<Winner> youngWin = young;
    String[] toString = young.toArray(s -> new String[s]);
    Arrays.stream(toString).flatMap((<any> f) -> {
        try {
            return Files.lines(Paths.get(f))
                    .filter(age -> int (age) <= 35 )
                    .mapToInt(a -> a.getWinnerage())
                    .map(WinneropsDB::new);
        } catch (Exception e) {
            System.out.println("error");
            return null;
        }
    });
    return null;
}

Body:
you don't need an IntStream at all.

Simply do:

return young.filter(w -> w.getAge() < 35)
            .sorted(Comparator.comparing(Winner::getName));


问:
UWP Xbox Live Leaderboards
I am trying to incorporate leaderboards into my UWP game. I am using C# and XAML to create my game. I have created a high score leaderboard and have pushed it with the test button in the dash board.

I have pushed a record to the leaderboard by calling:

```<code>_stats.SetStatisticIntegerData(XboxUser, "score", XP);
_stats.RequestFlushToService(XboxUser, true);
</code>```

I receive a successful response from the server.

When I try to retrieve the leaderboard from the server by the following:

```<code>_stats.GetLeaderboard(XboxUser, "score", new LeaderboardQuery());
</code>```

I get back a successful response.

The problem is I do not receive any rows with my response. I get back one column with the displayName of High Score, but no rows.

Does anyone know what I am doing incorrectly?

UPDATE
A bit more information:

I have created a leaderboard with the ID of score.

when I call the following:

```<code>var val = _stats.GetStatistic(XboxUser, "score");
</code>```

It throws the following exception:

```<code>The parameter is incorrect.

Stat not found in document
</code>```

When I store the data into the leaderboard I get the following:

Static Event:

ErrorCode: 0

ErrorMessage: ""

EventArgs: null

EventType: StatisticUpdateComplete

User: my User

答: I have the answer! Before calling add static or getting the Leaderboard you have to wait until the StatisticEventType.LocalUserAdded Event completes.

Title: UWP Xbox Live Leaderboards

Body:
I am trying to incorporate leaderboards into my UWP game. I am using C# and XAML to create my game. I have created a high score leaderboard and have pushed it with the test button in the dash board.

I have pushed a record to the leaderboard by calling:

_stats.SetStatisticIntegerData(XboxUser, "score", XP);
_stats.RequestFlushToService(XboxUser, true);

I receive a successful response from the server.

When I try to retrieve the leaderboard from the server by the following:

_stats.GetLeaderboard(XboxUser, "score", new LeaderboardQuery());

I get back a successful response.

The problem is I do not receive any rows with my response. I get back one column with the displayName of High Score, but no rows.

Does anyone know what I am doing incorrectly?

UPDATE
A bit more information:

I have created a leaderboard with the ID of score.

when I call the following:

var val = _stats.GetStatistic(XboxUser, "score");

It throws the following exception:

The parameter is incorrect.

Stat not found in document

When I store the data into the leaderboard I get the following:

Static Event:

ErrorCode: 0

ErrorMessage: ""

EventArgs: null

EventType: StatisticUpdateComplete

User: my User


问:
Browserless JavaScript
I talked to the Team Lead at Snap-On Tools once, and she told they used an "implementation of JavaScript" for their server-side coding. It's been a while, but I was thinking, WTF is she talking about? Are there interpreters for JavaScript besides those implemented in browsers?

How can you create a program or code, especially server-side, using JavaScript that doesn't execute in the context of a browser? What the hell is server-side about JavaScript if it's not generating content after the browser has loaded it? Can "server-side" JavaScript generate content before the HTTP response is deliver—and if so, how does that work/is set up?

I have many issues with JavaScript, but first-class functions are so sexy. And JavaScript Object Notation is so pure; I couldn't imagine an easier way to define data structures. Plus, you can hack out some code pretty quickly with dynamic typing if you're not writing something that's mission critical.

As a side question, given the last paragraph, have any suggestions about a good language to learn (comments will suffice)?

答:
I've heard good things about Jaxer.

By the far the most popular/attractive part of these server-side javascript solutions is in regards to data validation. You can use the same code that you use to validate forms client-side again on the server to ensure their integrity. This comes really useful in simply being DRY and not getting rules out of sync when something changes.

OwnerDisplayName: Chris

Title: Browserless JavaScript

LastEditorDisplayName: Chris

OwnerDisplayName: Paolo Bergantino

LastEditorDisplayName: Paolo Bergantino


问:
Using Firebase storage with AngularFire2
I'm converting my code to start using AF5 to interact with Firebase Storage but I am also configuring the metadata with firebase.storage.UploadMetadata. Can that be changed with AF5 and avoid importing the firebase library?

答:
Still, it hasn’t been publicly released.So you might need to install it as angularfire2@next.

Can that be changed with AF5 and avoid importing the firebase library?

Yes, You don't need to import entire firebase library.You just need to import AngularFireStorageModule.

```<code>import { AngularFireStorageModule } from 'angularfire2/storage';
</code>```

Here you can read more about it.

Body:
Still, it hasn’t been publicly released.So you might need to install it as angularfire2@next.

Can that be changed with AF5 and avoid importing the firebase library?

Yes, You don't need to import entire firebase library.You just need to import AngularFireStorageModule.

import { AngularFireStorageModule } from 'angularfire2/storage';

Here you can read more about it.


问:
Return variable from class defined in another thread
I'm programming an audio visualizer. To sync the data that is to be displayed to the music itself, I need to get the clip's/player's current position in the audio file by calling clip.getMicrosecondPosition() / player.getPosition(). This is working fine for the clip. The problem is that I need to define the player object in another thread since calling player.play() halts all execution in the current thread until the file is played until the end. Player is a class from the MP3SPI library (javazoom.jl.player.Player).

Code:

```<code>public class AudioTools implements Runnable {

public File file;
public boolean isMP3 = false;
public Player player;
public Clip clip;

public AudioTools(File file) {
    this.file = file;
    determineFilyType();
}

private void determineFileType() {
    if (file.getAbsolutePath().endsWith(".mp3")) {
        this.isMP3 = true;
    } else if (file.getAbsolutePath().endsWith(".wav")) {
        this.isMP3 = false;
    } else {
        System.err.println("Invalid File Type!");
        System.exit(0);
    }

}

public void play() {
    if (isMP3) {
        Thread t = new Thread(this);
        t.start(); // play MP3 using Player class
    } else {
        playWav(file); // play WAV using Clip class
    }

}

protected void playMP3(File file){
    try {
        player = new Player(new FileInputStream(file));
        player.play();
    } catch (Exception e) {
        System.out.println("Invalid MP3 File!");
        e.printStackTrace();
        System.exit(0);
    }

}

@Override
public void run() {
    playMP3(file);
}

private void playWav(File file) {
    try {
        AudioInputStream ais = AudioSystem.getAudioInputStream(file);
        DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
        clip = (Clip) AudioSystem.getLine(dataInfo);
        clip.open(ais);
        clip.start();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Invalid .wav file!");
        System.exit(0);
    }
}
</code>```

}

Main class:

```<code>public static void main(String[] args) {

File file = new File(/*PATH_TO_FILE_HERE*/);
AudioTools at = new AudioTools(file);
at.play();
// at.clip.getMicrosecondPosition() works here if loaded file is .wav.
// at.player.getPosition() returns null if loaded file is .mp3.
}
</code>```

From the main class, I'd like to be able to get the player's current position. Currently, trying this will return null.

Any helpful comments are appreciated. I've asked a similar question before, this edit made the question a bit more clear and shorter.

EDIT: Should contain all code necissary to run the example.

答: Solved using a different approach that isn't even part of the question. I already had an array of the decrypted audio data that I can turn into an AudioInputStream that Clip is able to play. </p>

Body:
I'm programming an audio visualizer. To sync the data that is to be displayed to the music itself, I need to get the clip's/player's current position in the audio file by calling clip.getMicrosecondPosition() / player.getPosition(). This is working fine for the clip. The problem is that I need to define the player object in another thread since calling player.play() halts all execution in the current thread until the file is played until the end. Player is a class from the MP3SPI library (javazoom.jl.player.Player).

Code:

public class AudioTools implements Runnable {

public File file;
public boolean isMP3 = false;
public Player player;
public Clip clip;

public AudioTools(File file) {
    this.file = file;
    determineFilyType();
}

private void determineFileType() {
    if (file.getAbsolutePath().endsWith(".mp3")) {
        this.isMP3 = true;
    } else if (file.getAbsolutePath().endsWith(".wav")) {
        this.isMP3 = false;
    } else {
        System.err.println("Invalid File Type!");
        System.exit(0);
    }

}

public void play() {
    if (isMP3) {
        Thread t = new Thread(this);
        t.start(); // play MP3 using Player class
    } else {
        playWav(file); // play WAV using Clip class
    }

}

protected void playMP3(File file){
    try {
        player = new Player(new FileInputStream(file));
        player.play();
    } catch (Exception e) {
        System.out.println("Invalid MP3 File!");
        e.printStackTrace();
        System.exit(0);
    }

}

@Override
public void run() {
    playMP3(file);
}

private void playWav(File file) {
    try {
        AudioInputStream ais = AudioSystem.getAudioInputStream(file);
        DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
        clip = (Clip) AudioSystem.getLine(dataInfo);
        clip.open(ais);
        clip.start();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Invalid .wav file!");
        System.exit(0);
    }
}

}

Main class:

public static void main(String[] args) {

File file = new File(/*PATH_TO_FILE_HERE*/);
AudioTools at = new AudioTools(file);
at.play();
// at.clip.getMicrosecondPosition() works here if loaded file is .wav.
// at.player.getPosition() returns null if loaded file is .mp3.
}

From the main class, I'd like to be able to get the player's current position. Currently, trying this will return null.

Any helpful comments are appreciated. I've asked a similar question before, this edit made the question a bit more clear and shorter.

EDIT: Should contain all code necissary to run the example.


问:
You can use a local server together with browser sync (gulp)
I have time using gulp, but I would like to know if using a local PHP server I can update the page immediately, or in its absence any other tool that allows me to update every change to PHP files</p>

答:
Add a php task to your gulpfile.</p>

```<code>var src = {
   php:'./public_html/**/*.php',
};

gulp.task('php', function(){
    gulp.src(src.php)
    .pipe(reload({stream:true}));
});

gulp.task ('watch', function(){
// other watch tasks
  gulp.watch(src.php, ['php']);

});
</code>```

Body:
Add a php task to your gulpfile.

var src = {
   php:'./public_html/**/*.php',
};

gulp.task('php', function(){
    gulp.src(src.php)
    .pipe(reload({stream:true}));
});

gulp.task ('watch', function(){
// other watch tasks
  gulp.watch(src.php, ['php']);

});


问:
How to update a child node that contains a specific value in the database
```<code>String userID = selectedCharacter.getUserID();
String charID = selectedCharacter.getCharID();
Character editedCharacter = new Character(userID, charID, name, hitPoints, armorClass, level, experience, gold);

            databaseRef
                    .orderByChild("charID")
                    .equalTo(selectedCharacter.getCharID())
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // Translate the character to a map of its data
                            Map<String,Object> updates = editedCharacter.toMap();
                            // Update ONLY the node with charID = editedCharacter.getCharID()
                            databaseRef.updateChildren(updates);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            throw databaseError.toException();
                        }
                    });
</code>```

So I'm trying to update a character's stats in my firebase database. As you can see:

here

the code I'm using is actually putting the update in character's root instead. What am I doing wrong here? I'm unsure of how to find the node with the key as I'm not storing the key anywhere.

答:
Instead of databaseRef.updateChildren(updates);

Could you try

databaseRef.child(dataSnapshot.getKey()).setValue(updates)

Then see if it works.

Body:
String userID = selectedCharacter.getUserID();
String charID = selectedCharacter.getCharID();
Character editedCharacter = new Character(userID, charID, name, hitPoints, armorClass, level, experience, gold);

            databaseRef
                    .orderByChild("charID")
                    .equalTo(selectedCharacter.getCharID())
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // Translate the character to a map of its data
                            Map<String,Object> updates = editedCharacter.toMap();
                            // Update ONLY the node with charID = editedCharacter.getCharID()
                            databaseRef.updateChildren(updates);
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                            throw databaseError.toException();
                        }
                    });

So I'm trying to update a character's stats in my firebase database. As you can see:

here

the code I'm using is actually putting the update in character's root instead. What am I doing wrong here? I'm unsure of how to find the node with the key as I'm not storing the key anywhere.


问:
Is it currently possible to build Eclipse Plugins by Maven AND have nice IDE Integration?
I'm currently evaluating maven to improve our build process. The building and creating of normal jar files works so far, although I'm not entirely happy with the Maven IDE.

I'm now at that point, where all libs I need for our project are built, and I'm moving on to the Eclipse RCP projects. And now I'm not sure how to go on.

There are some plugins I need to build first, before moving on to the actual RCP part. Therefore I have actually 3 problems.

I want to build those plugins, the only real solution for that seems to be the maven-bundle-plugin: http://felix.apache.org/site/apache-felix-maven-bundle-plugin-bnd.html

But, For nice IDE integration I also need the appropriate files (plugin.xml, build.properties, etc ...) which should be generated automatically.

For building the RCP parts, it seems so far the only solution is only the pde-maven-plugin http://mojo.codehaus.org/pde-maven-plugin/ which, as far as I can tell, uses ant-pde. This is stupid, isn't it?

The only other thing I could found was tycho (http://www.sonatype.com/people/2008/11/building-eclipse-plugins-with-maven-tycho/) , but this is till in a very early stage.

and again, a nice Eclipse integration is necessary. I really, really, really don't want to specify dependencies twice.

So How do you build your Eclipse RCP projects with maven?

Update

For now, it seems that there is no such solution available. Tycho looks very promising, but I wasted 2 days and didn't get it to run (the current version at this point). Maybe it will be ready in half a year or so.

答:
If u r building an Eclipse Plugin or application (RCP) Maven Tycho is the recommended way to build it.

It's pretty intelligent in resolving osgi dependencies. U can refer to my tutorials on Maven Tycho Tutorials

Maven Tycho requires m2eclipse and Tycho configurator installation.

And archetype should be eclipse-plugin or eclipse-feature or eclipse-repository

OwnerDisplayName: Mauli

LastEditorDisplayName: Mauli


答:
I think you made a few errors. It seems you lack a basic understanding of how these functions work. Almost all of them return some variable (like a link resource or a row array) that you can use in the rest of your code. If a call fails, these functions return false. So you should check if the value if explicitly false (by using the === operator) and only continue if everything is ok. Then, you must use the result value of the function, not the function itself. mysql_query is merely the call, not the result.

```<code><?php
$host = 'localhost';
$dbusername ='root';
$dbpassword ='';
$database ='mp19';

$link = mysql_connect('localhost', 'root','12345678');

if ($link === false)
{
    exit("Connection Failed: " . mysql_error());
}

if (mysql_select_db('mp19', $link) === false)
{
    exit("Could not select database mp19: " . mysql_error());
}

// Is '3-33' really your table name?! You should pick another name.
$sql = "(SELECT * FROM 3-33)";

$resultset = mysql_query($sql, $link);

// (!$sql)? $sql SQL is always set here. It is just the string
if ($resultset === false)
{
    exit("Error in SQL: " . mysql_error());
}

echo "<table><tr>";
echo "<th>Date</th>";

while ($row = mysql_fetch_assoc($resultset))
{
    $date = $row['fieldname'];
    echo "<td>$date</td></tr>";
}

mysql_close($link);

?>
</code>```

Title: Javascript and PHPMySQL

Body:
I think you made a few errors. It seems you lack a basic understanding of how these functions work. Almost all of them return some variable (like a link resource or a row array) that you can use in the rest of your code. If a call fails, these functions return false. So you should check if the value if explicitly false (by using the === operator) and only continue if everything is ok. Then, you must use the result value of the function, not the function itself. mysql_query is merely the call, not the result.

<?php
$host = 'localhost';
$dbusername ='root';
$dbpassword ='';
$database ='mp19';

$link = mysql_connect('localhost', 'root','12345678');

if ($link === false)
{
    exit("Connection Failed: " . mysql_error());
}

if (mysql_select_db('mp19', $link) === false)
{
    exit("Could not select database mp19: " . mysql_error());
}

// Is '3-33' really your table name?! You should pick another name.
$sql = "(SELECT * FROM 3-33)";

$resultset = mysql_query($sql, $link);

// (!$sql)? $sql SQL is always set here. It is just the string
if ($resultset === false)
{
    exit("Error in SQL: " . mysql_error());
}

echo "<table><tr>";
echo "<th>Date</th>";

while ($row = mysql_fetch_assoc($resultset))
{
    $date = $row['fieldname'];
    echo "<td>$date</td></tr>";
}

mysql_close($link);

?>