问:
Listening to store change in redux saga
I'm trying to create a redux saga that will listen to a change for one variable in the state. When it does change, I want to dispatch some other action. Is this possible?

This is what I want to do:

```<code>yield takeLatest(fooAction, fetchAll);

function* fetchAll() {
   const part = yield select(getPartOfState);
   if (part.flag) {
      yield call(listenToChange);
   }
}

function* listenToChange() {
   const anotherPart = yield select(getAnotherPartOfState);
   if (anotherPart === true) { // this is what I want to wait for
      // do something
   }
}
</code>```

So I basically want to wait for anotherPart to change, because initially it will be false, and execute this in the loop just once (even if the listenToChange gets executed multiple times. Is this possible?

答:
As Alex mentioned in his comment, listening to a state change comes down to listening to the actions that are likely to trigger a change of this piece of state.

The take effect can take various patterns describing actions as a parameter, which can help you do just that: an action, an array of actions, a function, etc.. If you don't want to whitelist such actions, you can even call take without an argument (or with the string '*' if you want to be more explicit), which gives you a chance to inspect state after every action.

With this is mind, a saga waiting for a piece of state to have a given value could be written like this:

```<code>function *waitForStateToHaveValue(selector, expectedValue) {
  let stateSlice = yield select(selector);
  while (stateSlice !== expectedValue) {
    yield take();
    stateSlice = yield select(selector);
  }
}
</code>```

Title: Listening to store change in redux saga

Body:
I'm trying to create a redux saga that will listen to a change for one variable in the state. When it does change, I want to dispatch some other action. Is this possible?

This is what I want to do:

yield takeLatest(fooAction, fetchAll);

function* fetchAll() {
   const part = yield select(getPartOfState);
   if (part.flag) {
      yield call(listenToChange);
   }
}

function* listenToChange() {
   const anotherPart = yield select(getAnotherPartOfState);
   if (anotherPart === true) { // this is what I want to wait for
      // do something
   }
}

So I basically want to wait for anotherPart to change, because initially it will be false, and execute this in the loop just once (even if the listenToChange gets executed multiple times. Is this possible?

Body:
As Alex mentioned in his comment, listening to a state change comes down to listening to the actions that are likely to trigger a change of this piece of state.

The take effect can take various patterns describing actions as a parameter, which can help you do just that: an action, an array of actions, a function, etc.. If you don't want to whitelist such actions, you can even call take without an argument (or with the string '*' if you want to be more explicit), which gives you a chance to inspect state after every action.

With this is mind, a saga waiting for a piece of state to have a given value could be written like this:

function *waitForStateToHaveValue(selector, expectedValue) {
  let stateSlice = yield select(selector);
  while (stateSlice !== expectedValue) {
    yield take();
    stateSlice = yield select(selector);
  }
}


来源: stackexchange

问:
Make UITextField accept small alphabet letter only in Swift?
I Want to Make textField that accept only small alphabet letter not capital alphabet letter or no any special symbol or not any digit.</p>

答:
Try this below code only getting small letters automatically.</p>

```<code>import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textEntry: UITextField!

   //MARK : - Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
       textEntry.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)
    }

    //MARK: - Lower letter function
    func textFieldDidChange(sender: UITextField) {
        sender.text = sender.text?.lowercased()
        print(textEntry.text ?? "") //Check your text output here
    }
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try this below code only getting small letters automatically.

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var textEntry: UITextField!

   //MARK : - Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
       textEntry.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)
    }

    //MARK: - Lower letter function
    func textFieldDidChange(sender: UITextField) {
        sender.text = sender.text?.lowercased()
        print(textEntry.text ?? "") //Check your text output here
    }
 }


答:
You may use this too, </p>

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Return false when user tries to delete but textField is empty
    let currentCharacterCount = textField.text?.characters.count ?? 0
    if (range.length + range.location > currentCharacterCount) {
        return false
    }

    // Return true when user tries to delete but textField is not empty
    if string == "" {
        return true
    }

    let userEnteredString = textField.text ?? ""
    let newString = (userEnteredString as NSString).replacingCharacters(in: range, with: string) as NSString

    return ((newString as String).range(of: "^[a-z]+$", options: .regularExpression) != nil)

}
</code>```

Title: Make UITextField accept small alphabet letter only in Swift?

Body: I Want to Make textField that accept only small alphabet letter not capital alphabet letter or no any special symbol or not any digit.

Body:
You may use this too,

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    // Return false when user tries to delete but textField is empty
    let currentCharacterCount = textField.text?.characters.count ?? 0
    if (range.length + range.location > currentCharacterCount) {
        return false
    }

    // Return true when user tries to delete but textField is not empty
    if string == "" {
        return true
    }

    let userEnteredString = textField.text ?? ""
    let newString = (userEnteredString as NSString).replacingCharacters(in: range, with: string) as NSString

    return ((newString as String).range(of: "^[a-z]+$", options: .regularExpression) != nil)

}


问:
How do I check if the username value is already in the database in visual basic?
```<code>Private Sub SignUpBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SignUpBtn.Click
    'ttp://www.sourcecodester.com/tutorials/visual-basic-net/7258/adding-and-saving-records-access-database-using-vbnet.html
    Try

        cm = New OleDb.OleDbCommand
        With cm
            .Connection = cn
            .CommandType = CommandType.Text
            .CommandText = "INSERT INTO Users (UserName,UserPassword) VALUES (@Uname,@Pword)"

            .Parameters.Add(New System.Data.OleDb.OleDbParameter("@UserName", System.Data.OleDb.OleDbType.VarChar, 255, Me.Uname.Text))
            .Parameters.Add(New System.Data.OleDb.OleDbParameter("@UserPassword", System.Data.OleDb.OleDbType.VarChar, 255, Me.Pword.Text))

            Me.Uname.Text = MainClass.consoleout

            ' RUN THE COMMAND
            cm.Parameters("@UserName").Value = Me.Uname.Text
            cm.Parameters("@UserPassword").Value = Me.Pword.Text

            cm.ExecuteNonQuery()
            MsgBox("Record saved.", MsgBoxStyle.Information)
            Dim Form1 As New Form1
            Form1.Show()
            Hide()

            Exit Sub
        End With
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical)
    End Try
End Sub
</code>```

I'm trying to make this form with a check that if the username entered is the same as a username in the database. Currently I can save any user over and over again and the record is just repeated in the database. My username text box is called Uname and my password text box is called Pword. The database table is called Users and the columns I trying to put them is called UserName And UserPassword. My database connection has already been declared in the Module. I got all of the coding for this from a website(http://www.sourcecodester.com/tutorials/visual-basic-net/7258/adding-and-saving-records-access-database-using-vbnet.html). I just modified it to suit my conditions. If someone could tell me how to make sure that no 2 usernames are saved in the database I would be very grateful.

答:
Add a (or rather: the missing) unique index on the field Uname.

Then catch and handle the error when attempting to insert a duplicate.

Body:
Private Sub SignUpBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SignUpBtn.Click
    'ttp://www.sourcecodester.com/tutorials/visual-basic-net/7258/adding-and-saving-records-access-database-using-vbnet.html
    Try

        cm = New OleDb.OleDbCommand
        With cm
            .Connection = cn
            .CommandType = CommandType.Text
            .CommandText = "INSERT INTO Users (UserName,UserPassword) VALUES (@Uname,@Pword)"

            .Parameters.Add(New System.Data.OleDb.OleDbParameter("@UserName", System.Data.OleDb.OleDbType.VarChar, 255, Me.Uname.Text))
            .Parameters.Add(New System.Data.OleDb.OleDbParameter("@UserPassword", System.Data.OleDb.OleDbType.VarChar, 255, Me.Pword.Text))

            Me.Uname.Text = MainClass.consoleout

            ' RUN THE COMMAND
            cm.Parameters("@UserName").Value = Me.Uname.Text
            cm.Parameters("@UserPassword").Value = Me.Pword.Text

            cm.ExecuteNonQuery()
            MsgBox("Record saved.", MsgBoxStyle.Information)
            Dim Form1 As New Form1
            Form1.Show()
            Hide()

            Exit Sub
        End With
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical)
    End Try
End Sub

I'm trying to make this form with a check that if the username entered is the same as a username in the database. Currently I can save any user over and over again and the record is just repeated in the database. My username text box is called Uname and my password text box is called Pword. The database table is called Users and the columns I trying to put them is called UserName And UserPassword. My database connection has already been declared in the Module. I got all of the coding for this from a website(http://www.sourcecodester.com/tutorials/visual-basic-net/7258/adding-and-saving-records-access-database-using-vbnet.html). I just modified it to suit my conditions. If someone could tell me how to make sure that no 2 usernames are saved in the database I would be very grateful.


问:
Pseudo Distributed Mode Hadoop
I have installed  Pseudo Distributed mode Hadoop 2.7.3 in Mac & did all Configuration which is specified in Plural Sight. I Copied Csv file from Local to hdfs. But next day when i searched for files , it is not present in hdfs and removed automatically. Is there any other conf setting so that my files are not loss?

core-site.xml

<configuration>
   <property>
      <name>fs.defaultFS</name>
      <value>hdfs://localhost:9000</value>
   </property>
</configuration>
```

<p>hdfs-site.xml</p>

<pre class="lang-xml prettyprint-override"><code><configuration>
   <property>
      <name>dfs.replication</name>
      <value>1</value>
   </property>
</configuration>
</code>```

Thanks,

答:
Add these properties to hdfs-site.xml

```<code><property>
   <name>dfs.namenode.name.dir</name>
   <value>/home/username/hadoop-dfs/name</value>
</property>
<property>
   <name>dfs.datanode.data.dir</name>
   <value>/home/username/hadoop-dfs/data</value>
</property>
</code>```

The metadata and data blocks are stored under /tmp by default as it is the value of hadoop.tmp.dir. The contents inside /tmp are deleted on reboot.

After adding these properties, format the namenode and start the services.

Title: Pseudo Distributed Mode Hadoop

Body:
I have installed  Pseudo Distributed mode Hadoop 2.7.3 in Mac & did all Configuration which is specified in Plural Sight. I Copied Csv file from Local to hdfs. But next day when i searched for files , it is not present in hdfs and removed automatically. Is there any other conf setting so that my files are not loss?

core-site.xml

<configuration>
   <property>
      <name>fs.defaultFS</name>
      <value>hdfs://localhost:9000</value>
   </property>
</configuration>

hdfs-site.xml

<configuration>
   <property>
      <name>dfs.replication</name>
      <value>1</value>
   </property>
</configuration>

Thanks,

Body:
Add these properties to hdfs-site.xml

<property>
   <name>dfs.namenode.name.dir</name>
   <value>/home/username/hadoop-dfs/name</value>
</property>
<property>
   <name>dfs.datanode.data.dir</name>
   <value>/home/username/hadoop-dfs/data</value>
</property>

The metadata and data blocks are stored under /tmp by default as it is the value of hadoop.tmp.dir. The contents inside /tmp are deleted on reboot.

After adding these properties, format the namenode and start the services.


问:
Using Shiny actionButton() function in onRender() function of htmlWidgets
I have a Shiny application in which a user can select black points in a Plotly scatterplot using the Plotly "box select" icon. The points the user selects will be highlighted in red. I have a MWE of this application below:

```<code>library(plotly)
library(htmlwidgets)
library(shiny)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot")
))

server <- shinyServer(function(input, output) {
  p <- ggplot(mtcars, aes(x = wt, y = mpg))  + xlim(10,40) +ylim(0,10)
  ggPS <- ggplotly(p)

  output$myPlot <- renderPlotly(ggPS %>%
    onRender("
       function(el, x, data) {

       var xArr = [];
       var yArr = [];
       for (a=0; a<data.wt.length; a++){
       xArr.push(data.wt[a])
       yArr.push(data.mpg[a])
       }

       Traces=[]
       var tracePoints = {
         x: yArr,
         y: xArr,
         hoverinfo: 'none',
         mode: 'markers',
         marker: {
           color: 'black',
           size: 4
         }
       };
       Traces.push(tracePoints);
       Plotly.addTraces(el.id, Traces);

       el.on('plotly_selected', function(e) {
       var numSel = e.points.length
       var xSel = [];
       var ySel = [];

       for (a=0; a<numSel; a++){
         xSel.push(e.points[a].x)
         ySel.push(e.points[a].y)
       }

       var trace = {
         x: xSel,
         y: ySel,
         mode: 'markers',
         marker: {
           color: 'red',
           size: 4
         },
         hoverinfo: 'none'
       };

       Traces.push(trace);
       Plotly.addTraces(el.id, Traces);
       })

       }
       ", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg)))})

shinyApp(ui, server)
</code>```

I am now trying to update this Shiny application so that the selected black points do not automatically become red. Instead, after the user selects the black points, they can click on an action button with a label "Highlight selected points". If the user clicks that action button, then the selected points become red. Below is my attempt at getting this to work. Unfortunately, this application is not working, and actually loses its functionality of drawing the original black points and providing a box select icon in the first place .

```<code>library(plotly)
library(Shiny)
library(htmlwidgets)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  actionButton("highlight", "Highlight selected points")
))

server <- shinyServer(function(input, output) {

  highlight <- reactive(input$highlight)

  p <- ggplot(mtcars, aes(x = wt, y = mpg))  + xlim(10,40) +ylim(0,10)
  ggPS <- ggplotly(p)

  output$myPlot <- renderPlotly(ggPS %>%
onRender("
   function(el, x, data) {

   var xArr = [];
   var yArr = [];
   for (a=0; a<data.wt.length; a++){
   xArr.push(data.wt[a])
   yArr.push(data.mpg[a])
   }

   Traces=[]
   var tracePoints = {
   x: yArr,
   y: xArr,
   hoverinfo: 'none',
   mode: 'markers',
   marker: {
   color: 'black',
   size: 4
   }
   };
   Traces.push(tracePoints);
   Plotly.addTraces(el.id, Traces);

   el.on('plotly_selected', function(e) {

observeEvent(data.highlightS, {
   var numSel = e.points.length
   var xSel = [];
   var ySel = [];
   for (a=0; a<numSel; a++){
   xSel.push(e.points[a].x)
   ySel.push(e.points[a].y)
   }

   var trace = {
   x: xSel,
   y: ySel,
   mode: 'markers',
   marker: {
   color: 'red',
   size: 4
   },
   hoverinfo: 'none'
   };
   Traces.push(trace);
   Plotly.addTraces(el.id, Traces);
})
   })

   }
   ", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg, highlightS=highlight())))})

shinyApp(ui, server)
</code>```

EDIT:

I wanted to include a picture to demonstrate what I am aiming for. Basically, if the user selects the 15 dots shown below, they remain black:

However, if the user selects the "Highlight the selected points" Shiny button, then the 15 dots will become red as shown below:

答:
This would have been a preferred way to do the above, but the other solution I provided works better. This is because of a plotly bug in the R-binding that scatters the key values on selection, so it only works for one iteration. Once a selection has happened, the key values will no longer work. If you try it out you will see what I mean.

Also I couldn't get the sizes to work as above, that could also be another bug, or just a weird design issue.

However I am providing it anyway because it will probably work some day, and it is a better solution requiring far less code - or maybe someone will suggest a nice workaround for it.

```<code>library(plotly)
library(htmlwidgets)
library(shiny)
library(shinyBS)
library(ggplot2)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  bsButton("high","Highlight Selected Points",type="toggle")
))

server <- shinyServer(function(input, output) {

  m <- mtcars
  m$selected <- 0
  m$key <- 1:nrow(m)

  rv <- reactiveValues(m=m,high=FALSE)

  observeEvent(input$high,{req(input$high);rv$high <- !rv$high } )

  ggPS <- reactive(ggplotly(ggplot(m, aes(x = wt, y = mpg))))

  sel <- reactive(event_data("plotly_selected"))

  mvis <- reactive({
    rv$high
    sdatf <- sel()
    isolate({
      rv$m$selected <- 0L
      rv$m$selected[ sdatf$key ] <- 1L  # now select the ones in sdatf
    })
    print(sdatf)  # debugging
    return(rv$m)
  })

  output$myPlot <- renderPlotly({
    mvf <- mvis()
    mvf$selfac <- factor(mvf$selected,levels=c(0L, 1L))
    print(mvf)
    highcol <- ifelse(rv$high,"red","black")
    clrs <-  c("black",highcol)
    ggPS() %>%  add_markers(data=mvf,x=~wt,y=~mpg,key=~key,
                            color=~selfac,colors=clrs) %>%
                layout(dragmode = "select")
    })
})

shinyApp(ui, server)
</code>```

Body:
I have a Shiny application in which a user can select black points in a Plotly scatterplot using the Plotly "box select" icon. The points the user selects will be highlighted in red. I have a MWE of this application below:

library(plotly)
library(htmlwidgets)
library(shiny)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot")
))

server <- shinyServer(function(input, output) {
  p <- ggplot(mtcars, aes(x = wt, y = mpg))  + xlim(10,40) +ylim(0,10)
  ggPS <- ggplotly(p)

  output$myPlot <- renderPlotly(ggPS %>%
    onRender("
       function(el, x, data) {

       var xArr = [];
       var yArr = [];
       for (a=0; a<data.wt.length; a++){
       xArr.push(data.wt[a])
       yArr.push(data.mpg[a])
       }

       Traces=[]
       var tracePoints = {
         x: yArr,
         y: xArr,
         hoverinfo: 'none',
         mode: 'markers',
         marker: {
           color: 'black',
           size: 4
         }
       };
       Traces.push(tracePoints);
       Plotly.addTraces(el.id, Traces);

       el.on('plotly_selected', function(e) {
       var numSel = e.points.length
       var xSel = [];
       var ySel = [];

       for (a=0; a<numSel; a++){
         xSel.push(e.points[a].x)
         ySel.push(e.points[a].y)
       }

       var trace = {
         x: xSel,
         y: ySel,
         mode: 'markers',
         marker: {
           color: 'red',
           size: 4
         },
         hoverinfo: 'none'
       };

       Traces.push(trace);
       Plotly.addTraces(el.id, Traces);
       })

       }
       ", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg)))})

shinyApp(ui, server)

I am now trying to update this Shiny application so that the selected black points do not automatically become red. Instead, after the user selects the black points, they can click on an action button with a label "Highlight selected points". If the user clicks that action button, then the selected points become red. Below is my attempt at getting this to work. Unfortunately, this application is not working, and actually loses its functionality of drawing the original black points and providing a box select icon in the first place .

library(plotly)
library(Shiny)
library(htmlwidgets)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  actionButton("highlight", "Highlight selected points")
))

server <- shinyServer(function(input, output) {

  highlight <- reactive(input$highlight)

  p <- ggplot(mtcars, aes(x = wt, y = mpg))  + xlim(10,40) +ylim(0,10)
  ggPS <- ggplotly(p)

  output$myPlot <- renderPlotly(ggPS %>%
onRender("
   function(el, x, data) {

   var xArr = [];
   var yArr = [];
   for (a=0; a<data.wt.length; a++){
   xArr.push(data.wt[a])
   yArr.push(data.mpg[a])
   }

   Traces=[]
   var tracePoints = {
   x: yArr,
   y: xArr,
   hoverinfo: 'none',
   mode: 'markers',
   marker: {
   color: 'black',
   size: 4
   }
   };
   Traces.push(tracePoints);
   Plotly.addTraces(el.id, Traces);

   el.on('plotly_selected', function(e) {

observeEvent(data.highlightS, {
   var numSel = e.points.length
   var xSel = [];
   var ySel = [];
   for (a=0; a<numSel; a++){
   xSel.push(e.points[a].x)
   ySel.push(e.points[a].y)
   }

   var trace = {
   x: xSel,
   y: ySel,
   mode: 'markers',
   marker: {
   color: 'red',
   size: 4
   },
   hoverinfo: 'none'
   };
   Traces.push(trace);
   Plotly.addTraces(el.id, Traces);
})
   })

   }
   ", data = list(dat= mtcars, wt=mtcars$wt, mpg=mtcars$mpg, highlightS=highlight())))})

shinyApp(ui, server)

EDIT:

I wanted to include a picture to demonstrate what I am aiming for. Basically, if the user selects the 15 dots shown below, they remain black:

However, if the user selects the "Highlight the selected points" Shiny button, then the 15 dots will become red as shown below:

Body:
This would have been a preferred way to do the above, but the other solution I provided works better. This is because of a plotly bug in the R-binding that scatters the key values on selection, so it only works for one iteration. Once a selection has happened, the key values will no longer work. If you try it out you will see what I mean.

Also I couldn't get the sizes to work as above, that could also be another bug, or just a weird design issue.

However I am providing it anyway because it will probably work some day, and it is a better solution requiring far less code - or maybe someone will suggest a nice workaround for it.

library(plotly)
library(htmlwidgets)
library(shiny)
library(shinyBS)
library(ggplot2)

ui <- shinyUI(fluidPage(
  plotlyOutput("myPlot"),
  bsButton("high","Highlight Selected Points",type="toggle")
))

server <- shinyServer(function(input, output) {

  m <- mtcars
  m$selected <- 0
  m$key <- 1:nrow(m)

  rv <- reactiveValues(m=m,high=FALSE)

  observeEvent(input$high,{req(input$high);rv$high <- !rv$high } )

  ggPS <- reactive(ggplotly(ggplot(m, aes(x = wt, y = mpg))))

  sel <- reactive(event_data("plotly_selected"))

  mvis <- reactive({
    rv$high
    sdatf <- sel()
    isolate({
      rv$m$selected <- 0L
      rv$m$selected[ sdatf$key ] <- 1L  # now select the ones in sdatf
    })
    print(sdatf)  # debugging
    return(rv$m)
  })

  output$myPlot <- renderPlotly({
    mvf <- mvis()
    mvf$selfac <- factor(mvf$selected,levels=c(0L, 1L))
    print(mvf)
    highcol <- ifelse(rv$high,"red","black")
    clrs <-  c("black",highcol)
    ggPS() %>%  add_markers(data=mvf,x=~wt,y=~mpg,key=~key,
                            color=~selfac,colors=clrs) %>%
                layout(dragmode = "select")
    })
})

shinyApp(ui, server)


问:
text-align justify like in word
How can I cast paragraphs with text-align: justify; and line breaks in text over the full line width?

HTML default is to align lines with a line-break to left.
I like to cast it out over the full line width, like it is in word and other typographic software.

To avoid miss understanding, clarifying typographic soft and hard wraps:

soft wrap: line break

hard wrap: paragraph break / and and start of a new paragraph

Justify casting word

Justify casting web browser

This text has text-align: justify; in the web browser as you can see in this paragraph. Now soft wraps follow.

    This is a test

    to show how text

    is cast in word

    And the text is aligned to left in stead of casting it to 100% width.
```

答:
I think problem is that your text is not separated by line as it does in MS Word.

Note Keep in mind that you can't justify single line in CSS. To fix that use hack with :after element:

p {
  text-align: justify;
}

p:not(:last-child):after {
  content: "";
  display: inline-block;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>
  This is text
  </p>
  <p>
  to show how text
  </p>
  <p>
  is cast in word
  </p>
</div></code>```

Title: text-align justify like in word

Body:
I think problem is that your text is not separated by line as it does in MS Word.

Note Keep in mind that you can't justify single line in CSS. To fix that use hack with :after element:

p {
  text-align: justify;
}

p:not(:last-child):after {
  content: "";
  display: inline-block;
  width: 100%;
}

<div>
  <p>
  This is text
  </p>
  <p>
  to show how text
  </p>
  <p>
  is cast in word
  </p>
</div>


问:
Nav-tabs don't work on route profile/{name} Laravel
I made a profile page in Laravel with something like /profile/{name} and I use a UserController@showProfile:

```<code>public function showProfile($name)
{
    if(!Cache::has($name))
    {
        if(DB::table('users')->where('name', $name)->exists())
        {
            $user = DB::table('users')->where('name', $name)->get();
            Cache::put($name, $user, 10);
        }
        else
        {
            return view ('error404');
        }
    }

    return view ('user.profile', ['profile_stats' => Cache::get($name)]);
}
</code>```

But nav-tabs don't work if I put /profile/{name}, if I let it just /profile in routes everything works.

This is profile.blade.php with nav-tabs: https://pastebin.com/wzKM8wRd and this https://pastebin.com/XLBKX6Gr is the layout.

Route::get('profile/{name}', 'UserController@showProfile');

答:
can you show us content view script: user.profile.blade.php ?

and don't use cache until you make sure that everything works fine.

```<code>public function showProfile($name)
{
    $user = DB::table('users')->where('name', $name)->get();

    return view ('user.profile', ['profile_stats' => $user]);
}
</code>```

upd

any js errors in the browser console?

navigation works when url ends with /profile/ ? maybe you should try /profile/{name}/

So fix up js errors... and then come back :) looks like your problem with hash navigation isn't laravel issue.

Body:
I made a profile page in Laravel with something like /profile/{name} and I use a UserController@showProfile:

public function showProfile($name)
{
    if(!Cache::has($name))
    {
        if(DB::table('users')->where('name', $name)->exists())
        {
            $user = DB::table('users')->where('name', $name)->get();
            Cache::put($name, $user, 10);
        }
        else
        {
            return view ('error404');
        }
    }

    return view ('user.profile', ['profile_stats' => Cache::get($name)]);
}

But nav-tabs don't work if I put /profile/{name}, if I let it just /profile in routes everything works.

This is profile.blade.php with nav-tabs: https://pastebin.com/wzKM8wRd and this https://pastebin.com/XLBKX6Gr is the layout.

Route::get('profile/{name}', 'UserController@showProfile');

Body:
can you show us content view script: user.profile.blade.php ?

and don't use cache until you make sure that everything works fine.

public function showProfile($name)
{
    $user = DB::table('users')->where('name', $name)->get();

    return view ('user.profile', ['profile_stats' => $user]);
}

upd

any js errors in the browser console?

navigation works when url ends with /profile/ ? maybe you should try /profile/{name}/

So fix up js errors... and then come back :) looks like your problem with hash navigation isn't laravel issue.


问:
passing loop of components to html in react
```<code>formRowData()
{
    if (!this.props.payments.result)
    {
        return;
    }
    const tableRows = this.props.payments.result.content.map((payment) => {
        payment = payment.payment;
        return <TransactionTableRow key={payment.paymentId} transactionRowData={payment}/>
    })

    return tableRows;
}
</code>```

This is my loop for multiple tr components which I am trying to display on the page as follows

```<code><TransactionsDashboard merchant={this.props.merchant} transactionsData={this.formRowData()} statsTableData={this.getStatsTableData()} />
</code>```

My transaction Row component:

```<code>import React from 'react'

const TransactionTableRow = ({key,transactionRowData}) => {
    return (
      <tr key={key}>
            <td height="70"><span className="txt-spcng">19 Jan 17<br /><small className="grey-txt">19 Jan 17</small></span></td>
            <td>{transactionRowData.paymentId}</td>
            <td>KTU7-ZAUOSPZ</td>
            <td><span className="txt-limit">firstname.lastnasdsd</span></td>
            <td className="amnt-dbt">₹ {transactionRowData.amount}</td>
            <td><span className="txt-limit">Payment Successdd sdsd d</span></td>
            <td align="center"><div className="tl-tip"><a href="javscript:void(0)" className="icon-dotted"></a></div></td>
        </tr>
    )
}

export default TransactionTableRow
</code>```

But i get an error Each child in an array or iterator should have a unique "key" prop.

答:
Issue is simple one, key is a reserved keyword, it will not get passed to child component, use some other name, use this:

```<code><TransactionTableRow unique_id={payment.paymentId}....

const TransactionTableRow = ({unique_id,transactionRowData}) => {
    return (
      <tr key={unique_id}>
       .....
</code>```

If you want to verify this just put a console.log('key', key), like this:

```<code>const TransactionTableRow = ({unique_id,transactionRowData}) => {
     console.log('key', key);
     return (
     ....
</code>```

It will print undefined.

Body:
formRowData()
{
    if (!this.props.payments.result)
    {
        return;
    }
    const tableRows = this.props.payments.result.content.map((payment) => {
        payment = payment.payment;
        return <TransactionTableRow key={payment.paymentId} transactionRowData={payment}/>
    })

    return tableRows;
}

This is my loop for multiple tr components which I am trying to display on the page as follows

<TransactionsDashboard merchant={this.props.merchant} transactionsData={this.formRowData()} statsTableData={this.getStatsTableData()} />

My transaction Row component:

import React from 'react'

const TransactionTableRow = ({key,transactionRowData}) => {
    return (

            19 Jan 17
19 Jan 17
            {transactionRowData.paymentId}
            KTU7-ZAUOSPZ
            firstname.lastnasdsd
            ₹ {transactionRowData.amount}
            Payment Successdd sdsd d

    )
}

export default TransactionTableRow

But i get an error Each child in an array or iterator should have a unique "key" prop.

Body:
Issue is simple one, key is a reserved keyword, it will not get passed to child component, use some other name, use this:

<TransactionTableRow unique_id={payment.paymentId}....

const TransactionTableRow = ({unique_id,transactionRowData}) => {
    return (
      <tr key={unique_id}>
       .....

If you want to verify this just put a console.log('key', key), like this:

const TransactionTableRow = ({unique_id,transactionRowData}) => {
     console.log('key', key);
     return (
     ....

It will print undefined.


问:
Mercurial Repository Nightly Pull from a subdirectory on a server
I am attempting to run a Windows batch script nightly to pull a fresh copy of data to my local hard drive from a Mercurial repository, overwriting any data I have locally. The server on which the repository is located has many repos, so is located in a sub-directory on the server. I have set up PuTTY to use an RSA key so when I log onto the server with PuTTY, I need only enter my username.

The batch script has a command:

```<code>hg pull ssh://myusername@mydomain.com/targetrepo/
</code>```

...but this only opens a prompt for me to enter my password. Normally, this would be fine but because the pull will be executed from a batch script, I need the RSA key authentication to work.

How do I allow a batch script in a subdirectory on the server that contains a Mercurial repository to execute without requiring entry of a password?

答:
You said it yourself -- you need the RSA key authentication to work. So you'll need to debug why that isn't working. The easiest way would be to see the sshd logs on the server side. It'll probably be one of

Your key isn't on the server

The ~/.ssh directory or its contents' permissions on the server are wrong

The SSH daemon on the server doesn't allow passwordless access

It's not actually asking for a password at all; it's asking for a passphrase for your key

ContentLicense: CC BY-SA 2.5

Body:
I am attempting to run a Windows batch script nightly to pull a fresh copy of data to my local hard drive from a Mercurial repository, overwriting any data I have locally. The server on which the repository is located has many repos, so is located in a sub-directory on the server. I have set up PuTTY to use an RSA key so when I log onto the server with PuTTY, I need only enter my username.

The batch script has a command:

hg pull ssh://myusername@mydomain.com/targetrepo/

...but this only opens a prompt for me to enter my password. Normally, this would be fine but because the pull will be executed from a batch script, I need the RSA key authentication to work.

How do I allow a batch script in a subdirectory on the server that contains a Mercurial repository to execute without requiring entry of a password?


问:
Post images on Google+ through url
I want to post images and videos on google+ through my titanium application. Here is my url which I am using:

```<code>var webView = Ti.UI.createWebView({
  url: 'https://plus.google.com/share?client_id=1234567889.apps.googleusercontent.com&continue='+Ti.App.id+'%3A%2F%2Fshare%2F&text='+textToShare+'&url='+urlToShare+'&bundle_id='+Ti.App.id+'&gpsdk=1.0.0'
});

win.add(webView);
</code>```

Can anyone tell, How to pass image as parameter in above url?

Any help would be appreciated.

Thanks

答:
You can add/upload image on Google+:
  Reference Link: https://developers.google.com/+/domains/posts/creating

```<code>    // Helper function courtesy of https://github.com/guzzle/guzzle/blob/3a0787217e6c0246b457e637ddd33332efea1d2a/src/Guzzle/Http/Message/PostFile.php#L90

    function getCurlValue($filename, $contentType, $postname) {
          // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax
          // See: https://wiki.php.net/rfc/curl-file-upload

    if (function_exists('curl_file_create')) {
        return curl_file_create($filename, $contentType, $postname);
    }

    // Use the old style if using an older version of PHP
    $value = "@{$filename};filename=" . $postname;
    if ($contentType) {
        $value .= ';type=' . $contentType;
    }

    return $value; }   $filename = '/path/to/file.jpg'; $cfile = getCurlValue($filename,'image/jpeg','cattle-01.jpg');   //NOTE: The top level key in the array is important, as some apis will insist that it is 'file'. $data = array('file' => $cfile);   $ch = curl_init(); $options = array(CURLOPT_URL => 'http://your/server/api/upload',
             CURLOPT_RETURNTRANSFER => true,
             CURLINFO_HEADER_OUT => true, //Request header
             CURLOPT_HEADER => true, //Return header
             CURLOPT_SSL_VERIFYPEER => false, //Don't veryify server certificate
             CURLOPT_POST => true,
             CURLOPT_POSTFIELDS => $data
            );
</code>```

Title: Post images on Google+ through url

Body:
I want to post images and videos on google+ through my titanium application. Here is my url which I am using:

var webView = Ti.UI.createWebView({
  url: 'https://plus.google.com/share?client_id=1234567889.apps.googleusercontent.com&continue='+Ti.App.id+'%3A%2F%2Fshare%2F&text='+textToShare+'&url='+urlToShare+'&bundle_id='+Ti.App.id+'&gpsdk=1.0.0'
});

win.add(webView);

Can anyone tell, How to pass image as parameter in above url?

Any help would be appreciated.

Thanks

Body:
You can add/upload image on Google+:
  Reference Link: https://developers.google.com/+/domains/posts/creating

    // Helper function courtesy of https://github.com/guzzle/guzzle/blob/3a0787217e6c0246b457e637ddd33332efea1d2a/src/Guzzle/Http/Message/PostFile.php#L90

    function getCurlValue($filename, $contentType, $postname) {
          // PHP 5.5 introduced a CurlFile object that deprecates the old @filename syntax
          // See: https://wiki.php.net/rfc/curl-file-upload

    if (function_exists('curl_file_create')) {
        return curl_file_create($filename, $contentType, $postname);
    }

    // Use the old style if using an older version of PHP
    $value = "@{$filename};filename=" . $postname;
    if ($contentType) {
        $value .= ';type=' . $contentType;
    }

    return $value; }   $filename = '/path/to/file.jpg'; $cfile = getCurlValue($filename,'image/jpeg','cattle-01.jpg');   //NOTE: The top level key in the array is important, as some apis will insist that it is 'file'. $data = array('file' => $cfile);   $ch = curl_init(); $options = array(CURLOPT_URL => 'http://your/server/api/upload',
             CURLOPT_RETURNTRANSFER => true,
             CURLINFO_HEADER_OUT => true, //Request header
             CURLOPT_HEADER => true, //Return header
             CURLOPT_SSL_VERIFYPEER => false, //Don't veryify server certificate
             CURLOPT_POST => true,
             CURLOPT_POSTFIELDS => $data
            );


问:
Could not find `Options` in `getopts`
I am trying to use the Options struct in the getopts crate, which exists according to the Rust book.

The code I am running is this.

```<code>let mut opts = getopts::Options::new();
</code>```

While building the project the compiler gives the error

 let mut opts = getopts::Options::new();
                ^^^^^^^^^^^^^^^^^^^^^ Could not find `Options in `getopts`
```

How do I resolve this? I am using the nightly version of Rust.

答: You need to use the crates.io version instead.  You can see here that the built-in version of getopts has been flagged as a compiler internal with rustc_private.  The version on crates.io is basically the same crate.  The compiler-internal version is just kept segregated for various reasons.

Title: Could not find `Options` in `getopts`

Body:
I am trying to use the Options struct in the getopts crate, which exists according to the Rust book.

The code I am running is this.

let mut opts = getopts::Options::new();

While building the project the compiler gives the error

 let mut opts = getopts::Options::new();
                ^^^^^^^^^^^^^^^^^^^^^ Could not find `Options in `getopts`

How do I resolve this? I am using the nightly version of Rust.


问:
How to enter quotes in a Java string?
I want to initialize a String in Java, but that string needs to include quotes; for example: "ROM". I tried doing:

```<code>String value = " "ROM" ";
</code>```

but that doesn't work. How can I include "s within a string?

答:
suppose ROM is string variable which equals "strval"
you can simply do

```<code>String value= " \" "+ROM+" \" ";
</code>```

it will be stored as

```<code>value= " "strval" ";
</code>```

Title: How to enter quotes in a Java string?

Body:
I want to initialize a String in Java, but that string needs to include quotes; for example: "ROM". I tried doing:

String value = " "ROM" ";

but that doesn't work. How can I include "s within a string?

Body:
suppose ROM is string variable which equals "strval"
you can simply do

String value= " \" "+ROM+" \" ";

it will be stored as

value= " "strval" ";


问:
Understanding COUNT behavior in queries vs. EXPLAIN vs. functions
I am curious to understand (and perhaps improve) an issue I am having with PostgreSQL 9.6. Names simplified but everything else is taken from a psql session.

I start with a materialized view, mv.

First, I create two simple functions:

```<code>CREATE FUNCTION count_mv() RETURNS BIGINT AS $$
SELECT COUNT(*) FROM mv;
$$ LANGUAGE SQL STABLE PARALLEL SAFE;
</code>```

and

```<code>CREATE FUNCTION mv_pks() RETURNS TABLE (table_pk INTEGER) AS $$
SELECT table_pk FROM mv;
$$ LANGUAGE SQL STABLE PARALLEL SAFE;
</code>```

Let's time some queries.

db=>\timing on

I can count results from the materialized view very quickly.

```<code>db=> SELECT COUNT(*) FROM mv;
  count
---------
 2567883
(1 row)

Time: 79.803 ms
</code>```

Let's see how it's doing this.

```<code>db=> EXPLAIN ANALYZE SELECT COUNT(*) FROM mv;
                                                                  QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=41331.24..41331.25 rows=1 width=8) (actual time=765.681..765.681 rows=1 loops=1)
   ->  Gather  (cost=41330.62..41331.23 rows=6 width=8) (actual time=765.557..765.670 rows=7 loops=1)
         Workers Planned: 6
         Workers Launched: 6
         ->  Partial Aggregate  (cost=40330.62..40330.63 rows=1 width=8) (actual time=760.175..760.175 rows=1 loops=7)
               ->  Parallel Seq Scan on mv  (cost=0.00..39261.09 rows=427809 width=0) (actual time=0.014..397.952 rows=366840 loops=7)
 Planning time: 0.326 ms
 Execution time: 769.934 ms
(8 rows)
</code>```

Good. So it's taking advantage of multiple workers. But why is the query so much slower when using EXPLAIN ANALYZE?

Now I use the count_mv() function, which has the same underlying SQL and is declared STABLE.

```<code>db=> select count_mv();
  count_mv
------------
    2567883
(1 row)

Time: 406.058 ms
</code>```

Whoa! Why is this slower than the same SQL on the materialized view? And a lot slower! Is it not taking advantage of parallel workers, and if not, why not?

BEGIN EDIT

As proposed in an answer below, I loaded the auto_explain module and checked the log output for EXPLAIN on the function call.

```<code>    Query Text:
    SELECT COUNT(*) FROM mv;

     Finalize Aggregate  (cost=41331.60..41331.61 rows=1 width=8) (actual time=1345.446..1345.446 rows=1 loops=1)
       ->  Gather  (cost=41330.97..41331.58 rows=6 width=8) (actual time=1345.438..1345.440 rows=1 loops=1)
            Workers Planned: 6
            Workers Launched: 0
             ->  Partial Aggregate  (cost=40330.97..40330.99 rows=1 width=8) (actual time=1345.435..1345.435 rows=1 loops=1)
                  ->  Parallel Seq Scan on mv  (cost=0.00..39261.38 rows=427838 width=0) (actual time=0.020..791.022 rows=2567883 loops=1)
</code>```

The new question is why 6 workers are planned but none are launched. The server is otherwise idle, the configuration is the same, and the query is the same.

END EDIT

All right. So what if I do this:

```<code>db=> SELECT COUNT(*) FROM mv_pks();
  count
---------
 2567883
(1 row)

Time: 72.687 ms
</code>```

The same performance as counting rows on the materialized view directly without using EXPLAIN ANALYZE, but you'll have to trust me here: the performance of this function depends on the state of the materialized view when the function is created. The fast timing here is the result of creating the function when the table is empty. If I recreate the function when the table is full, the function requires over 1000 ms to run!

To summarize my questions:

Why is the SQL query inside a STABLE SQL function taking no parameters so much slower than a query outside that function.

Why is the SQL query so much slower when using EXPLAIN ANALYZE?

Why do I get all different results when counting rows from a function that can either be equivalently fast to counting rows on the materialized view or slower than any other method, depending on when the function was created?

Thanks in advance!

答:
For 1), you can find out yourself using auto_explain, which can show plans for queries inside functions. Does it use a parallel plan?

For 2) that is the overhead of measuring, which depends on the platform, but can be high.

For 3) compare the SQL plans in both cases. Queries in SQL functions are not cached, so I don't have an explanation why it should behave like this. Did you repeat the test multiple time to rule out that you see the effect of reading from disk versus reading from cache?

Body:
I am curious to understand (and perhaps improve) an issue I am having with PostgreSQL 9.6. Names simplified but everything else is taken from a psql session.

I start with a materialized view, mv.

First, I create two simple functions:

CREATE FUNCTION count_mv() RETURNS BIGINT AS $$
SELECT COUNT(*) FROM mv;
$$ LANGUAGE SQL STABLE PARALLEL SAFE;

and

CREATE FUNCTION mv_pks() RETURNS TABLE (table_pk INTEGER) AS $$
SELECT table_pk FROM mv;
$$ LANGUAGE SQL STABLE PARALLEL SAFE;

Let's time some queries.

db=>\timing on

I can count results from the materialized view very quickly.

db=> SELECT COUNT(*) FROM mv;
  count
---------
 2567883
(1 row)

Time: 79.803 ms

Let's see how it's doing this.

db=> EXPLAIN ANALYZE SELECT COUNT(*) FROM mv;
                                                                  QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=41331.24..41331.25 rows=1 width=8) (actual time=765.681..765.681 rows=1 loops=1)
   ->  Gather  (cost=41330.62..41331.23 rows=6 width=8) (actual time=765.557..765.670 rows=7 loops=1)
         Workers Planned: 6
         Workers Launched: 6
         ->  Partial Aggregate  (cost=40330.62..40330.63 rows=1 width=8) (actual time=760.175..760.175 rows=1 loops=7)
               ->  Parallel Seq Scan on mv  (cost=0.00..39261.09 rows=427809 width=0) (actual time=0.014..397.952 rows=366840 loops=7)
 Planning time: 0.326 ms
 Execution time: 769.934 ms
(8 rows)

Good. So it's taking advantage of multiple workers. But why is the query so much slower when using EXPLAIN ANALYZE?

Now I use the count_mv() function, which has the same underlying SQL and is declared STABLE.

db=> select count_mv();
  count_mv
------------
    2567883
(1 row)

Time: 406.058 ms

Whoa! Why is this slower than the same SQL on the materialized view? And a lot slower! Is it not taking advantage of parallel workers, and if not, why not?

BEGIN EDIT

As proposed in an answer below, I loaded the auto_explain module and checked the log output for EXPLAIN on the function call.

    Query Text:
    SELECT COUNT(*) FROM mv;

     Finalize Aggregate  (cost=41331.60..41331.61 rows=1 width=8) (actual time=1345.446..1345.446 rows=1 loops=1)
       ->  Gather  (cost=41330.97..41331.58 rows=6 width=8) (actual time=1345.438..1345.440 rows=1 loops=1)
            Workers Planned: 6
            Workers Launched: 0
             ->  Partial Aggregate  (cost=40330.97..40330.99 rows=1 width=8) (actual time=1345.435..1345.435 rows=1 loops=1)
                  ->  Parallel Seq Scan on mv  (cost=0.00..39261.38 rows=427838 width=0) (actual time=0.020..791.022 rows=2567883 loops=1)

The new question is why 6 workers are planned but none are launched. The server is otherwise idle, the configuration is the same, and the query is the same.

END EDIT

All right. So what if I do this:

db=> SELECT COUNT(*) FROM mv_pks();
  count
---------
 2567883
(1 row)

Time: 72.687 ms

The same performance as counting rows on the materialized view directly without using EXPLAIN ANALYZE, but you'll have to trust me here: the performance of this function depends on the state of the materialized view when the function is created. The fast timing here is the result of creating the function when the table is empty. If I recreate the function when the table is full, the function requires over 1000 ms to run!

To summarize my questions:

Why is the SQL query inside a STABLE SQL function taking no parameters so much slower than a query outside that function.

Why is the SQL query so much slower when using EXPLAIN ANALYZE?

Why do I get all different results when counting rows from a function that can either be equivalently fast to counting rows on the materialized view or slower than any other method, depending on when the function was created?

Thanks in advance!


问:
Trying to find a string in an array, but linear/sequential search doesn't work
Below I have code which puts separate lines from a text file into an array. It asks the user to type in a string, and subsequently looks for the string in the array and see if the strings equals an element of the array. If so, it says it does and says which element it equals, and if not it says it could not find it. However, this code always says it can't find the line even though I can clearly see that the input equals an element from the array. What is incorrect here? I have no clue where the problem lies so below is the code for creating the array and the linear search algorithm:</p>

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

File file = new File("text.txt"); //puts separate lines of file into an array
Scanner text = new Scanner(file);
String[] Array = new String[10];

for (int i = 0; i < 10 && text.hasNextLine(); i++)
{
    String line = text.nextLine();
    if (line.isEmpty())
    {
        continue;

    }
    Array[i] = line;
    System.out.printf("Element %d of the array is: %s%n", i, Array[i]);

}

Scanner input = new Scanner(System.in); //performs sequential search based on user input
System.out.println("Type the line you want to find: ");
String line = input.next();
int pos = 0;
boolean found = false;
while (pos < Array.length && !found)
{
    if(Array[pos]== line)
    {
        found = true;
    }
    else
    {
        pos++;
    }

}
 if (found)
 {
     System.out.println("Found at position: " + pos);

 }
 else
 {
     System.out.println("Could not find " + line);

 }

}
</code>```

答:
The problem might lay in the following code snippet:

```<code>Array[pos]== line
</code>```

The comparison here is done using the references and not the actual content of the String. This behavior works fine for string literals and String values which are explicitly interned (and stored in the Java string pool). You might also check out following link : https://dzone.com/articles/string-interning-what-why-and

I would suggest to use String.equals() for comparing the values. Hope this helps.

Body:
Below I have code which puts separate lines from a text file into an array. It asks the user to type in a string, and subsequently looks for the string in the array and see if the strings equals an element of the array. If so, it says it does and says which element it equals, and if not it says it could not find it. However, this code always says it can't find the line even though I can clearly see that the input equals an element from the array. What is incorrect here? I have no clue where the problem lies so below is the code for creating the array and the linear search algorithm:

public static void main(String[] args) throws FileNotFoundException
{

File file = new File("text.txt"); //puts separate lines of file into an array
Scanner text = new Scanner(file);
String[] Array = new String[10];

for (int i = 0; i < 10 && text.hasNextLine(); i++)
{
    String line = text.nextLine();
    if (line.isEmpty())
    {
        continue;

    }
    Array[i] = line;
    System.out.printf("Element %d of the array is: %s%n", i, Array[i]);

}

Scanner input = new Scanner(System.in); //performs sequential search based on user input
System.out.println("Type the line you want to find: ");
String line = input.next();
int pos = 0;
boolean found = false;
while (pos < Array.length && !found)
{
    if(Array[pos]== line)
    {
        found = true;
    }
    else
    {
        pos++;
    }

}
 if (found)
 {
     System.out.println("Found at position: " + pos);

 }
 else
 {
     System.out.println("Could not find " + line);

 }

}

Body:
The problem might lay in the following code snippet:

Array[pos]== line

The comparison here is done using the references and not the actual content of the String. This behavior works fine for string literals and String values which are explicitly interned (and stored in the Java string pool). You might also check out following link : https://dzone.com/articles/string-interning-what-why-and

I would suggest to use String.equals() for comparing the values. Hope this helps.


问:
How to Find the 4 furthest points of this rectangle
I have plotted a list of corners I've obtained using Harris Corner detection.

Now I need to find the 4 furthers points that will represent the corners of the rectangle

I know I can get the two top and bottom diagonal corners using

```<code>  max(C);
  min(C);
</code>```

Where C is an n row matrix with a column for x and y like

```<code>  x y
  0 1
  2 3
  4 5
  6 6
</code>```

But how do I get the other two corners?

I thought I could rotate the matrix and use min and max again, but of course that just returns me a huge n column matrix (and I want a 2 column matrix)

I feel like the answer is obvious, but I'm blanking :(

答:
Another alternative solution, if you dont want to use corner detection:

```<code>im=zeros(100);

im(40:70,30:80)=1;
im=imrotate(im,rand*100);

[x,y]=find(im);
x=x+2*randn(size(x));
y=y+2*randn(size(y));
X=[x(:),y(:)];

d=ceil(pdist2(X,X)*10)/10;

[a,b]=find(d==max(d(:)));

xm=x(a);
ym=y(a);

figure,plot(x,y,'ks')
hold on, plot(xm,ym,'ro','MarkerSize',12,'MArkerFaceColor','r')
axis image
</code>```

Body:
I have plotted a list of corners I've obtained using Harris Corner detection.

Now I need to find the 4 furthers points that will represent the corners of the rectangle

I know I can get the two top and bottom diagonal corners using

  max(C);
  min(C);

Where C is an n row matrix with a column for x and y like

  x y
  0 1
  2 3
  4 5
  6 6

But how do I get the other two corners?

I thought I could rotate the matrix and use min and max again, but of course that just returns me a huge n column matrix (and I want a 2 column matrix)

I feel like the answer is obvious, but I'm blanking :(

Body:
Another alternative solution, if you dont want to use corner detection:

im=zeros(100);

im(40:70,30:80)=1;
im=imrotate(im,rand*100);

[x,y]=find(im);
x=x+2*randn(size(x));
y=y+2*randn(size(y));
X=[x(:),y(:)];

d=ceil(pdist2(X,X)*10)/10;

[a,b]=find(d==max(d(:)));

xm=x(a);
ym=y(a);

figure,plot(x,y,'ks')
hold on, plot(xm,ym,'ro','MarkerSize',12,'MArkerFaceColor','r')
axis image


问:
Select tag not including options after the first time
Relatively new to php, I want to fetch a column named make for which i am using a loop and mysqli_fetch_row to fetch each row from the column and then i am inserting the data into a select tag. The problem I am facing is that it inserts the data into the options tag the first time, and after that it just echos it out of the list.
Here is the code for it,

```<code>$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
//$row= mysqli_fetch_all($queryResult);
$i=0;
echo"<label for='make'>Please select a make:</label>
<select>
    <option name='make' value='All'>All</option>";
    while($row= mysqli_fetch_row($queryResult)){
    echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
    }
</code>```

What to d0 here?

答:
Try this:

```<code><select>
while($row= mysqli_fetch_row($queryResult)){
   echo '<option value="'.$row[$i].'">'.$row[$i].'</option>';
}
</select>
</code>```

Put only option tag inside the loop.

Body:
Relatively new to php, I want to fetch a column named make for which i am using a loop and mysqli_fetch_row to fetch each row from the column and then i am inserting the data into a select tag. The problem I am facing is that it inserts the data into the options tag the first time, and after that it just echos it out of the list.
Here is the code for it,

$SQLstring = "select make from inventory";
$queryResult = @mysqli_query($DBConnect, $SQLstring)
Or die ("
Unable to query the $TableName table.
"."
Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "
";
//$row= mysqli_fetch_all($queryResult);
$i=0;
echo"Please select a make:
<select>
    <option name='make' value='All'>All</option>";
    while($row= mysqli_fetch_row($queryResult)){
    echo"<option value='$row[$i]'>$row[$i]</option>
</select>";
    }

What to d0 here?

Body:
Try this:

<select>
while($row= mysqli_fetch_row($queryResult)){
   echo '<option value="'.$row[$i].'">'.$row[$i].'</option>';
}
</select>

Put only option tag inside the loop.


问:
Cannot get data from related models in Rails
I have 2 models in different namespace.

```<code>class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end
</code>```

The Membership model is in different folder with AuthorizationRole model (I don't know what is called)

When run Admin::Membership.find(:all), the data from AuthorizationRole model is not included. I've create membership_id field on authorization_roles table, but I still can't get both models related. Is something wrong in this code? Sorry if I'm missing something basic here.

答:
Check to see if you are setting the table name prefix. The Rails model generator adds a file like this for namespaced models:

```<code># /app/models/admin.rb
module Admin
  def self.table_name_prefix
    'admin_'
  end
end
</code>```

Note: this is Rails version 3.0.1 -- not sure about earlier versions.

Body:
I have 2 models in different namespace.

class Admin::Membership < ActiveRecord::Base
  has_many :authorization_roles
end

class AuthorizationRole < ActiveRecord::Base
  belongs_to :membership
end

The Membership model is in different folder with AuthorizationRole model (I don't know what is called)

When run Admin::Membership.find(:all), the data from AuthorizationRole model is not included. I've create membership_id field on authorization_roles table, but I still can't get both models related. Is something wrong in this code? Sorry if I'm missing something basic here.

Body:
Check to see if you are setting the table name prefix. The Rails model generator adds a file like this for namespaced models:

# /app/models/admin.rb
module Admin
  def self.table_name_prefix
    'admin_'
  end
end

Note: this is Rails version 3.0.1 -- not sure about earlier versions.


问:
No-op dyno on Heroku
I have the exact same situation described here: Multiple SSL Certificates in One Heroku Application, which is I want to securely access the same application using different domains.

The technique described in the first answer is promising, however I just discovered Heroku started a free service called Automated Certificate Management, which automatically takes care of creating and renewing certificates, which is great. But this is only available for applications with paid dynos.

I don't mind paying 7 $/month for a Hobby dyno, however as my app will only be used for SSL traffic, I don't know how to start a dyno without anything to run. In other words, I want to create a vacant dyno which won't do anything, just to activate the Automated Certificate Management. Is this possible and are there any thing that can go wrong in my plan?

答:
This method won't work with Heroku's ACM, as the domains for which the certificate is generated are the ones the app points to.

So you won't be able to have the certificate on one app, and the domain on another.

However, ACM does handle multiple domains (up to 100), and will generate a single certificate valid for all of them. So while you will have only one certificate, it will work for all of your app domains.

Title: No-op dyno on Heroku


问:
What is a datasource in java? Can someone please explain me in simple language?
What is a DataSource in java?
Can someone please explain me in simple language?</p>

答: According to documentation, the DataSouce interface is something like DriverManager. In most applications, it is connection to the database.


问:
Why does strptime from Time::Piece not parse my format?
My collegue (who has left the company) has written a bunch of scripts, including batch and Perl scripts, and I'm getting rid of the regional settings dependencies.

In the last Perl script, he's written the following piece of code:

```<code>my $format = "%d.%m.%Y %H:%M";
my $today_converted = Time::Piece->strptime($today, $format) - ONE_HOUR - ONE_HOUR - ONE_HOUR - ONE_HOUR - ONE_HOUR;
</code>```

(the idea is to get five hours before midnight of that particular date)

The value of $today seems to be "03/04/2017" (which stands for the third of April (European dateformat)), which seems not to be understood by Time::Piece implementation:

```<code>Error parsing time at C:/Perl64/lib/Time/Piece.pm line 481.
</code>```

Which format can I use which is understood by Time::Piece Perl implementation?

答:
I think it's worth clarifying that strptime() will parse most date and time formats - that's the point of the method. But you need to define the format of the date string that you are parsing. That's what the second parameter to strptime() (in this case, your $format variable) is for.

The letters used in the format are taken from a standard list of definitions which used by every implementation of strptime() (and its inverse, strftime()). See man strptime on your system for a complete list of the available options.

In your case, the format is %d.%m.%Y %H:%M - which means that it will parse timestamps which have the day, month and year separated by dots, followed by a space and the hours and minutes separated by a colon. If you want to parse timestamps in a different format, then you will need to change the definition of $format.

Body:
My collegue (who has left the company) has written a bunch of scripts, including batch and Perl scripts, and I'm getting rid of the regional settings dependencies.

In the last Perl script, he's written the following piece of code:

my $format = "%d.%m.%Y %H:%M";
my $today_converted = Time::Piece->strptime($today, $format) - ONE_HOUR - ONE_HOUR - ONE_HOUR - ONE_HOUR - ONE_HOUR;

(the idea is to get five hours before midnight of that particular date)

The value of $today seems to be "03/04/2017" (which stands for the third of April (European dateformat)), which seems not to be understood by Time::Piece implementation:

Error parsing time at C:/Perl64/lib/Time/Piece.pm line 481.

Which format can I use which is understood by Time::Piece Perl implementation?


问:
Get data from two tables in codeigniter
i am trying to execute query to get data from table 1 and apply where clause on table 2
this is a sample query to execute on Code-igniter

```<code> SELECT * FROM table1,table2 WHERE `hide` = 0 AND `reject` = 0 AND `disable` = 0 AND `private` = 0 AND `table2`.`wepay_account_id` != '' ORDER BY `table1_id` DESC LIMIT 40
</code>```

this query execute in database but not execute in code-igniter

i am trying this code in model

```<code> $this->db->limit($limit, $start);
        $this->db->where('hide', 0);
        $this->db->where('reject', 0);
        $this->db->where('disable', 0);
        $this->db->where('private', 0);
        $this->db->where('table2.wepay_account_id !=',"");
        $this->db->from('table1','table2');
        $this->db->order_by('table1', 'DESC');
        $query = $this->db->get();
        $a=$this->db->last_query();
        print_r($a);
        exit;
</code>```

but i am facing this error

```<code>Error Number: 1054

Unknown column 'table2.wepay_account_id' in 'where clause'

SELECT * FROM (`table1`) WHERE `hide` = 0 AND `reject` = 0 AND `disable` = 0 AND `private` = 0 AND `table2`.`wepay_account_id` != '' ORDER BY `table1_id` DESC LIMIT 40
</code>```

答:
In this code segment Select use for table1. There is no table2

Its not posisble add where condition as table2.wepay_account_id

Use this join(),

```<code> $this->db->from('table1');
 $this->db->join('table2', 'table1.id = table2.id')
</code>```

Title: Get data from two tables in codeigniter

Body:
i am trying to execute query to get data from table 1 and apply where clause on table 2
this is a sample query to execute on Code-igniter

 SELECT * FROM table1,table2 WHERE `hide` = 0 AND `reject` = 0 AND `disable` = 0 AND `private` = 0 AND `table2`.`wepay_account_id` != '' ORDER BY `table1_id` DESC LIMIT 40

this query execute in database but not execute in code-igniter

i am trying this code in model

 $this->db->limit($limit, $start);
        $this->db->where('hide', 0);
        $this->db->where('reject', 0);
        $this->db->where('disable', 0);
        $this->db->where('private', 0);
        $this->db->where('table2.wepay_account_id !=',"");
        $this->db->from('table1','table2');
        $this->db->order_by('table1', 'DESC');
        $query = $this->db->get();
        $a=$this->db->last_query();
        print_r($a);
        exit;

but i am facing this error

Error Number: 1054

Unknown column 'table2.wepay_account_id' in 'where clause'

SELECT * FROM (`table1`) WHERE `hide` = 0 AND `reject` = 0 AND `disable` = 0 AND `private` = 0 AND `table2`.`wepay_account_id` != '' ORDER BY `table1_id` DESC LIMIT 40

Body:
In this code segment Select use for table1. There is no table2

Its not posisble add where condition as table2.wepay_account_id

Use this join(),

 $this->db->from('table1');
 $this->db->join('table2', 'table1.id = table2.id')


问:
Make UITextField accept small alphabet letter only in Swift?
I Want to Make textField that accept only small alphabet letter not capital alphabet letter or no any special symbol or not any digit.</p>

答:
You can use regular expression for it, in example below regular expression that allows only small symbols</p>

```<code>func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.isEmpty {
        return true
    }
    let regex = "[a-z]{1,}"
    return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: string)
}
</code>```

Body:
You can use regular expression for it, in example below regular expression that allows only small symbols

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if string.isEmpty {
        return true
    }
    let regex = "[a-z]{1,}"
    return NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: string)
}


问:
find common and different elements between two List in java
I want to get the below

 1. common elements between two list.

 2. Elements in ListB which is not available in ListA

 3. Elements in ListA which is not available in ListB

```<code>List<String> fruitsListA = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Grapes");
List<String> fruitsListACopy = fruitsListA;

List<String> fruitsListB = new ArrayList<String>();
fruits.add("Strawberry");
fruits.add("Cranberry");
fruits.add("Orange");
fruits.add("Apple");
List<String> fruitsListBCopy = fruitsListB;

1. common elements between two list

    fruitsListACopy.retainAll(fruitsListB);

2. Elements in ListB which is not available in ListA

    fruitsListB.removeAll(fruitsListA);

3. Elements in ListA which is not available in ListB

    fruitsListA.removeAll(fruitsListBCopy);
</code>```

case 1 : Im able to get the common items in both the list. So If I print fruitsListACopy it gives ['Apple']

case 2 : I could see fruitsListA got modified automatically I mean instead of having all the items ['Apple','Banana','Grapes'] it has only common item
['Apple'] .

case 3: I could see fruitsListB got modified automatically I mean instead of having all the items ['Strawberry','Cranberry','Orange','Apple'] it has only
['Strawberry','Cranberry','Orange'] with the removal of coomon item which is Apple.

I could even see fruitsListA got modified automatically I mean instead of having all the items ['Apple','Banana','Grapes'] it has only common item
['Apple'] .

The changes done in the copied list gets reflects in original list when I use removeAll and retainAll methods.

Is there any other best way to meet this need?

答:
I could even see fruitsListA got modified automatically

When you make a copy like yhis

```<code>List<String> fruitsListACopy = fruitsListA;
</code>```

You do not copy the list. Instead, you make a reference to the existing list. Hence, all modifications to the "copy" reflect on the original.

To make a copy, call constructor again:

```<code>List<String> fruitsListACopy = new ArrayList<String>(fruitsListA);
</code>```

Body:
I want to get the below

 1. common elements between two list.

 2. Elements in ListB which is not available in ListA

 3. Elements in ListA which is not available in ListB

List<String> fruitsListA = new ArrayList<String>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Grapes");
List<String> fruitsListACopy = fruitsListA;

List<String> fruitsListB = new ArrayList<String>();
fruits.add("Strawberry");
fruits.add("Cranberry");
fruits.add("Orange");
fruits.add("Apple");
List<String> fruitsListBCopy = fruitsListB;

1. common elements between two list

    fruitsListACopy.retainAll(fruitsListB);

2. Elements in ListB which is not available in ListA

    fruitsListB.removeAll(fruitsListA);

3. Elements in ListA which is not available in ListB

    fruitsListA.removeAll(fruitsListBCopy);

case 1 : Im able to get the common items in both the list. So If I print fruitsListACopy it gives ['Apple']

case 2 : I could see fruitsListA got modified automatically I mean instead of having all the items ['Apple','Banana','Grapes'] it has only common item
['Apple'] .

case 3: I could see fruitsListB got modified automatically I mean instead of having all the items ['Strawberry','Cranberry','Orange','Apple'] it has only
['Strawberry','Cranberry','Orange'] with the removal of coomon item which is Apple.

I could even see fruitsListA got modified automatically I mean instead of having all the items ['Apple','Banana','Grapes'] it has only common item
['Apple'] .

The changes done in the copied list gets reflects in original list when I use removeAll and retainAll methods.

Is there any other best way to meet this need?

Body:
I could even see fruitsListA got modified automatically

When you make a copy like yhis

List<String> fruitsListACopy = fruitsListA;

You do not copy the list. Instead, you make a reference to the existing list. Hence, all modifications to the "copy" reflect on the original.

To make a copy, call constructor again:

List<String> fruitsListACopy = new ArrayList<String>(fruitsListA);


问:
Does Binding work ONLY with DependencyProperty?
MSDN says,

Each binding typically has these four components: a binding target
  object, a target property, a binding
  source, and a Path to the value in the
  binding source to use. For example, if
  you want to bind the content of a
  TextBox to the Name property of an
  Employee object, your target object is
  the TextBox, the target property is
  the Text property, the value to use is
  Name, and the source object is the
  Employee object.

The target property must be a dependency property.

The above excerpt explains why the following code works,

```<code><TextBox Text="{Binding EmployeeName}">
</code>```

It works because Text is a dependency property. Upto this point, everything is fine!

My question is,

IF target property must be a dependency property for Binding to work, then how does the folllowing Setter work? Please note that Value in Setter is NOT a dependency property!

```<code><Style TargetType="{x:Type TextBox}">
      <Setter Property="Text" Value="{Binding EmployeeName}"/>
</Style>
</code>```

I've an explanation for it. But I'm not sure if that is correct. Let me first explain it, and then, you guys correct me if I'm wrong. :-)

I think, since the type of Value is Object, that means, it can hold instances of ANY type. It can hold an instance of even Binding type. It, however, cannot take part in the process of evaluating (or resolving) the Binding expression, since it's not a dependency property. So Style object simply transfers this Binding object (which Value holds) from Setter to the TextBox as such, without evaluating/resolving the Binding value. As such the above Setter becomes equivalent to this:

```<code> Text="{Binding EmployeeName}"
</code>```

And since now, Text is a dependency property, it can resolve the Binding value. So it first appears that target of binding is Value, but in reality, Text is the target of the binding.

It's like Setter is a postman, Value itself is postman's Bag, Binding instance (i.e what Value holds) is a Letter. Postman (i.e Setter) delivers the Letter(i.e Binding instance) to the Target (i.e Text property), without opening it, i.e without knowing what Message (i.e EmployeeName) the Letter carries.

Please correct me if I'm wrong.

答:
The XAML is setting Setter.Value to an object of type Binding.  The Style thus created then sets the Text dependency property on the target object to that Binding, so that the binding will update Text whenever the source property changes.

If Setter.Value were a dependency property, then the setter would end up being an intermediary in property-change notification:  the source property changes, the binding notifies the setter, the setter notifies the target.  Since it's just a CLR property, the setter's not actually involved in change notification:  the source property changes and the binding notifies the target.

Body:
MSDN says,

Each binding typically has these four components: a binding target
  object, a target property, a binding
  source, and a Path to the value in the
  binding source to use. For example, if
  you want to bind the content of a
  TextBox to the Name property of an
  Employee object, your target object is
  the TextBox, the target property is
  the Text property, the value to use is
  Name, and the source object is the
  Employee object.

The target property must be a dependency property.

The above excerpt explains why the following code works,

<TextBox Text="{Binding EmployeeName}">

It works because Text is a dependency property. Upto this point, everything is fine!

My question is,

IF target property must be a dependency property for Binding to work, then how does the folllowing Setter work? Please note that Value in Setter is NOT a dependency property!

I've an explanation for it. But I'm not sure if that is correct. Let me first explain it, and then, you guys correct me if I'm wrong. :-)

I think, since the type of Value is Object, that means, it can hold instances of ANY type. It can hold an instance of even Binding type. It, however, cannot take part in the process of evaluating (or resolving) the Binding expression, since it's not a dependency property. So Style object simply transfers this Binding object (which Value holds) from Setter to the TextBox as such, without evaluating/resolving the Binding value. As such the above Setter becomes equivalent to this:

 Text="{Binding EmployeeName}"

And since now, Text is a dependency property, it can resolve the Binding value. So it first appears that target of binding is Value, but in reality, Text is the target of the binding.

It's like Setter is a postman, Value itself is postman's Bag, Binding instance (i.e what Value holds) is a Letter. Postman (i.e Setter) delivers the Letter(i.e Binding instance) to the Target (i.e Text property), without opening it, i.e without knowing what Message (i.e EmployeeName) the Letter carries.

Please correct me if I'm wrong.


问:
ListView - stretch single item across the whole ListView height
If I have a single item in an ArrayAdapter on a ListView, I would like to stretch that one item all over the ListView height (so I have the text of the one item in the center of the screen).

Like this:

This is really easily done with RecyclerView (the image above) but in my case I can't afford rebuilding ListView screens on RecyclerView now. I tried setting the height of the layout item to the screen height "match_parent" or in code, overriding the 80dp value. It didn't have any impact on my situation, the result looked like this:

this is how I am creating the ArrayAdapter:

```<code>string[] noResultsItem = { Resources.GetString(Resource.String.no_network) };
playlistListView.Adapter = new ArrayAdapter<string>(this, Resource.Layout.no_result_row, Resource.Id.textTop, noResultsItem);
</code>```

This is the layout for the ArrayAdapter item:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:id="@+id/noResultsRow">
    <TextView
        android:id="@+id/textTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="18dip"
        android:textColor="#ffffff"
        android:text=""
        android:gravity="center_horizontal" />
</RelativeLayout>
</code>```

I can imagine a solution with hiding and showing the ListView and replacing it with a TextView that would be centered but I don't like that solution that much.

答:
Use Relative Layout height as

```<code> android:layout_height="80dp"
</code>```

replaces it on

android:layout_height="match_parent"
and gravity should be center or you can take LinearLayout

Body:
If I have a single item in an ArrayAdapter on a ListView, I would like to stretch that one item all over the ListView height (so I have the text of the one item in the center of the screen).

Like this:

This is really easily done with RecyclerView (the image above) but in my case I can't afford rebuilding ListView screens on RecyclerView now. I tried setting the height of the layout item to the screen height "match_parent" or in code, overriding the 80dp value. It didn't have any impact on my situation, the result looked like this:

this is how I am creating the ArrayAdapter:

string[] noResultsItem = { Resources.GetString(Resource.String.no_network) };
playlistListView.Adapter = new ArrayAdapter<string>(this, Resource.Layout.no_result_row, Resource.Id.textTop, noResultsItem);

This is the layout for the ArrayAdapter item:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    android:id="@+id/noResultsRow">
    <TextView
        android:id="@+id/textTop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:textSize="18dip"
        android:textColor="#ffffff"
        android:text=""
        android:gravity="center_horizontal" />
</RelativeLayout>

I can imagine a solution with hiding and showing the ListView and replacing it with a TextView that would be centered but I don't like that solution that much.

Body:
Use Relative Layout height as

 android:layout_height="80dp"

replaces it on

android:layout_height="match_parent"
and gravity should be center or you can take LinearLayout


问:
Show / Hide - Content on Button Click
Hello fellow programmer,

im getting used to Angular 2, therefore Typescript, so have mercy with me.

I have 5 Buttons which should enable or Disable Content on Click, like a Sidemenu.

HTML - Code

```<code>  <li class="navigation-items">
    <button class="dropdown-header" (click)="onSelect(2)">Link 2</button>
    <div *ngIf="DropdownVar == 2" class="dropdown-content">
      <a href="#">Link 1</a>
      <a href="#">Link 2</a>
      <a href="#">Link 3</a>
    </div>
  </li>
</code>```

Typescript - Code

```<code>DropdownVar = 0;

onSelect(x){
 this.DropdownVar = x;
 console.log(x);
}
</code>```

It seems that my var gets the propper value but my *ngif does not work.
Is there a better way to handle my Problem?

Additional i would like to have a little animation for the Content which i want to show, but i guess css is the way to go.

答:
you can use [hidden] instead ngIf

```<code><li class="navigation-items">
<button class="dropdown-header" (click)="onSelect()">Link 2</button>
<div  class="dropdown-content" [hidden]="IsHidden">
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
</div>
</code>```

In Component

```<code>IsHidden= true;

onSelect(){
 this.IsHidden= !this.IsHidden;
}
</code>```

Title: Show / Hide - Content on Button Click

Body:
Hello fellow programmer,

im getting used to Angular 2, therefore Typescript, so have mercy with me.

I have 5 Buttons which should enable or Disable Content on Click, like a Sidemenu.

HTML - Code

    <button class="dropdown-header" (click)="onSelect(2)">Link 2</button>

      Link 1
      Link 2
      Link 3

Typescript - Code

DropdownVar = 0;

onSelect(x){
 this.DropdownVar = x;
 console.log(x);
}

It seems that my var gets the propper value but my *ngif does not work.
Is there a better way to handle my Problem?

Additional i would like to have a little animation for the Content which i want to show, but i guess css is the way to go.

Body:
you can use [hidden] instead ngIf

<li class="navigation-items">
<button class="dropdown-header" (click)="onSelect()">Link 2</button>
<div  class="dropdown-content" [hidden]="IsHidden">
  <a href="#">Link 1</a>
  <a href="#">Link 2</a>
  <a href="#">Link 3</a>
</div>

In Component

IsHidden= true;

onSelect(){
 this.IsHidden= !this.IsHidden;
}


答:
Put the select outside the while loop</p>

```<code>    $SQLstring = "select make from inventory";
    $queryResult = @mysqli_query($DBConnect, $SQLstring)
    Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
    //$row= mysqli_fetch_all($queryResult);
    $i=0;
    echo"<label for='make'>Please select a make:</label>
    <select>
        <option name='make' value='All'>All</option>";
        while($row= mysqli_fetch_row($queryResult)){
        echo"<option value='$row[$i]'>$row[$i]</option>";
        }
    echo "</select>";
</code>```

Title: Select tag not including options after the first time

Body:
Put the select outside the while loop

    $SQLstring = "select make from inventory";
    $queryResult = @mysqli_query($DBConnect, $SQLstring)
    Or die ("<p>Unable to query the $TableName table.</p>"."<p>Error code ". mysqli_errno($DBConnect). ": ".mysqli_error($DBConnect)). "</p>";
    //$row= mysqli_fetch_all($queryResult);
    $i=0;
    echo"<label for='make'>Please select a make:</label>
    <select>
        <option name='make' value='All'>All</option>";
        while($row= mysqli_fetch_row($queryResult)){
        echo"<option value='$row[$i]'>$row[$i]</option>";
        }
    echo "</select>";


问:
Query showing records that do NOT match in between tables
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

```<code>Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly
</code>```

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

```<code>SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID
</code>```

And my results:

```<code>AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32
</code>```

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

```<code>AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly
</code>```

答:
Something like this perhaps?</p>

```<code>SELECT     qrd.InstallationDate,
           qrd.QuarterlyReportType
FROM       #QuarterlyReportsDue qrd
WHERE      qrd.QuarterlyReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
           AND NOT EXISTS (
                 SELECT   1
                 FROM     Reports r
                 WHERE    r.AssessmentID = qrd.AssessmentID
                          AND r.ReportType = qrd.QuarterlyReportType
              )
ORDER BY   qrd.AssessmentID
</code>```

Body:
I have two tables. One is a table of the reports that have been submitted to us. Another is a temp table with the records of reports that should eventually be submitted to us. I would like to show only the records in the temp table that do not match the ones in the reports table (so the reports that still must be submitted are displayed).

Example data is:

Reports table:

CREATE TABLE [dbo].[Reports]
(
    [ReportID] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [date] NULL,
    [AssessmentID] [int] NOT NULL,
    [ReportType] [varchar](50) NULL
);

AssessmentID    ReportType  ReportID
1   1st Quarterly   27
2   1st Quarterly   30
2   2nd Quarterly   31
2   3rd Quarterly   32

QuarterlyReportsDue table:

CREATE TABLE #QuarterlyReportsDue
(
AssessmentID INT,
InstallationDate DATE,
QuarterlyReportType VARCHAR(50)
);

AssessmentID    InstallationDate    QuarterlyReportType
1   2009-08-14  1st Quarterly
1   2009-08-14  2nd Quarterly
1   2009-08-14  3rd Quarterly
1   2009-08-14  4th Quarterly
2   2008-05-16  4th Quarterly
2   2008-05-16  3rd Quarterly
2   2008-05-16  2nd Quarterly
2   2008-05-16  1st Quarterly

I have tried LEFT OUTER JOINS but am running into issues. Please see my below SQL:

SELECT #QuarterlyReportsDue.InstallationDate, #QuarterlyReportsDue.QuarterlyReportType, Reports.ReportType
FROM #QuarterlyReportsDue
LEFT OUTER JOIN Reports ON #QuarterlyReportsDue.AssessmentID = Reports.AssessmentID
WHERE Reports.ReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
AND Reports.ReportType <> #QuarterlyReportsDue.QuarterlyReportType
ORDER BY #QuarterlyReportsDue.AssessmentID

And my results:

AssessmentID    QuarterlyReportType ReportType  ReportID
1   2nd Quarterly   1st Quarterly   27
1   3rd Quarterly   1st Quarterly   27
1   4th Quarterly   1st Quarterly   27
2   4th Quarterly   1st Quarterly   30
2   4th Quarterly   2nd Quarterly   31
2   4th Quarterly   3rd Quarterly   32
2   1st Quarterly   2nd Quarterly   31
2   1st Quarterly   3rd Quarterly   32
2   3rd Quarterly   1st Quarterly   30
2   3rd Quarterly   2nd Quarterly   31
2   2nd Quarterly   1st Quarterly   30
2   2nd Quarterly   3rd Quarterly   32

For assessment 1 it works great, assessment 2 has many duplicates. How can I get around this to only show the ideal results?

AssessmentID    QuarterlyReportType ReportType
1   2nd Quarterly   1st Quarterly
1   3rd Quarterly   1st Quarterly
1   4th Quarterly   1st Quarterly
2       4th Quarterly

Body:
Something like this perhaps?

SELECT     qrd.InstallationDate,
           qrd.QuarterlyReportType
FROM       #QuarterlyReportsDue qrd
WHERE      qrd.QuarterlyReportType IN ('1st Quarterly', '2nd Quarterly', '3rd Quarterly', '4th Quarterly')
           AND NOT EXISTS (
                 SELECT   1
                 FROM     Reports r
                 WHERE    r.AssessmentID = qrd.AssessmentID
                          AND r.ReportType = qrd.QuarterlyReportType
              )
ORDER BY   qrd.AssessmentID


问:
Android back button app is not closing
i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice</p>

```<code>  private Boolean exit = false;

        @Override
        public void onBackPressed() {
            if (exit) {
                this.finish(); // finish activity
            } else {
                Toast.makeText(this, "Press Back again to Exit.",
                        Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);

            }

        }
</code>```

答:
This will work for you
    Define this it globally </p>

```<code>private boolean doubleBackToExitProceed = false;
@Override
  public void onBackPressed() {
    if (doubleBackToExitProceed) {
      finish();
      return;
    }
    doubleBackToExitProceed = true;
    Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

      @Override
      public void run() {
        doubleBackToExitProceed = false;
      }
    }, 2000);// time in milliseconds.
  }
</code>```

Title: Android back button app is not closing

Body:
i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice

  private Boolean exit = false;

        @Override
        public void onBackPressed() {
            if (exit) {
                this.finish(); // finish activity
            } else {
                Toast.makeText(this, "Press Back again to Exit.",
                        Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);

            }

        }

Body:
This will work for you
    Define this it globally

private boolean doubleBackToExitProceed = false;
@Override
  public void onBackPressed() {
    if (doubleBackToExitProceed) {
      finish();
      return;
    }
    doubleBackToExitProceed = true;
    Toast.makeText(this, "Press Back again to Exit.", Toast.LENGTH_SHORT).show();

    new Handler().postDelayed(new Runnable() {

      @Override
      public void run() {
        doubleBackToExitProceed = false;
      }
    }, 2000);// time in milliseconds.
  }


问:
Javascript replace every 6th colon in array
I have some problems with replacing every 6th colon in my array. Have tried something with Regex, but that doesn't seem to work. I have red other questions were people are using nth and then set this variabele to the index you want to replace, but can't figure out why that isn't working. I used the join function to replace the ',' in my array with ':'.

```<code>arrayProducts[i] = arrayProducts[i].join(':');
</code>```

When i use console.log(arrayProducts); this is my result:

F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3

This is what I want:

```<code>F200:0:0.0000:1:100:0:1,KPO2:0:0.0000:1:200:0:2,HGB1:0:0.0000:1:300:0:3
</code>```

Thanks for reading!

Edit: F200, KP02 and HGB1, could also be numbers / digits like: 210, 89, 102 so the :[A-Z] method from regex doesn't work.

答:
Another solution (based on the number of iteration)

using map method:

```<code>str.split(':').map((v, i) => (i % 7 === 0 ? ',' : ':') + v ).join('').slice(1)
</code>```

using reduce method:

```<code>str.split(':').reduce((acc,v, i) =>  {
    return acc +  (i % 7 === 0 ? ',' : ':' ) + v ;
}, '').slice(1)
</code>```

Note: arrow expression does not work on old browsers

Body:
I have some problems with replacing every 6th colon in my array. Have tried something with Regex, but that doesn't seem to work. I have red other questions were people are using nth and then set this variabele to the index you want to replace, but can't figure out why that isn't working. I used the join function to replace the ',' in my array with ':'.

arrayProducts[i] = arrayProducts[i].join(':');

When i use console.log(arrayProducts); this is my result:

F200:0:0.0000:1:100:0:1:KPO2:0:0.0000:1:200:0:2:HGB1:0:0.0000:1:300:0:3

This is what I want:

F200:0:0.0000:1:100:0:1,KPO2:0:0.0000:1:200:0:2,HGB1:0:0.0000:1:300:0:3

Thanks for reading!

Edit: F200, KP02 and HGB1, could also be numbers / digits like: 210, 89, 102 so the :[A-Z] method from regex doesn't work.

Body:
Another solution (based on the number of iteration)

using map method:

str.split(':').map((v, i) => (i % 7 === 0 ? ',' : ':') + v ).join('').slice(1)

using reduce method:

str.split(':').reduce((acc,v, i) =>  {
    return acc +  (i % 7 === 0 ? ',' : ':' ) + v ;
}, '').slice(1)

Note: arrow expression does not work on old browsers