问:
How do I force the font color to remain the way it is rather than changing
My program basically highlights the keywords in text to the user choice font color.I have a problem only when displaying the search terms in the cell that is specified by the user not in actual execution of the program. I take the terms input, range/cell to display these terms, font color from the user. This is partial code:

```<code> Dim Ran As String
          searchTerms = InputBox("Please enter words to search, if more than one string seperate by comma and space", "Need Input", 1)

       Ran = InputBox("Please enter cell where you want the search terms to be displayed ideally below verbatim like C2,D2 ", "Need Input", 0, 8)
      r = Range(Ran).Row
      c = Range(Ran).Column

       If IsEmpty(Cells(r, 1)) And c <> "A" Then
         Range(Ran).Value = Range(Ran).Value & ", " & searchTerms
        Else: Range(Ran).EntireRow.Insert
        Range(Ran).Value = searchTerms
        End If

       searchTerms = Split(UCase(searchTerms), ", ")
</code>```

This works as expected for 2 executions but for third time execution the previous execution font color changes to the 1st execution color. How do I force it to remain as it was before execution. Suppose after 1st time execution it was yellow, After Second execution the appended variables were green, Then when I am performing the third execution the whole cell content change to yellow before peforming the execution and the only the third execution terms will change to user defined font color. But the Second execution appended terms will be yellow as first execution color.
This is the code which is highlighting function:

```<code>Function HilightString(offSet As Integer, searchString As String, rowNum As Long, ingredCol As String, FontColor, fontSize As Integer) As Integer

        Dim x As Integer
        Dim newOffset As Integer
        Dim targetString As Variant

         If Cells(rowNum, ingredCol).HasFormula Then
Cells(rowNum, ingredCol).Value = "'" & Cells(rowNum, ingredCol).Formula
End If
        targetString = Mid(Cells(rowNum, ingredCol), offSet)
        foundPos = InStr(UCase(targetString), searchString)

        If foundPos > 0 Then

            Cells(rowNum, ingredCol).Characters(offSet + foundPos - 1, Len(searchString)).Font.ColorIndex = FontColor

            Cells(rowNum, ingredCol).Characters(offSet + foundPos - 1, Len(searchString)).Font.Size = 14

            newOffset = offSet + foundPos + Len(searchString)

            x = HilightString(newOffset, searchString, rowNum, ingredCol, FontColor, fontSize)
        Else

            Exit Function

        End If
 End Function
</code>```

First execution highlighted turn, signal in blue and created in cell c2:

Second execution highlighted Rear in green It works fine till this point

Before complete third execution highlighted blink

After 3rd execution. The second executed words turn back to blue

答:
When you do this to add the new words:

```<code>Range(Ran).Value = Range(Ran).Value & ", " & searchTerms
</code>```

you cannot preserve multiple colors of text - replacing the content will just give the whole cell the color of the first letter.  That's OK for your first and second runs, but will fail from run 3 forward.

You need to add the new text using the Characters collection, not by replacing the whole cell content.

Example:

```<code>Sub Tester()

    Dim c As Range
    Set c = Range("A1")

    AddTextWithColor c, "first", vbRed
    AddTextWithColor c, "second", vbBlue
    AddTextWithColor c, "third", vbGreen

End Sub

Sub AddTextWithColor(c As Range, txt As String, clr As Long)
    Dim l As Long
    With c
        If Len(.Value) = 0 Then
            .Value = txt
        Else
            l = .Characters.Count
            'adds the new text without replacing existing formatting
            .Characters(l + 1, Len(txt) + 2).Text = "," & txt
        End If
        With .Characters(IIf(l = 0, 1, l + 2), Len(txt)).Font
            .Color = clr
            .Size = 14
        End With
    End With
End Sub
</code>```

Body:
My program basically highlights the keywords in text to the user choice font color.I have a problem only when displaying the search terms in the cell that is specified by the user not in actual execution of the program. I take the terms input, range/cell to display these terms, font color from the user. This is partial code:

 Dim Ran As String
          searchTerms = InputBox("Please enter words to search, if more than one string seperate by comma and space", "Need Input", 1)

       Ran = InputBox("Please enter cell where you want the search terms to be displayed ideally below verbatim like C2,D2 ", "Need Input", 0, 8)
      r = Range(Ran).Row
      c = Range(Ran).Column

       If IsEmpty(Cells(r, 1)) And c <> "A" Then
         Range(Ran).Value = Range(Ran).Value & ", " & searchTerms
        Else: Range(Ran).EntireRow.Insert
        Range(Ran).Value = searchTerms
        End If

       searchTerms = Split(UCase(searchTerms), ", ")

This works as expected for 2 executions but for third time execution the previous execution font color changes to the 1st execution color. How do I force it to remain as it was before execution. Suppose after 1st time execution it was yellow, After Second execution the appended variables were green, Then when I am performing the third execution the whole cell content change to yellow before peforming the execution and the only the third execution terms will change to user defined font color. But the Second execution appended terms will be yellow as first execution color.
This is the code which is highlighting function:

Function HilightString(offSet As Integer, searchString As String, rowNum As Long, ingredCol As String, FontColor, fontSize As Integer) As Integer

        Dim x As Integer
        Dim newOffset As Integer
        Dim targetString As Variant

         If Cells(rowNum, ingredCol).HasFormula Then
Cells(rowNum, ingredCol).Value = "'" & Cells(rowNum, ingredCol).Formula
End If
        targetString = Mid(Cells(rowNum, ingredCol), offSet)
        foundPos = InStr(UCase(targetString), searchString)

        If foundPos > 0 Then

            Cells(rowNum, ingredCol).Characters(offSet + foundPos - 1, Len(searchString)).Font.ColorIndex = FontColor

            Cells(rowNum, ingredCol).Characters(offSet + foundPos - 1, Len(searchString)).Font.Size = 14

            newOffset = offSet + foundPos + Len(searchString)

            x = HilightString(newOffset, searchString, rowNum, ingredCol, FontColor, fontSize)
        Else

            Exit Function

        End If
 End Function

First execution highlighted turn, signal in blue and created in cell c2:

Second execution highlighted Rear in green It works fine till this point

Before complete third execution highlighted blink

After 3rd execution. The second executed words turn back to blue

Body:
When you do this to add the new words:

Range(Ran).Value = Range(Ran).Value & ", " & searchTerms

you cannot preserve multiple colors of text - replacing the content will just give the whole cell the color of the first letter.  That's OK for your first and second runs, but will fail from run 3 forward.

You need to add the new text using the Characters collection, not by replacing the whole cell content.

Example:

Sub Tester()

    Dim c As Range
    Set c = Range("A1")

    AddTextWithColor c, "first", vbRed
    AddTextWithColor c, "second", vbBlue
    AddTextWithColor c, "third", vbGreen

End Sub

Sub AddTextWithColor(c As Range, txt As String, clr As Long)
    Dim l As Long
    With c
        If Len(.Value) = 0 Then
            .Value = txt
        Else
            l = .Characters.Count
            'adds the new text without replacing existing formatting
            .Characters(l + 1, Len(txt) + 2).Text = "," & txt
        End If
        With .Characters(IIf(l = 0, 1, l + 2), Len(txt)).Font
            .Color = clr
            .Size = 14
        End With
    End With
End Sub


来源: stackexchange

问:
juMP - use variable defined in sum range
I am trying to define a constraint containing summation over two indices, k and t.

```<code>for i in data.I
    for j in 1:length(data.P[i])
        @constraint(m, w[i, j, length(data.T[data.P[i][j]])]/(1+sum(data.A[i][k][t] for k in 1:length(data.P[i]), t in data.T[data.P[i][k]])) <= s[i, j])
    end
end
</code>```

I get the following error in running the code:

ERROR: LoadError: UndefVarError: k not defined

I have implemented the same model in OPL for CPLEX in the same way, and this was not an issue. Am I not allowed to introduce such variable as an index in the summation, then use it subsequently as an index to an array within the same sum() as I am trying to do above?

答:
This is a question of Julia syntax:

```<code>julia> sum(i+j for i in 1:3, j in 1:i)
ERROR: UndefVarError: i not defined

julia> sum(i+j for i in 1:3 for j in 1:i)
24
</code>```

The same should hold for JuMP.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to define a constraint containing summation over two indices, k and t.

for i in data.I
    for j in 1:length(data.P[i])
        @constraint(m, w[i, j, length(data.T[data.P[i][j]])]/(1+sum(data.A[i][k][t] for k in 1:length(data.P[i]), t in data.T[data.P[i][k]])) <= s[i, j])
    end
end

I get the following error in running the code:

ERROR: LoadError: UndefVarError: k not defined

I have implemented the same model in OPL for CPLEX in the same way, and this was not an issue. Am I not allowed to introduce such variable as an index in the summation, then use it subsequently as an index to an array within the same sum() as I am trying to do above?

Body:
This is a question of Julia syntax:

julia> sum(i+j for i in 1:3, j in 1:i)
ERROR: UndefVarError: i not defined

julia> sum(i+j for i in 1:3 for j in 1:i)
24

The same should hold for JuMP.


问:
Testing Codeception on Gitlab CI with Selenium service
I'm trying to setup selenium standalone chrome service to test my Codeception suit.

I run chrome standalone as a service:

```<code>services:
  - mysql:latest
  - selenium/standalone-chrome:latest
</code>```

And then I setup the connections for my Codeception test uses WebDriver with an extension for WordPress:

```<code>WPWebDriver:
   url: 'http://localhost'
   host: 'selenium__standalone-chrome'
   browser: chrome
   port: 4444
   restart: true
   wait: 2
   adminUsername: admin
   adminPassword: 1234
   adminUrl: /wp-admin
</code>```

All other tests run well but when it comes to the suite where I use Selenium it refuses to connect:

```<code>Time: 7.55 seconds, Memory: 16.00MB

There was 1 failure:

---------
1) SampleTestCept: Test if wp is working in selenium
 Test  tests/php/acceptance/SampleTestCept.php
 Step  See "Just another WordPress site"
 Fail  Failed asserting that  on page /
--> This site can’t be reached
localhost refused to connect.
Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
Reload
DETAILS
--> contains "this site can't be reached".

Scenario Steps:

 2. $I->see("This site can't be reached") at tests/php/acceptance/SampleTestCept.php:6
 1. $I->amOnPage("/") at tests/php/acceptance/SampleTestCept.php:4
</code>```

Any ideas of what am I doing wrong?

答: Use environment variable HOSTNAME, to find gitlab runner actual hostname.</p>

Body:
I'm trying to setup selenium standalone chrome service to test my Codeception suit.

I run chrome standalone as a service:

services:
  - mysql:latest
  - selenium/standalone-chrome:latest

And then I setup the connections for my Codeception test uses WebDriver with an extension for WordPress:

WPWebDriver:
   url: 'http://localhost'
   host: 'selenium__standalone-chrome'
   browser: chrome
   port: 4444
   restart: true
   wait: 2
   adminUsername: admin
   adminPassword: 1234
   adminUrl: /wp-admin

All other tests run well but when it comes to the suite where I use Selenium it refuses to connect:

Time: 7.55 seconds, Memory: 16.00MB

There was 1 failure:

---------
1) SampleTestCept: Test if wp is working in selenium
 Test  tests/php/acceptance/SampleTestCept.php
 Step  See "Just another WordPress site"
 Fail  Failed asserting that  on page /
--> This site can’t be reached
localhost refused to connect.
Try:
Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_REFUSED
Reload
DETAILS
--> contains "this site can't be reached".

Scenario Steps:

 2. $I->see("This site can't be reached") at tests/php/acceptance/SampleTestCept.php:6
 1. $I->amOnPage("/") at tests/php/acceptance/SampleTestCept.php:4

Any ideas of what am I doing wrong?


问:
RequestMapping in xml
I am new to Spring MVC 3.0, I have a background of struts 2.0.
I am comfortable with configuration in xml.

So, I am looking for a way to represent to @RequestMapping in the springdispatcher-servlet.xml or any other dependent xml.

Is there a way to move the @RequestMapping annotations to xml file?

As a side question,

what is the benefit of @RequestMapping on individual methods over struts single point of entry per Action?

Below is a sample class:

```<code>@Controller
public class ContentController {

    @RequestMapping(value="/content", method=RequestMethod.GET)
    public ModelAndView getContent() {
        // do something
    }

    @RequestMapping(value="/savecontent", method=RequestMethod.GET)
    public ModelAndView getSaveContent() {
        // do something
    }
}
</code>```

Regards.

答:
Not only is this possible, it was the only way to do it pre-Spring 2.5. Rather bizarrely, pretty much all mention of this has been removed from the Spring ref manual, even though it's still a perfectly valid way of mapping your requests.  The only mention of it I can stil lfind is section 15.4.1.

A simple example is:

```<code><bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
   <property name="mappings">
      <map>
         <entry key="/doSomething/**" value-ref="controllerA"/>
         <entry key="/other Thing/**" value-ref="controllerB"/>
      </map>
   </property>
</bean>
</code>```

ContentLicense: CC BY-SA 2.5

Title: RequestMapping in xml

Body:
I am new to Spring MVC 3.0, I have a background of struts 2.0.
I am comfortable with configuration in xml.

So, I am looking for a way to represent to @RequestMapping in the springdispatcher-servlet.xml or any other dependent xml.

Is there a way to move the @RequestMapping annotations to xml file?

As a side question,

what is the benefit of @RequestMapping on individual methods over struts single point of entry per Action?

Below is a sample class:

@Controller
public class ContentController {

    @RequestMapping(value="/content", method=RequestMethod.GET)
    public ModelAndView getContent() {
        // do something
    }

    @RequestMapping(value="/savecontent", method=RequestMethod.GET)
    public ModelAndView getSaveContent() {
        // do something
    }
}

Regards.

Body:
Not only is this possible, it was the only way to do it pre-Spring 2.5. Rather bizarrely, pretty much all mention of this has been removed from the Spring ref manual, even though it's still a perfectly valid way of mapping your requests.  The only mention of it I can stil lfind is section 15.4.1.

A simple example is:

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
   <property name="mappings">
      <map>
         <entry key="/doSomething/**" value-ref="controllerA"/>
         <entry key="/other Thing/**" value-ref="controllerB"/>
      </map>
   </property>
</bean>


问:
Merge two table based on row name
I need to merge two table into one based on Row name, each table has 172 rows and 172 columns example of my data look

```<code>#table 1
A B C
1 2 3
2 3 4
5 6 7

#table 2
A B C
1 3 8
2 4 6
5 4 2
</code>```

I want my output like this

```<code>A B C
1 2 3
1 3 8
2 3 4
2 4 6
5 6 7
5 4 2
</code>```

答:
```<code>mapply(rbind, table1, table2)
</code>```

This function is fine for your case. However, if the table that you have is like this:

```<code>  A B C
1 1 2 3
2 2 3 4
3 5 6 7

  A B C
1 5 4 2
2 2 4 6
3 1 3 8
</code>```

The function above will result in:

```<code>     A B C
[1,] 1 2 3
[2,] 5 4 2
[3,] 2 3 4
[4,] 2 4 6
[5,] 5 6 7
[6,] 1 3 8
</code>```

So if you want to get the result that you want, you can use this function:

```<code>rbind(table1,table2)[order(rbind(table1,table2)$A),]
</code>```

Title: Merge two table based on row name

Body:
I need to merge two table into one based on Row name, each table has 172 rows and 172 columns example of my data look

#table 1
A B C
1 2 3
2 3 4
5 6 7

#table 2
A B C
1 3 8
2 4 6
5 4 2

I want my output like this

A B C
1 2 3
1 3 8
2 3 4
2 4 6
5 6 7
5 4 2

Body:
mapply(rbind, table1, table2)

This function is fine for your case. However, if the table that you have is like this:

  A B C
1 1 2 3
2 2 3 4
3 5 6 7

  A B C
1 5 4 2
2 2 4 6
3 1 3 8

The function above will result in:

     A B C
[1,] 1 2 3
[2,] 5 4 2
[3,] 2 3 4
[4,] 2 4 6
[5,] 5 6 7
[6,] 1 3 8

So if you want to get the result that you want, you can use this function:

rbind(table1,table2)[order(rbind(table1,table2)$A),]


答:
For multiclass classification, LogisticRegressionWithLBFGS needs the number of classes argument numClasses, which you do not provide.

It is always a good idea to provide at least a sample of your data along with your question; since you don't, here is my attempt to reproduce your error with dummy data of my own:

from pyspark.mllib.classification import LogisticRegressionWithLBFGS, LogisticRegressionModel
from pyspark.mllib.regression import LabeledPoint

parsed_data = [LabeledPoint(0, [4.6,3.6,1.0,0.2]),  # 3 classes
                LabeledPoint(0, [5.7,4.4,1.5,0.4]),
                LabeledPoint(1, [6.7,3.1,4.4,1.4]),
                LabeledPoint(2, [4.8,3.4,1.6,0.2]),
                LabeledPoint(1, [4.4,3.2,1.3,0.2])]

model = LogisticRegressionWithLBFGS.train(sc.parallelize(parsed_data)) # this will reproduce your error:
[...]
Py4JJavaError: An error occurred while calling o168.trainLogisticRegressionModelWithLBFGS.
: org.apache.spark.SparkException: Multinomial models contain a matrix of coefficients, use coefficientMatrix instead.
[...]

# set numClasses=3:
model = LogisticRegressionWithLBFGS.train(sc.parallelize(parsed_data), numClasses=3) # works OK
```

(Tested with Spark 2.1.1)

Title: Py4JavaError when calling LogisticRegressionModelWithLBFGS.train

Body:
I have a training set of 5000 rows and 401 columns wherein  column 1 is the label and the remaining 400 columns are features.
I am trying to do a multiclass logistic regression using pyspark mllib. Please find my code below. I must confess , this not an optimized /well written code as I am still a newbie in the field of python/pyspark.

tset=sio.loadmat('ex3data1.mat') # load the training set from a mat file
X=tset['X']                      # read the X,y values
y=tset['y']
print(X.shape) # works!
print(y.shape)
sp=
SparkSession.builder.master("local").appName("multiclassifier").getOrCreate()
sc=sp.sparkContext
XY=np.concatenate((y,X),axis=1) # 5000x401 where the first col is the label.
print(XY[0:2])

sample output of the print above. Please note that I only printing the first row

[[  1.00000000e+01   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    8.56059680e-06   1.94035948e-06  -7.37438725e-04  -8.13403799e-03
   -1.86104473e-02  -1.87412865e-02  -1.87572508e-02  -1.90963542e-02
   -1.64039011e-02  -3.78191381e-03   3.30347316e-04   1.27655229e-05
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   1.16421569e-04
    1.20052179e-04  -1.40444581e-02  -2.84542484e-02   8.03826593e-02
    2.66540339e-01   2.73853746e-01   2.78729541e-01   2.74293607e-01
    2.24676403e-01   2.77562977e-02  -7.06315478e-03   2.34715414e-04
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   1.28335523e-17  -3.26286765e-04
   -1.38651604e-02   8.15651552e-02   3.82800381e-01   8.57849775e-01
    1.00109761e+00   9.69710638e-01   9.30928598e-01   1.00383757e+00
    9.64157356e-01   4.49256553e-01  -5.60408259e-03  -3.78319036e-03
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    5.10620915e-06   4.36410675e-04  -3.95509940e-03  -2.68537241e-02
    1.00755014e-01   6.42031710e-01   1.03136838e+00   8.50968614e-01
    5.43122379e-01   3.42599738e-01   2.68918777e-01   6.68374643e-01
    1.01256958e+00   9.03795598e-01   1.04481574e-01  -1.66424973e-02
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    2.59875260e-05  -3.10606987e-03   7.52456076e-03   1.77539831e-01
    7.92890120e-01   9.65626503e-01   4.63166079e-01   6.91720680e-02
   -3.64100526e-03  -4.12180405e-02  -5.01900656e-02   1.56102907e-01
    9.01762651e-01   1.04748346e+00   1.51055252e-01  -2.16044665e-02
    0.00000000e+00   0.00000000e+00   0.00000000e+00   5.87012352e-05
   -6.40931373e-04  -3.23305249e-02   2.78203465e-01   9.36720163e-01
    1.04320956e+00   5.98003217e-01  -3.59409041e-03  -2.16751770e-02
   -4.81021923e-03   6.16566793e-05  -1.23773318e-02   1.55477482e-01
    9.14867477e-01   9.20401348e-01   1.09173902e-01  -1.71058007e-02
    0.00000000e+00   0.00000000e+00   1.56250000e-04  -4.27724104e-04
   -2.51466503e-02   1.30532561e-01   7.81664862e-01   1.02836583e+00
    7.57137601e-01   2.84667194e-01   4.86865128e-03  -3.18688725e-03
    0.00000000e+00   8.36492601e-04  -3.70751123e-02   4.52644165e-01
    1.03180133e+00   5.39028101e-01  -2.43742611e-03  -4.80290033e-03
    0.00000000e+00   0.00000000e+00  -7.03635621e-04  -1.27262443e-02
    1.61706648e-01   7.79865383e-01   1.03676705e+00   8.04490400e-01
    1.60586724e-01  -1.38173339e-02   2.14879493e-03  -2.12622549e-04
    2.04248366e-04  -6.85907627e-03   4.31712963e-04   7.20680947e-01
    8.48136063e-01   1.51383408e-01  -2.28404366e-02   1.98971950e-04
    0.00000000e+00   0.00000000e+00  -9.40410539e-03   3.74520505e-02
    6.94389110e-01   1.02844844e+00   1.01648066e+00   8.80488426e-01
    3.92123945e-01  -1.74122413e-02  -1.20098039e-04   5.55215142e-05
   -2.23907271e-03  -2.76068376e-02   3.68645493e-01   9.36411169e-01
    4.59006723e-01  -4.24701797e-02   1.17356610e-03   1.88929739e-05
    0.00000000e+00   0.00000000e+00  -1.93511951e-02   1.29999794e-01
    9.79821705e-01   9.41862388e-01   7.75147704e-01   8.73632241e-01
    2.12778350e-01  -1.72353349e-02   0.00000000e+00   1.09937426e-03
   -2.61793751e-02   1.22872879e-01   8.30812662e-01   7.26501773e-01
    5.24441863e-02  -6.18971913e-03   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00  -9.36563862e-03   3.68349741e-02
    6.99079299e-01   1.00293583e+00   6.05704402e-01   3.27299224e-01
   -3.22099249e-02  -4.83053002e-02  -4.34069138e-02  -5.75151144e-02
    9.55674190e-02   7.26512627e-01   6.95366966e-01   1.47114481e-01
   -1.20048679e-02  -3.02798203e-04   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00  -6.76572712e-04  -6.51415556e-03
    1.17339359e-01   4.21948410e-01   9.93210937e-01   8.82013974e-01
    7.45758734e-01   7.23874268e-01   7.23341725e-01   7.20020340e-01
    8.45324959e-01   8.31859739e-01   6.88831870e-02  -2.77765012e-02
    3.59136710e-04   7.14869281e-05   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   1.53186275e-04   3.17353553e-04
   -2.29167177e-02  -4.14402914e-03   3.87038450e-01   5.04583435e-01
    7.74885876e-01   9.90037446e-01   1.00769478e+00   1.00851440e+00
    7.37905042e-01   2.15455291e-01  -2.69624864e-02   1.32506127e-03
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    2.36366422e-04  -2.26031454e-03  -2.51994485e-02  -3.73889910e-02
    6.62121228e-02   2.91134498e-01   3.23055726e-01   3.06260315e-01
    8.76070942e-02  -2.50581917e-02   2.37438725e-04   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   6.20939216e-18   6.72618320e-04
   -1.13151411e-02  -3.54641066e-02  -3.88214912e-02  -3.71077412e-02
   -1.33524928e-02   9.90964718e-04   4.89176960e-05   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
    0.00000000e+00]]

end of print output.

pXYdf=pd.DataFrame(XY)
sXYdf=sp.createDataFrame(pXYdf)

from pyspark.mllib.classification import LogisticRegressionWithLBFGS,
LogisticRegressionModel
import pyspark.mllib.regression as reg

trainingData = sXYdf.rdd.map(lambda x: reg.LabeledPoint(x[0],x[1:]))
trainingData.take(2) # this works!!

output of 1 record in LabeledPoint format: ( i am unable to properly format that here as there are 400 features here.

[LabeledPoint(10.0,[0.0,0.0,0.0,0.0,0.0,0.0,....,8.56059679589e-06, 1.94035947712e06,.........]),

lrm=LogisticRegressionWithLBFGS.train(trainingData)

I am getting the following error:

Py4JJavaError: An error occurred while calling o168.trainLogisticRegressionModelWithLBFGS.
: org.apache.spark.SparkException: Multinomial models contain a matrix of coefficients, use coefficientMatrix instead.
[...]

Body:
For multiclass classification, LogisticRegressionWithLBFGS needs the number of classes argument numClasses, which you do not provide.

It is always a good idea to provide at least a sample of your data along with your question; since you don't, here is my attempt to reproduce your error with dummy data of my own:

from pyspark.mllib.classification import LogisticRegressionWithLBFGS, LogisticRegressionModel
from pyspark.mllib.regression import LabeledPoint

parsed_data = [LabeledPoint(0, [4.6,3.6,1.0,0.2]),  # 3 classes
                LabeledPoint(0, [5.7,4.4,1.5,0.4]),
                LabeledPoint(1, [6.7,3.1,4.4,1.4]),
                LabeledPoint(2, [4.8,3.4,1.6,0.2]),
                LabeledPoint(1, [4.4,3.2,1.3,0.2])]

model = LogisticRegressionWithLBFGS.train(sc.parallelize(parsed_data)) # this will reproduce your error:
[...]
Py4JJavaError: An error occurred while calling o168.trainLogisticRegressionModelWithLBFGS.
: org.apache.spark.SparkException: Multinomial models contain a matrix of coefficients, use coefficientMatrix instead.
[...]

# set numClasses=3:
model = LogisticRegressionWithLBFGS.train(sc.parallelize(parsed_data), numClasses=3) # works OK

(Tested with Spark 2.1.1)


问:
How do you ensure the area of a reactive probability density function is fixed to 1?
I have the following code which allows the user to adjust the parameters of the beta distribution (p, q) via the Shiny GUI.

However, as theta must be within the range 0 to 1, my code is missing a step that basically ensures the area under the curve is always equal to 1 regardless of parameter choice.

I cannot think how to go about this so any help is much appreciated.

```<code># Required packages
require(shiny)
require(ggplot2)
require(gridExtra)

# Beta plot function
betaFun <- function(p = 1.1, q = 1.1){

  prior <- function(theta){
    (theta ^ (p - 1)) * ((1 - theta) ^ (q - 1))
  }

  priorFill <- function(theta){
    ifelse(prior(theta) > 0 & prior(theta) < 1, prior(theta), NA)
  }

  ggplot(data = data.frame(x = as.double(0)), mapping = aes(x = x)) +
  stat_function(fun = prior, col = 'blue') +
  stat_function(fun = priorFill, geom = "area", fill = "blue", alpha = 0.2) +
  geom_segment(x = 0, y = 0, xend = 1, yend = 0, color = 'blue') +
  xlim(0, 1) +
  ylim(0, 1)

}

# UI
ui <- fluidPage(
  titlePanel("Beta Distribution"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("pInput", "Parameter p", min = 1.1, max = 5, value = 1, step = 0.1),
      sliderInput("qInput", "Parameter q", min = 1.1, max = 5, value = 1, step = 0.1)
  ),

    mainPanel(
      plotOutput("betaPlot")
    )
  )
)

# Server
server <- function(input, output) {
  output$betaPlot <- renderPlot({
    betaFun(p = input$pInput,
            q = input$qInput)
  })
}

# Execution
shinyApp(ui = ui, server = server)
</code>```

答:
One way to do this would be to calculate all the values before running ggplot (instead of on the fly using stat_function) so that you can normalize to an area of one up front. Then you can plot using geom_line instead of stat_function. For example:

```<code># Required packages
require(shiny)
require(ggplot2)
require(gridExtra)

# Beta plot function
betaFun <- function(p = 1.1, q = 1.1){

  theta = seq(0,1,length=1000)
  dat = data.frame(theta, prior=(theta ^ (p - 1)) * ((1 - theta) ^ (q - 1)))
  dat$prior = dat$prior/(sum(dat$prior)*mean(diff(theta)))  # Normalize to area = 1

  ggplot(dat, aes(theta, prior)) +
    geom_line(color="blue") +
    geom_area(alpha=0.2, fill="blue") +
    geom_segment(x = 0, y = 0, xend = 1, yend = 0, color = 'blue') +
    xlim(0, 1) +
    ylim(0, 5) +
    theme_classic(base_size=15)

}

# UI
ui <- fluidPage(
  titlePanel("Beta Distribution"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("pInput", "Parameter p", min = 1.1, max = 5, value = 1, step = 0.1),
      sliderInput("qInput", "Parameter q", min = 1.1, max = 5, value = 1, step = 0.1)
    ),

    mainPanel(
      plotOutput("betaPlot")
    )
  )
)

# Server
server <- function(input, output) {
  output$betaPlot <- renderPlot({
    betaFun(p = input$pInput,
            q = input$qInput)
  })
}

# Execution
shinyApp(ui = ui, server = server)
</code>```

Body:
I have the following code which allows the user to adjust the parameters of the beta distribution (p, q) via the Shiny GUI.

However, as theta must be within the range 0 to 1, my code is missing a step that basically ensures the area under the curve is always equal to 1 regardless of parameter choice.

I cannot think how to go about this so any help is much appreciated.

# Required packages
require(shiny)
require(ggplot2)
require(gridExtra)

# Beta plot function
betaFun <- function(p = 1.1, q = 1.1){

  prior <- function(theta){
    (theta ^ (p - 1)) * ((1 - theta) ^ (q - 1))
  }

  priorFill <- function(theta){
    ifelse(prior(theta) > 0 & prior(theta) < 1, prior(theta), NA)
  }

  ggplot(data = data.frame(x = as.double(0)), mapping = aes(x = x)) +
  stat_function(fun = prior, col = 'blue') +
  stat_function(fun = priorFill, geom = "area", fill = "blue", alpha = 0.2) +
  geom_segment(x = 0, y = 0, xend = 1, yend = 0, color = 'blue') +
  xlim(0, 1) +
  ylim(0, 1)

}

# UI
ui <- fluidPage(
  titlePanel("Beta Distribution"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("pInput", "Parameter p", min = 1.1, max = 5, value = 1, step = 0.1),
      sliderInput("qInput", "Parameter q", min = 1.1, max = 5, value = 1, step = 0.1)
  ),

    mainPanel(
      plotOutput("betaPlot")
    )
  )
)

# Server
server <- function(input, output) {
  output$betaPlot <- renderPlot({
    betaFun(p = input$pInput,
            q = input$qInput)
  })
}

# Execution
shinyApp(ui = ui, server = server)

Body:
One way to do this would be to calculate all the values before running ggplot (instead of on the fly using stat_function) so that you can normalize to an area of one up front. Then you can plot using geom_line instead of stat_function. For example:

# Required packages
require(shiny)
require(ggplot2)
require(gridExtra)

# Beta plot function
betaFun <- function(p = 1.1, q = 1.1){

  theta = seq(0,1,length=1000)
  dat = data.frame(theta, prior=(theta ^ (p - 1)) * ((1 - theta) ^ (q - 1)))
  dat$prior = dat$prior/(sum(dat$prior)*mean(diff(theta)))  # Normalize to area = 1

  ggplot(dat, aes(theta, prior)) +
    geom_line(color="blue") +
    geom_area(alpha=0.2, fill="blue") +
    geom_segment(x = 0, y = 0, xend = 1, yend = 0, color = 'blue') +
    xlim(0, 1) +
    ylim(0, 5) +
    theme_classic(base_size=15)

}

# UI
ui <- fluidPage(
  titlePanel("Beta Distribution"),

  sidebarLayout(
    sidebarPanel(
      sliderInput("pInput", "Parameter p", min = 1.1, max = 5, value = 1, step = 0.1),
      sliderInput("qInput", "Parameter q", min = 1.1, max = 5, value = 1, step = 0.1)
    ),

    mainPanel(
      plotOutput("betaPlot")
    )
  )
)

# Server
server <- function(input, output) {
  output$betaPlot <- renderPlot({
    betaFun(p = input$pInput,
            q = input$qInput)
  })
}

# Execution
shinyApp(ui = ui, server = server)


问:
Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'
I'm new in angular 2 and i try to make a reactive form but i have some trouble. After many search in stack i found no solutions.

Here you can see my error

The code :

View :

User data

            <form [formGroup]="userForm">

                    name
                    <input type="text" class="form-control" formControlName="name">

                    email
                    <input type="text" class="form-control" formControlName="email">

                        Rue
                        <input type="text" class="form-control" formControlName="rue">

                        Ville
                        <input type="text" class="form-control" formControlName="ville">

                        Cp
                        <input type="text" class="form-control" formControlName="cp">

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>

```
<p>My module.ts</p>
<pre class="lang-js prettyprint-override"><code>    import { NgModule }      from '@angular/core';
    import { CommonModule }  from '@angular/common';
    import { BrowserModule } from '@angular/platform-browser';
    import { ContactComponent } from './contact.component';
    import { FormGroup , FormControl , ReactiveFormsModule , FormsModule } from '@angular/forms';

    @NgModule({
      imports: [
        NgModule,
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        FormGroup,
        FormControl
      ],
      declarations: [
        ContactComponent
      ]
    })
    export class ContactModule {}

And my component.ts

    import {Component} from '@angular/core';
    import { FormGroup , FormControl } from '@angular/forms';

    @Component({
      selector: 'contact',
      templateUrl: './contact.component.html'
      // styleUrls: ['../../app.component.css']
    })
    export class ContactComponent {

        userForm = new FormGroup({
            name: new FormControl(),
            email: new FormControl(),
            adresse: new FormGroup({
                rue: new FormControl(),
                ville: new FormControl(),
                cp: new FormControl(),
            })
        });
    }
</code>```

I don't understand my error because import of ReactiveForm is here. So ... i need your help :) Thanks

After I read your answer and refactoring my code, it's ok, that works! The problem was i import reactive module in the module of my page contact and i need import this in module of my app. So thanks a lot for your interest :)

Hope this answer help another people guys.

答:
Try to add ReactiveFormsModule in your component as well.</p>

```<code>import { FormGroup, FormArray, FormBuilder,
          Validators,ReactiveFormsModule  } from '@angular/forms';
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm new in angular 2 and i try to make a reactive form but i have some trouble. After many search in stack i found no solutions.

Here you can see my error

The code :

View :

User data

            <form [formGroup]="userForm">

                    name
                    <input type="text" class="form-control" formControlName="name">

                    email
                    <input type="text" class="form-control" formControlName="email">

                        Rue
                        <input type="text" class="form-control" formControlName="rue">

                        Ville
                        <input type="text" class="form-control" formControlName="ville">

                        Cp
                        <input type="text" class="form-control" formControlName="cp">

                <button type="submit" class="btn btn-primary">Submit</button>
            </form>

My module.ts

    import { NgModule }      from '@angular/core';
    import { CommonModule }  from '@angular/common';
    import { BrowserModule } from '@angular/platform-browser';
    import { ContactComponent } from './contact.component';
    import { FormGroup , FormControl , ReactiveFormsModule , FormsModule } from '@angular/forms';

    @NgModule({
      imports: [
        NgModule,
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        FormGroup,
        FormControl
      ],
      declarations: [
        ContactComponent
      ]
    })
    export class ContactModule {}

And my component.ts

    import {Component} from '@angular/core';
    import { FormGroup , FormControl } from '@angular/forms';

    @Component({
      selector: 'contact',
      templateUrl: './contact.component.html'
      // styleUrls: ['../../app.component.css']
    })
    export class ContactComponent {

        userForm = new FormGroup({
            name: new FormControl(),
            email: new FormControl(),
            adresse: new FormGroup({
                rue: new FormControl(),
                ville: new FormControl(),
                cp: new FormControl(),
            })
        });
    }

I don't understand my error because import of ReactiveForm is here. So ... i need your help :) Thanks

After I read your answer and refactoring my code, it's ok, that works! The problem was i import reactive module in the module of my page contact and i need import this in module of my app. So thanks a lot for your interest :)

Hope this answer help another people guys.

Body:
Try to add ReactiveFormsModule in your component as well.

import { FormGroup, FormArray, FormBuilder,
          Validators,ReactiveFormsModule  } from '@angular/forms';


问:
R merge multiple files into 1 dataframe and keep all values
I have 6 multiple files, each having only 1 column of names. I want to read all these files and combine them in 1 dataframe so that it looks like this:

```<code>file1  file2  file3  file4  file5  file6
adam   adam   adam   adam   adam   adam
Roy    NA     Roy    Roy    NA     NA
NA     Sam    Sam    NA     NA     NA
</code>```

The colnames of resulting dataframe should represent the actual file names. Let's say that the file I read were named file1.txt, file2.txt and so on..

Any help will be much appreciated.

What I've been trying so far:

```<code>multmerge = function(mypath){
+ filenames=list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
+ datalist = lapply(filenames, function(x){read.csv(file=x,header=F)})
+ Reduce(function(x,y) {merge(x,y, all.x=T)}, datalist)}
> mymergeddata = multmerge("/Path/To/The/Folder/Having/All/Files")
> dim(mymergeddata)
[1] 11508     1
</code>```

As seen here it is combining all values (names) in one column..

答:
Another solution with purrr::map

```<code>files <- list.files("/path/",full.names = TRUE)

combinedDF <- files %>% map(read.csv, stringsAsFactors=FALSE, col.names=files) %>%
  reduce(cbind)
</code>```

Body:
I have 6 multiple files, each having only 1 column of names. I want to read all these files and combine them in 1 dataframe so that it looks like this:

file1  file2  file3  file4  file5  file6
adam   adam   adam   adam   adam   adam
Roy    NA     Roy    Roy    NA     NA
NA     Sam    Sam    NA     NA     NA

The colnames of resulting dataframe should represent the actual file names. Let's say that the file I read were named file1.txt, file2.txt and so on..

Any help will be much appreciated.

What I've been trying so far:

multmerge = function(mypath){
+ filenames=list.files(path=mypath, full.names=TRUE, pattern = "\\.txt$")
+ datalist = lapply(filenames, function(x){read.csv(file=x,header=F)})
+ Reduce(function(x,y) {merge(x,y, all.x=T)}, datalist)}
> mymergeddata = multmerge("/Path/To/The/Folder/Having/All/Files")
> dim(mymergeddata)
[1] 11508     1

As seen here it is combining all values (names) in one column..

Body:
Another solution with purrr::map

files <- list.files("/path/",full.names = TRUE)

combinedDF <- files %>% map(read.csv, stringsAsFactors=FALSE, col.names=files) %>%
  reduce(cbind)


问:
Bootstrap navbar is displaying vertically instead of horizontally
I'm working on a project using CodePen and I'm using bootstrap to make a navbar. But for some reason it's displaying vertically instead of horizontally. Even when I copy and paste code from the W3Schools examples and the Bootstrap website. I don't know what else to do. Please help.

This is the W3Schools example code:

```<code>    <nav class="navbar navbar-default">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">WebSiteName</a>
        </div>
        <ul class="nav navbar-nav">
          <li class="active"><a href="#">Home</a></li>
          <li><a href="#">Page 1</a></li>
          <li><a href="#">Page 2</a></li>
          <li><a href="#">Page 3</a></li>
        </ul>
      </div>
</code>```

This is example code from the Bootstrap website:

```<code>    <nav class="navbar navbar-default">
      <div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <a class="navbar-brand" href="#">Brand</a>
</div>

<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
    <li><a href="#">Link</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">One more separated link</a></li>
      </ul>
    </li>
  </ul>
  <form class="navbar-form navbar-left">
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Search">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
  <ul class="nav navbar-nav navbar-right">
    <li><a href="#">Link</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
      </ul>
    </li>
  </ul>
</div><!-- /.navbar-collapse -->
</code>```

Both do not work. And  yes, I've triple checked my <link> and

答:
First like in the comments you are using bootstrap 3 markup and you are linking to both bootstrap 3 and 4 remove the bootstrap 4 css.  Then you need to have the div with the class of collapse navbar-collapse so just add this to the div that has the id of nav just like the following:

```<code><nav class="navbar navbar-inverse">
  <div class="container-fluid">

    <div class="navbar-header">
      <a class="navbar-brand" href="#about">
        <span style="font-family: 'Source Code Pro', Monospace; color:green"><i class="fa fa-code"></i>Ryan</span></a>
    </div>
    <div class="collapse navbar-collapse"  id="nav">
    <ul class="nav navbar-nav">
      <li><a href="#about">About</a></li>
      <li><a href="#portfolio">Portfolio</a></li>
      <li><a href="#contact">Contact</a></li>
    </ul>
    </div>
  </div>
</nav>
</code>```

You may want to add the collapse button to the navbar header as well otherwise your links wont show up at mobile widths so it would look like:

```<code><nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#nav" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#about">
        <span style="font-family: 'Source Code Pro', Monospace; color:green"><i class="fa fa-code"></i>Ryan</span>
      </a>
    </div>
    <div class="collapse navbar-collapse"  id="nav">
    <ul class="nav navbar-nav">
      <li><a href="#about">About</a></li>
      <li><a href="#portfolio">Portfolio</a></li>
      <li><a href="#contact">Contact</a></li>
    </ul>
    </div>
  </div>
</nav>
</code>```

Body:
I'm working on a project using CodePen and I'm using bootstrap to make a navbar. But for some reason it's displaying vertically instead of horizontally. Even when I copy and paste code from the W3Schools examples and the Bootstrap website. I don't know what else to do. Please help.

This is the W3Schools example code:

          WebSiteName

Home

Page 1

Page 2

Page 3

This is example code from the Bootstrap website:

  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    Toggle navigation

  </button>
  Brand

Link (current)

Link

      Dropdown

Action

Another action

Something else here

Separated link

One more separated link

  <form class="navbar-form navbar-left">

      <input type="text" class="form-control" placeholder="Search">

    <button type="submit" class="btn btn-default">Submit</button>
  </form>

Link

      Dropdown

Action

Another action

Something else here

Separated link

Both do not work. And  yes, I've triple checked my <link> and

Body:
First like in the comments you are using bootstrap 3 markup and you are linking to both bootstrap 3 and 4 remove the bootstrap 4 css.  Then you need to have the div with the class of collapse navbar-collapse so just add this to the div that has the id of nav just like the following:

<nav class="navbar navbar-inverse">
  <div class="container-fluid">

    <div class="navbar-header">
      <a class="navbar-brand" href="#about">
        <span style="font-family: 'Source Code Pro', Monospace; color:green"><i class="fa fa-code"></i>Ryan</span></a>
    </div>
    <div class="collapse navbar-collapse"  id="nav">
    <ul class="nav navbar-nav">
      <li><a href="#about">About</a></li>
      <li><a href="#portfolio">Portfolio</a></li>
      <li><a href="#contact">Contact</a></li>
    </ul>
    </div>
  </div>
</nav>

You may want to add the collapse button to the navbar header as well otherwise your links wont show up at mobile widths so it would look like:

<nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#nav" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#about">
        <span style="font-family: 'Source Code Pro', Monospace; color:green"><i class="fa fa-code"></i>Ryan</span>
      </a>
    </div>
    <div class="collapse navbar-collapse"  id="nav">
    <ul class="nav navbar-nav">
      <li><a href="#about">About</a></li>
      <li><a href="#portfolio">Portfolio</a></li>
      <li><a href="#contact">Contact</a></li>
    </ul>
    </div>
  </div>
</nav>


问:
Taxonomy/Ontology of software bugs?
Is there a taxonomy of ontology of software bugs?</p>

答: Security-wise, a well known taxonomy of software bugs (introduced to a wider audience by Gary McGraw in his series of books on software security) distinguishes between an implementation bug and a design flaw. An implementation bug is a low-level defect lurking in your implementation. A typical example for an implementation bug is a buffer overflow. A design flaw, on the other hand, is a 'logic' bug within your implementation that allows a malicious person to break or circumvent your system or some security mechanism you implemented simply by using it in a manner you didn't anticipate. A good example for this are flaws in API design which allow an attacker to combine specific calls to the API to force the system to do things that the designers of the system did not anticipate.

Title: Taxonomy/Ontology of software bugs?


问:
How to make data grid autoscrolling?
After adding some other elements in the Grid, I found my data grid is no longer auto scrolling.
I want to know how to make Data grid autoscrolling in any case.</p>

答:
Check the below link and see if it solves your problem

how can I enable scrollbars on the WPF Datagrid?

Title: How to make data grid autoscrolling?


问:
Phonegap disable Camera configuration
I'm working on an application for Android and IOS. In the application the user should be able to make some pictures, so I call the camera in Cordova with navigator.camera.getPicture().
Is there any chance to disable all the configurations in the Camera Application which will be Called? So the User isn't able to activate flash, go to settings menue from camera, can't switch to front camera and so on. So he is only able to take a picture.

Unfortunately I think this isn't possible but maybe someone of you knows the gold Answer!

Thanks!

答:
I don't think this is possible using the standard camera plugin provided by phonegap. https://github.com/apache/cordova-plugin-camera#module_camera.getPicture displays a full reference for the camera plug in and doesn't mention anywhere about having these capabilities.

One solution is that you could utilise this plugin: https://www.npmjs.com/package/cordova-plugin-camera-preview#camera_Settings.FlashMode.

It would allow you to create your own camera interface where you wouldn't need to give the user access to any additional features other than taking a picture.

Title: Phonegap disable Camera configuration


问:
navigating through a list of components
I am using reactjs to try and navigate through a list of components using the keyboard kind of like how you can navigate through facebook using the j and k keys. How can I shift focus to the first component in the list using the j key when I first land on the page and then shift focus between the components after using j and k?

```<code><ul className={s.feed}>
  {this.props.data.map((item, index) => {
    <li key={index} className={s.componentContainer}>
      <Component component={item} />
    </li>
  })}
</ul>
</code>```

so what the code does is basically generates components into the ordered list and im just wondering how I can shift focus between them with the j and k keys and not using tab.

答:
Currently I am working on similar problem.

Suppose you have such state:

```<code>items = [
    {
        name: 'a',
        onFocus: true
    },
    {
        name: 'b',
        onFocus: false
    }
];
</code>```

In you lifecicle methods add and remove enent listeners

```<code>componentWillMount() {
    document.addEventListener("keydown", this.handleKeyDown, false);
}
componentWillUnmount() {
    document.removeEventListener("keydown", this.handleKeyDown);
}
</code>```

here is handleKeyDown - you just set onFocus value in the handler:

```<code>handleKeyDown(e) {
    let index = -1;
    const items = this.state.items;
    items.map((item, i) =>{
        if(item.onFocus)index = i;
    });

    switch(e.keyCode) {
        case 74:
            e.preventDefault();
            if(index > 0) i--;
            break;
        case 75:
            e.preventDefault();
            if(index < this.state.items.length - 1) i++;
            break;
    }
    for(let i = 0; i < items.length; i++) {
        items[i].onFocus = i === index;
    }
    this.setState({items});
}
</code>```

And depending on which element has onFocus set to true - you can set (for example) appropriate classes:

```<code><ul>
  {this.props.data.map((item, i) => {
    <li key={i}>
      <Component component={item} className={item.onFocus ? 'active' : ''} />
    </li>
  })}
</ul>
</code>```

Title: navigating through a list of components

Body:
I am using reactjs to try and navigate through a list of components using the keyboard kind of like how you can navigate through facebook using the j and k keys. How can I shift focus to the first component in the list using the j key when I first land on the page and then shift focus between the components after using j and k?

  {this.props.data.map((item, index) => {

      <Component component={item} />

  })}

so what the code does is basically generates components into the ordered list and im just wondering how I can shift focus between them with the j and k keys and not using tab.

Body:
Currently I am working on similar problem.

Suppose you have such state:

items = [
    {
        name: 'a',
        onFocus: true
    },
    {
        name: 'b',
        onFocus: false
    }
];

In you lifecicle methods add and remove enent listeners

componentWillMount() {
    document.addEventListener("keydown", this.handleKeyDown, false);
}
componentWillUnmount() {
    document.removeEventListener("keydown", this.handleKeyDown);
}

here is handleKeyDown - you just set onFocus value in the handler:

handleKeyDown(e) {
    let index = -1;
    const items = this.state.items;
    items.map((item, i) =>{
        if(item.onFocus)index = i;
    });

    switch(e.keyCode) {
        case 74:
            e.preventDefault();
            if(index > 0) i--;
            break;
        case 75:
            e.preventDefault();
            if(index < this.state.items.length - 1) i++;
            break;
    }
    for(let i = 0; i < items.length; i++) {
        items[i].onFocus = i === index;
    }
    this.setState({items});
}

And depending on which element has onFocus set to true - you can set (for example) appropriate classes:

<ul>
  {this.props.data.map((item, i) => {
    <li key={i}>
      <Component component={item} className={item.onFocus ? 'active' : ''} />
    </li>
  })}
</ul>


问:
Animated SVG Circle Background Image
I need to add a background image to my SVG circle.  But, nothing I've tried thus far has worked.

Here's what I've tried so far...

```<code><svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px">
    <defs>
        <pattern id="image" x="0" y="0" patternUnits="userSpaceOnUse" height="40px" width="40px">
            <image x="0" y="0"height="40px" width="40px" xlink:href="url.png"></image>
        </pattern>
    </defs>
    <g transform="translate(40,40)">
        <circle cx="0" cy="0" r="20" class="circle base" fill="url(#image)"></circle>
        <circle cx="0" cy="0" r="20" class="circle progress" fill="url(#image)"></circle>
    </g>
</svg>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px">
    <g transform="translate(40,40)">
        <defs>
            <pattern id="image" x="0" y="0" patternUnits="userSpaceOnUse" height="40px" width="40px">
                <image x="0" y="0" height="40px" width="40px" xlink:href="url.png"></image>
            </pattern>
        </defs>
        <circle cx="0" cy="0" r="20" class="circle base" fill="url(#image)"></circle>
        <circle cx="0" cy="0" r="20" class="circle progress" fill="url(#image)"></circle>
    </g>
</svg>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px">
    <filter id="this_image" x="0%" y="0%" width="100%" height="100%">
        <feImage xlink:href="url.png"/>
    </filter>
    <g transform="translate(40,40)">
        <circle cx="0" cy="0" r="20" class="circle base" fill="url(#this_image)"></circle>
        <circle cx="0" cy="0" r="20" class="circle progress" fill="url(#this_image)"></circle>
    </g>
</svg>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px">
    <g transform="translate(40,40)">
        <filter id="this_image" x="0%" y="0%" width="100%" height="100%">
            <feImage xlink:href="url.png"/>
        </filter>
        <circle cx="0" cy="0" r="20" class="circle base" fill="url(#this_image)"></circle>
        <circle cx="0" cy="0" r="20" class="circle progress" fill="url(#this_image)"></circle>
    </g>
</svg>
</code>```

Here's a jsfiddle mockup.

Would appreciate any suggestions.  Clearly, I'm unsure whether the filter/defs-pattern should go inside the SVG or the transform

答:
Your pattern fills are not working for one simple reason. This:</p>

```<code>circle { ... fill:none; ... }
</code>```

Title: Animated SVG Circle Background Image

Body:
I need to add a background image to my SVG circle.  But, nothing I've tried thus far has worked.

Here's what I've tried so far...

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px">
    <defs>
        <pattern id="image" x="0" y="0" patternUnits="userSpaceOnUse" height="40px" width="40px">
            <image x="0" y="0"height="40px" width="40px" xlink:href="url.png"></image>
        </pattern>
    </defs>
    <g transform="translate(40,40)">
        <circle cx="0" cy="0" r="20" class="circle base" fill="url(#image)"></circle>
        <circle cx="0" cy="0" r="20" class="circle progress" fill="url(#image)"></circle>
    </g>
</svg>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px">
    <g transform="translate(40,40)">
        <defs>
            <pattern id="image" x="0" y="0" patternUnits="userSpaceOnUse" height="40px" width="40px">
                <image x="0" y="0" height="40px" width="40px" xlink:href="url.png"></image>
            </pattern>
        </defs>
        <circle cx="0" cy="0" r="20" class="circle base" fill="url(#image)"></circle>
        <circle cx="0" cy="0" r="20" class="circle progress" fill="url(#image)"></circle>
    </g>
</svg>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px">
    <filter id="this_image" x="0%" y="0%" width="100%" height="100%">
        <feImage xlink:href="url.png"/>
    </filter>
    <g transform="translate(40,40)">
        <circle cx="0" cy="0" r="20" class="circle base" fill="url(#this_image)"></circle>
        <circle cx="0" cy="0" r="20" class="circle progress" fill="url(#this_image)"></circle>
    </g>
</svg>

<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px">
    <g transform="translate(40,40)">
        <filter id="this_image" x="0%" y="0%" width="100%" height="100%">
            <feImage xlink:href="url.png"/>
        </filter>
        <circle cx="0" cy="0" r="20" class="circle base" fill="url(#this_image)"></circle>
        <circle cx="0" cy="0" r="20" class="circle progress" fill="url(#this_image)"></circle>
    </g>
</svg>

Here's a jsfiddle mockup.

Would appreciate any suggestions.  Clearly, I'm unsure whether the filter/defs-pattern should go inside the SVG or the transform

Body:
Your pattern fills are not working for one simple reason. This:

circle { ... fill:none; ... }


问:
Python/Tkinter Audio Player
I'm developing a media player. Right now it's a simple window with a button to load .wav files. The problem is I would like to implement a pause button now. But, when playing a audio file the GUI isn't accessible again (no buttons can be pushed) till the file is done playing. How can I make the GUI dynamic while an audio file is playing?

I'm using PyAudio, and their implementation doesn't allow this.

答:
Try this out:
Check the code https://drive.google.com/file/d/0B7ccI33Aew5fNVhwZ2puYTBuUFU/view?usp=sharing
I have used pygame also.Hope this helps.</p>

Title: Python/Tkinter Audio Player


问:
react-particle-js not updating the number of particles
I have:

```<code>return (
  <Particles
    style={{
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      zIndex: -1
    }}
    params={{
      number: {
        value: 400,
        density: {
          enable: true,
          value_area: 800
        }
      },
      line_linked: {
        enable: true,
        distance: 150,
        color: "#ffffff",
        opacity: 0.4,
        width: 1
      },
      "shape": {
        "type": "circle",
        "stroke": {
          "width": 0,
          "color": "#000000"
        },
        polygon: {
          nb_sides: 7
        }
      },
      "interactivity": {
        "detect_on": "canvas",
        "events": {
          "onhover": {
            "enable": true,
            "mode": "grab"
          },
          "onclick": {
            "enable": true,
            "mode": "push"
          },
          "resize": true
        },
        "modes": {
          "grab": {
            "distance": 400,
            "line_linked": {
              "opacity": 1
            }
          },
          "repulse": {
            "distance": 200,
            "duration": 0.4
          }
        }
      },
      "retina_detect": true
    }} />
</code>```

No matter how high I make number.value, the number of particles on the screen just doesn't increase. Any thoughts on what I'm doing wrong?

答:
You've missed to enclose this properties inside particles. Also remove the z-index property from styles or set it to 0 that will display the particles

```<code>particles: {
  number: {
    value: 400,
    density: {
      enable: true,
      value_area: 800
    }
  },
  line_linked: {
    enable: true,
    distance: 150,
    color: "#ffffff",
    opacity: 0.4,
    width: 1
  },
  "shape": {
    "type": "circle",
    "stroke": {
      "width": 0,
      "color": "#000000"
    },
    polygon: {
      nb_sides: 7
    }
  }
 },
  "interactivity": {
    "detect_on": "canvas",
    "events": {
      "onhover": {
        "enable": true,
        "mode": "grab"
      },
      "onclick": {
        "enable": true,
        "mode": "push"
      },
      "resize": true
    },
    "modes": {
      "grab": {
        "distance": 400,
        "line_linked": {
          "opacity": 1
        }
      },
      "repulse": {
        "distance": 200,
        "duration": 0.4
      }
    }
  },
  "retina_detect": true
</code>```

Body:
I have:

return (
  <Particles
    style={{
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      zIndex: -1
    }}
    params={{
      number: {
        value: 400,
        density: {
          enable: true,
          value_area: 800
        }
      },
      line_linked: {
        enable: true,
        distance: 150,
        color: "#ffffff",
        opacity: 0.4,
        width: 1
      },
      "shape": {
        "type": "circle",
        "stroke": {
          "width": 0,
          "color": "#000000"
        },
        polygon: {
          nb_sides: 7
        }
      },
      "interactivity": {
        "detect_on": "canvas",
        "events": {
          "onhover": {
            "enable": true,
            "mode": "grab"
          },
          "onclick": {
            "enable": true,
            "mode": "push"
          },
          "resize": true
        },
        "modes": {
          "grab": {
            "distance": 400,
            "line_linked": {
              "opacity": 1
            }
          },
          "repulse": {
            "distance": 200,
            "duration": 0.4
          }
        }
      },
      "retina_detect": true
    }} />

No matter how high I make number.value, the number of particles on the screen just doesn't increase. Any thoughts on what I'm doing wrong?

Body:
You've missed to enclose this properties inside particles. Also remove the z-index property from styles or set it to 0 that will display the particles

particles: {
  number: {
    value: 400,
    density: {
      enable: true,
      value_area: 800
    }
  },
  line_linked: {
    enable: true,
    distance: 150,
    color: "#ffffff",
    opacity: 0.4,
    width: 1
  },
  "shape": {
    "type": "circle",
    "stroke": {
      "width": 0,
      "color": "#000000"
    },
    polygon: {
      nb_sides: 7
    }
  }
 },
  "interactivity": {
    "detect_on": "canvas",
    "events": {
      "onhover": {
        "enable": true,
        "mode": "grab"
      },
      "onclick": {
        "enable": true,
        "mode": "push"
      },
      "resize": true
    },
    "modes": {
      "grab": {
        "distance": 400,
        "line_linked": {
          "opacity": 1
        }
      },
      "repulse": {
        "distance": 200,
        "duration": 0.4
      }
    }
  },
  "retina_detect": true


问:
How to load a Swing GUI Form using a JavaFX controller (Button in JavaFX)
I want to load a Java Swing GUI form using a JavaFX controller. This should happen when the button is clicked in the JavaFX File, then the Swing GUI form should be loaded.

I tried to load a Swing GUI form using the normal way but it didn't work.

```<code>Example ex=new Example;
ex.setVisible(true);
</code>```

答:
Could you be more specific with what you are asking?
I ran the following code successfully.

```<code>@FXML
private void handleButtonAction(ActionEvent event) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            JFrame frame = new JFrame("FrameDemo");

            // 2. Optional: What happens when the frame closes?
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            // 3. Create components and put them in the frame.
            // ...create emptyLabel...
            frame.getContentPane().add(new JLabel("Test"), BorderLayout.CENTER);

            // 4. Size the frame.
            frame.pack();

            // 5. Show it.
            frame.setVisible(true);
        }
    });
}
</code>```

handleButtonAction is a function in the controller class of my JavaFX project.

Did you want to create a separate window, or embed Swing in a JavaFX Window?

Body:
I want to load a Java Swing GUI form using a JavaFX controller. This should happen when the button is clicked in the JavaFX File, then the Swing GUI form should be loaded.

I tried to load a Swing GUI form using the normal way but it didn't work.

Example ex=new Example;
ex.setVisible(true);

Body:
Could you be more specific with what you are asking?
I ran the following code successfully.

@FXML
private void handleButtonAction(ActionEvent event) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            JFrame frame = new JFrame("FrameDemo");

            // 2. Optional: What happens when the frame closes?
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            // 3. Create components and put them in the frame.
            // ...create emptyLabel...
            frame.getContentPane().add(new JLabel("Test"), BorderLayout.CENTER);

            // 4. Size the frame.
            frame.pack();

            // 5. Show it.
            frame.setVisible(true);
        }
    });
}

handleButtonAction is a function in the controller class of my JavaFX project.

Did you want to create a separate window, or embed Swing in a JavaFX Window?


问:
PostgreSQL connection for IIS Server using ASP.NET C#
newB here. I'm creating a website using ASP.NET connecting to POSTGRESQL Database. It works fine in my localhost but when I deploy to IIS Server im getting an error: "The type or namespace name "Npsql" could not be found (Are you missing a using directive or an assembly reference?)" is there I need to install to IIS?</p>

答: Make sure that your NPSQL dll is available.</p>


问:
Issue with mysql node js
I have recently installed MySQL on my Ubuntu 16.04. And I have successfully been able to use commands in the command prompt to create tables, and do commands like

```<code>select * from articles
</code>```

However, the issue appears when I run code from a .js file from node.js. The command line just freezes afterwards. In the picture below, the terminal on the right is the one calling the select.js file with node, while the one on the left is manually calling select * from articles:

Interestingly enough, when I use the insert.js file, the same thing happens in the terminal on the right BUT the line is inserted (which I can verify manually with the terminal on the left).

QUESTION:
Why might the terminal on the right not finish executing and in the case of the select * from articles not display the content inside the articles table?

答:
It's because you'r not closing db connection after select so there is something in event loop.

Add connection.end(); after console.log(query.sql);
and console.log(result); to display results

Title: Issue with mysql node js

Body:
I have recently installed MySQL on my Ubuntu 16.04. And I have successfully been able to use commands in the command prompt to create tables, and do commands like

select * from articles

However, the issue appears when I run code from a .js file from node.js. The command line just freezes afterwards. In the picture below, the terminal on the right is the one calling the select.js file with node, while the one on the left is manually calling select * from articles:

Interestingly enough, when I use the insert.js file, the same thing happens in the terminal on the right BUT the line is inserted (which I can verify manually with the terminal on the left).

QUESTION:
Why might the terminal on the right not finish executing and in the case of the select * from articles not display the content inside the articles table?


问:
Error when using DataPicker with tabsLayout
so I have been doing this project, that when you click the button , it displays the date , and the button goes invisible, the TextView that will display the data is currently invisible behind the button. The button happens to be in a tab .Well the problem is when I run the app it gives me this error.It isn't a duplicate because I think that I have initialized the Button before starting the onClickListener, so I don't get why it is null.Maybe because its from a tabbed activity=

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pedrogouveia.averagemaker/com.pedrogouveia.averagemaker.Testes}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
</code>```

well here is the code:
Java :

```<code>public class Testes extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;
private DatePickerDialog.OnDateSetListener hourSetListener;
private DatePickerDialog.OnDateSetListener dateSetListener;
private Button date_button;
private Button hora_picker;
private TextView date_text;
private TextView hora_text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testes);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    date_button=(Button) findViewById(R.id.date_button);

    date_button.setOnClickListener(
            new Button.OnClickListener(){
                public void onClick(View v){
                        Calendar cal = Calendar.getInstance();
                        int year = cal.get(Calendar.YEAR);
                        int month = cal.get(Calendar.MONTH);
                        int day = cal.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog date_dialog = new DatePickerDialog(
                                Testes.this,
                                android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                                hourSetListener,
                                year, month, day);
                        date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        date_dialog.show();

                    };
                }

    );

    dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month=month+1;
            date_button.setVisibility(View.GONE);
            date_text = (TextView) findViewById(R.id.date_text);
            date_text.setVisibility(View.VISIBLE);
            String dt = day+"-"+month+"-"+year;
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            try {
                sdf.parse(dt);
                date_text.setText(dt);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    };

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_testes, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()){
       case go_to_fazer_media:{
           if (item.isChecked())
               item.setChecked(false);
            else{
           Intent i = new Intent(Testes.this,Formas.class);
           startActivity(i);
               return true;
            }
       }
       case definicoes:{
           if (item.isChecked())
               item.setChecked(false);
           else{
              return true;
           }
       }
   }

    return super.onOptionsItemSelected(item);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch(position){

            case 0:
                Tab1tests tab1 =  new Tab1tests();
                return tab1;
            case 1:
                Tab2calendar tab2 =  new Tab2calendar();
                return tab2;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Adicionar Testes";
            case 1:
                return "Mapa de Testes";
        }
        return null;
    }
}}
</code>```

XML:

```<code>    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/disciplina"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/section_label"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Disciplina:"
    android:textSize="35sp" />

<TextView
    android:id="@+id/sala"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/disciplina"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Sala:"
    android:textSize="35sp"/>

<TextView
    android:id="@+id/Dia"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/sala"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Dia:"
    android:textSize="35sp" />

<TextView
    android:id="@+id/Hora"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/Dia"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Hora:"
    android:textSize="35sp" />

<Button
    android:id="@+id/add_test"
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_marginBottom="95dp"
    android:text="Adicionar o teste"
    android:textSize="20sp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

<TextView
    android:id="@+id/date_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/hora_picker"
    android:layout_alignTop="@+id/Dia"
    android:text="ESCOLHER DATA"
    android:textSize="25sp"
    android:textStyle="bold"
    android:visibility="invisible"/>

<Button
    android:id="@+id/date_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/hora_picker"
    android:layout_alignTop="@+id/Dia"
    android:text="ESCOLHER DATA"
    android:textSize="25sp"
    android:textStyle="bold"
    android:onClick="setDate"/>

<TextView
    android:id="@+id/hora_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="ESCOLHER HORA"
    android:textStyle="bold"
    android:textSize="25sp"
    android:layout_alignBottom="@+id/Hora"
    android:layout_toEndOf="@+id/Hora"
    android:visibility="invisible"/>
<Button
    android:id="@+id/hora_picker"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="ESCOLHER HORA"
    android:textStyle="bold"
    android:textSize="25sp"
    android:layout_alignBaseline="@+id/Hora"
    android:layout_alignBottom="@+id/Hora"
    android:layout_toEndOf="@+id/sala" />

<EditText
    android:id="@+id/sala_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/sala"
    android:layout_toEndOf="@+id/Hora"
    android:ems="10"
    android:hint="Nª/Nome da sala"
    android:textSize="25sp"
    android:inputType="textPersonName" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/disciplina"
    android:layout_toEndOf="@+id/disciplina"
    android:scrollbarSize="25sp"
    android:layout_alignTop="@+id/disciplina" />
</code>```

Here is a image of the layout:
Layout image

答:
you have a problem at you click listener change , you need to use View.OnClickListener()

from

```<code>date_button.setOnClickListener(
            new Button.OnClickListener(){
</code>```

to

```<code> date_button.setOnClickListener(
                new View.OnClickListener(){
</code>```

Body:
so I have been doing this project, that when you click the button , it displays the date , and the button goes invisible, the TextView that will display the data is currently invisible behind the button. The button happens to be in a tab .Well the problem is when I run the app it gives me this error.It isn't a duplicate because I think that I have initialized the Button before starting the onClickListener, so I don't get why it is null.Maybe because its from a tabbed activity=

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pedrogouveia.averagemaker/com.pedrogouveia.averagemaker.Testes}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

well here is the code:
Java :

public class Testes extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;
private DatePickerDialog.OnDateSetListener hourSetListener;
private DatePickerDialog.OnDateSetListener dateSetListener;
private Button date_button;
private Button hora_picker;
private TextView date_text;
private TextView hora_text;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testes);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    date_button=(Button) findViewById(R.id.date_button);

    date_button.setOnClickListener(
            new Button.OnClickListener(){
                public void onClick(View v){
                        Calendar cal = Calendar.getInstance();
                        int year = cal.get(Calendar.YEAR);
                        int month = cal.get(Calendar.MONTH);
                        int day = cal.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog date_dialog = new DatePickerDialog(
                                Testes.this,
                                android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                                hourSetListener,
                                year, month, day);
                        date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        date_dialog.show();

                    };
                }

    );

    dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month=month+1;
            date_button.setVisibility(View.GONE);
            date_text = (TextView) findViewById(R.id.date_text);
            date_text.setVisibility(View.VISIBLE);
            String dt = day+"-"+month+"-"+year;
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            try {
                sdf.parse(dt);
                date_text.setText(dt);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    };

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_testes, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()){
       case go_to_fazer_media:{
           if (item.isChecked())
               item.setChecked(false);
            else{
           Intent i = new Intent(Testes.this,Formas.class);
           startActivity(i);
               return true;
            }
       }
       case definicoes:{
           if (item.isChecked())
               item.setChecked(false);
           else{
              return true;
           }
       }
   }

    return super.onOptionsItemSelected(item);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch(position){

            case 0:
                Tab1tests tab1 =  new Tab1tests();
                return tab1;
            case 1:
                Tab2calendar tab2 =  new Tab2calendar();
                return tab2;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Adicionar Testes";
            case 1:
                return "Mapa de Testes";
        }
        return null;
    }
}}

XML:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/disciplina"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/section_label"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Disciplina:"
    android:textSize="35sp" />

<TextView
    android:id="@+id/sala"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/disciplina"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Sala:"
    android:textSize="35sp"/>

<TextView
    android:id="@+id/Dia"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/sala"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Dia:"
    android:textSize="35sp" />

<TextView
    android:id="@+id/Hora"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/Dia"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Hora:"
    android:textSize="35sp" />

<Button
    android:id="@+id/add_test"
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_marginBottom="95dp"
    android:text="Adicionar o teste"
    android:textSize="20sp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

<TextView
    android:id="@+id/date_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/hora_picker"
    android:layout_alignTop="@+id/Dia"
    android:text="ESCOLHER DATA"
    android:textSize="25sp"
    android:textStyle="bold"
    android:visibility="invisible"/>

<Button
    android:id="@+id/date_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/hora_picker"
    android:layout_alignTop="@+id/Dia"
    android:text="ESCOLHER DATA"
    android:textSize="25sp"
    android:textStyle="bold"
    android:onClick="setDate"/>

<TextView
    android:id="@+id/hora_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="ESCOLHER HORA"
    android:textStyle="bold"
    android:textSize="25sp"
    android:layout_alignBottom="@+id/Hora"
    android:layout_toEndOf="@+id/Hora"
    android:visibility="invisible"/>
<Button
    android:id="@+id/hora_picker"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="ESCOLHER HORA"
    android:textStyle="bold"
    android:textSize="25sp"
    android:layout_alignBaseline="@+id/Hora"
    android:layout_alignBottom="@+id/Hora"
    android:layout_toEndOf="@+id/sala" />

<EditText
    android:id="@+id/sala_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/sala"
    android:layout_toEndOf="@+id/Hora"
    android:ems="10"
    android:hint="Nª/Nome da sala"
    android:textSize="25sp"
    android:inputType="textPersonName" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/disciplina"
    android:layout_toEndOf="@+id/disciplina"
    android:scrollbarSize="25sp"
    android:layout_alignTop="@+id/disciplina" />

Here is a image of the layout:
Layout image

Body:
you have a problem at you click listener change , you need to use View.OnClickListener()

from

date_button.setOnClickListener(
            new Button.OnClickListener(){

to

 date_button.setOnClickListener(
                new View.OnClickListener(){


问:
Change a variable name in all places in Python
I have written a code in Python3 using the IDE Wing, but I want to change a variable name, e.g., var_1, to var_2 in all places in my file. In MATLAB, when you change a variable name in one place, by Shift+Enter it is automatically done for all other occurrences of that variable in the file. Is there any similar way to do it in Python?

答:
You can accomplish this using nearly any text editor you want by using the Find and Replace feature.

The normal keyboard shortcut (including python's IDLE) for this is Ctrl+H, though different editors have different shortcuts.