问:
Shiny DT: format date column in excel through Buttons extensions
I have a datatable with date column that shows UTC timezone.
Using last development version of DT one can choose to convert date column to locale string and everything shows nicely in shiny webapp. However, if user will download the table through Buttons extension, the date column will be exported in the UTC time zone (and unreadable format)

```<code>library(DT)
library(shiny)

df <- data.frame(a = 1:100, b = 1:100,
             d=seq(as.POSIXct("2017-08-23 10:00:00"), as.POSIXct("2017-11-30 10:00:00"), by = "days"))

ui <- fluidPage(
  dataTableOutput("table")
)

server <- function(input, output){

  output$table <- DT::renderDataTable({
    datatable(df,
              extensions = c("Buttons"),
              options = list(dom = 'Bfrtip',
                             buttons = list("csv",list(extend='excel',filename="DF"))
              )) %>% formatDate(3, "toLocaleString", params = list('fr-FR'))
  })

}

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

So if local OS time zone is +5, it will show "23/08/2017 à 10:00:00" in a shiny webapp, but "2017-08-23T05:00:00Z" in excel file. Is there any possible way to format exports?

答:
To achieve what you want, I propose two methods, both require you to transform the data set to the user's locale.

Using an input

In the same view as the table, provide a shiny input, which allows user selection of the locale. Use this value to transform the UTC entries.

```<code>library(DT)
library(shiny)
library(dplyr)

ui <- fluidPage(
  selectInput(
    "timezone", "Timezone",
    choices = c("Europe/Paris", "America/Los_Angeles", "Australia/Sydney")
  ),
  DT::dataTableOutput("table")
)

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

  df <- data.frame(
    a = 1:100,
    b = 1:100,
    d = seq(
      as.POSIXct("2017-08-23 10:00:00", tz = "UTC"),
      as.POSIXct("2017-11-30 10:00:00", tz = "UTC"),
      by = "days")
  )

  df_locale <- reactive({

    df %>%
      mutate(
        local = format(d, "%d %B %Y %I:%M:%S %p %Z", tz = input$timezone)
      )

  })

  output$table <- DT::renderDataTable({

    DT::datatable(
      df_locale(),
      extensions = 'Buttons',
      options = list(
        dom = 'Bfrtip',
        buttons = list("copy", "csv", list(extend = "excel", filename = "DF"))
      )
    ) %>%
    formatDate(3, "toLocaleString", params = list("fr-FR"))

  })

}

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

Automatically based on the client machine

This is more involved and relies on the answer to this question.

```<code>library(DT)
library(shiny)
library(dplyr)
library(lubridate)

ui <- fluidPage(

  HTML('<input type="text" id="client_time" name="client_time" style="display: none;"> '),
  HTML('<input type="text" id="client_time_zone_offset" name="client_time_zone_offset" style="display: none;"> '),
  tags$script('
  $(function() {
    var time_now = new Date()
    $("input#client_time").val(time_now.getTime())
    $("input#client_time_zone_offset").val(time_now.getTimezoneOffset())
  });
  '),
  DT::dataTableOutput("table")
)

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

  df <- data.frame(
    a = 1:100,
    b = 1:100,
    d = seq(
      as.POSIXct("2017-08-23 10:00:00", tz = "UTC"),
      as.POSIXct("2017-11-30 10:00:00", tz = "UTC"),
      by = "days")
  )

  client_time <- reactive({as.numeric(input$client_time) / 1000})
  time_zone_offset <- reactive({-as.numeric(input$client_time_zone_offset) * 60})

  df_locale <- reactive({

    df %>%
      mutate(
        local = format(d + seconds(time_zone_offset()), "%d %B %Y %I:%M:%S %p")
      )

  })

  output$table <- DT::renderDataTable({

    DT::datatable(
      df_locale(),
      extensions = 'Buttons',
      options = list(
        dom = 'Bfrtip',
        buttons = list("copy", "csv", list(extend = "excel", filename = "DF"))
      )
    ) %>%
      formatDate(3, "toLocaleString", params = list("fr-FR"))

  })

}

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

N.B. While the advantage of the automated option is that no user interaction is required, I have not tried to determine the Olson Name location of the client and therefore not resolving the time zone beyond a time offset from UTC. There are likely options available to improve using alternate javascript.

Update using download button

If you want to download something different to what is available in the DT::datatable via the Buttons extension, you have the option to use the standard downloadHandler and associated button. In the code below I demonstrate how you can combine your original code to display the table and offer a csv download of the data transformed to suit the client time zone offset shown in the previous two approaches.

```<code>library(DT)
library(shiny)
library(dplyr)
library(readr)
library(lubridate)

ui <- fluidPage(

  HTML('<input type="text" id="client_time" name="client_time" style="display: none;"> '),
  HTML('<input type="text" id="client_time_zone_offset" name="client_time_zone_offset" style="display: none;"> '),
  tags$script('
              $(function() {
              var time_now = new Date()
              $("input#client_time").val(time_now.getTime())
              $("input#client_time_zone_offset").val(time_now.getTimezoneOffset())
              });
              '),
  downloadButton("download_data", "Get Data"),
  DT::dataTableOutput("table")
  )

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

  df <- data.frame(
    a = 1:100,
    b = 1:100,
    d = seq(
      as.POSIXct("2017-08-23 10:00:00", tz = "UTC"),
      as.POSIXct("2017-11-30 10:00:00", tz = "UTC"),
      by = "days")
  )

  client_time <- reactive({as.numeric(input$client_time) / 1000})
  time_zone_offset <- reactive({-as.numeric(input$client_time_zone_offset) * 60})

  df_locale <- reactive({

    df %>%
      mutate(
        d = format(d + seconds(time_zone_offset()), "%d %B %Y %I:%M:%S %p")
      )

  })

  output$download_data <- downloadHandler(
    filename <- function() {
      paste0(format(Sys.Date(), "%Y%m%d"), "-data.csv")
    },
    content <- function(file) {
      write_csv(df_locale(), file)
    },
    contentType = "text/csv"
  )

  output$table <- DT::renderDataTable({

    DT::datatable(df) %>%
      formatDate(3, "toLocaleString")

  })

}

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

The Buttons extention for DT does not currently have the ability to be customised with R. Changing the behaviour may be possible with javascript, you can read here about the API.

Body:
I have a datatable with date column that shows UTC timezone.
Using last development version of DT one can choose to convert date column to locale string and everything shows nicely in shiny webapp. However, if user will download the table through Buttons extension, the date column will be exported in the UTC time zone (and unreadable format)

library(DT)
library(shiny)

df <- data.frame(a = 1:100, b = 1:100,
             d=seq(as.POSIXct("2017-08-23 10:00:00"), as.POSIXct("2017-11-30 10:00:00"), by = "days"))

ui <- fluidPage(
  dataTableOutput("table")
)

server <- function(input, output){

  output$table <- DT::renderDataTable({
    datatable(df,
              extensions = c("Buttons"),
              options = list(dom = 'Bfrtip',
                             buttons = list("csv",list(extend='excel',filename="DF"))
              )) %>% formatDate(3, "toLocaleString", params = list('fr-FR'))
  })

}

shinyApp(ui, server)

So if local OS time zone is +5, it will show "23/08/2017 à 10:00:00" in a shiny webapp, but "2017-08-23T05:00:00Z" in excel file. Is there any possible way to format exports?

Body:
To achieve what you want, I propose two methods, both require you to transform the data set to the user's locale.

Using an input

In the same view as the table, provide a shiny input, which allows user selection of the locale. Use this value to transform the UTC entries.

library(DT)
library(shiny)
library(dplyr)

ui <- fluidPage(
  selectInput(
    "timezone", "Timezone",
    choices = c("Europe/Paris", "America/Los_Angeles", "Australia/Sydney")
  ),
  DT::dataTableOutput("table")
)

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

  df <- data.frame(
    a = 1:100,
    b = 1:100,
    d = seq(
      as.POSIXct("2017-08-23 10:00:00", tz = "UTC"),
      as.POSIXct("2017-11-30 10:00:00", tz = "UTC"),
      by = "days")
  )

  df_locale <- reactive({

    df %>%
      mutate(
        local = format(d, "%d %B %Y %I:%M:%S %p %Z", tz = input$timezone)
      )

  })

  output$table <- DT::renderDataTable({

    DT::datatable(
      df_locale(),
      extensions = 'Buttons',
      options = list(
        dom = 'Bfrtip',
        buttons = list("copy", "csv", list(extend = "excel", filename = "DF"))
      )
    ) %>%
    formatDate(3, "toLocaleString", params = list("fr-FR"))

  })

}

shinyApp(ui, server)

Automatically based on the client machine

This is more involved and relies on the answer to this question.

library(DT)
library(shiny)
library(dplyr)
library(lubridate)

ui <- fluidPage(

  HTML('<input type="text" id="client_time" name="client_time" style="display: none;"> '),
  HTML('<input type="text" id="client_time_zone_offset" name="client_time_zone_offset" style="display: none;"> '),
  tags$script('
  $(function() {
    var time_now = new Date()
    $("input#client_time").val(time_now.getTime())
    $("input#client_time_zone_offset").val(time_now.getTimezoneOffset())
  });
  '),
  DT::dataTableOutput("table")
)

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

  df <- data.frame(
    a = 1:100,
    b = 1:100,
    d = seq(
      as.POSIXct("2017-08-23 10:00:00", tz = "UTC"),
      as.POSIXct("2017-11-30 10:00:00", tz = "UTC"),
      by = "days")
  )

  client_time <- reactive({as.numeric(input$client_time) / 1000})
  time_zone_offset <- reactive({-as.numeric(input$client_time_zone_offset) * 60})

  df_locale <- reactive({

    df %>%
      mutate(
        local = format(d + seconds(time_zone_offset()), "%d %B %Y %I:%M:%S %p")
      )

  })

  output$table <- DT::renderDataTable({

    DT::datatable(
      df_locale(),
      extensions = 'Buttons',
      options = list(
        dom = 'Bfrtip',
        buttons = list("copy", "csv", list(extend = "excel", filename = "DF"))
      )
    ) %>%
      formatDate(3, "toLocaleString", params = list("fr-FR"))

  })

}

shinyApp(ui, server)

N.B. While the advantage of the automated option is that no user interaction is required, I have not tried to determine the Olson Name location of the client and therefore not resolving the time zone beyond a time offset from UTC. There are likely options available to improve using alternate javascript.

Update using download button

If you want to download something different to what is available in the DT::datatable via the Buttons extension, you have the option to use the standard downloadHandler and associated button. In the code below I demonstrate how you can combine your original code to display the table and offer a csv download of the data transformed to suit the client time zone offset shown in the previous two approaches.

library(DT)
library(shiny)
library(dplyr)
library(readr)
library(lubridate)

ui <- fluidPage(

  HTML('<input type="text" id="client_time" name="client_time" style="display: none;"> '),
  HTML('<input type="text" id="client_time_zone_offset" name="client_time_zone_offset" style="display: none;"> '),
  tags$script('
              $(function() {
              var time_now = new Date()
              $("input#client_time").val(time_now.getTime())
              $("input#client_time_zone_offset").val(time_now.getTimezoneOffset())
              });
              '),
  downloadButton("download_data", "Get Data"),
  DT::dataTableOutput("table")
  )

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

  df <- data.frame(
    a = 1:100,
    b = 1:100,
    d = seq(
      as.POSIXct("2017-08-23 10:00:00", tz = "UTC"),
      as.POSIXct("2017-11-30 10:00:00", tz = "UTC"),
      by = "days")
  )

  client_time <- reactive({as.numeric(input$client_time) / 1000})
  time_zone_offset <- reactive({-as.numeric(input$client_time_zone_offset) * 60})

  df_locale <- reactive({

    df %>%
      mutate(
        d = format(d + seconds(time_zone_offset()), "%d %B %Y %I:%M:%S %p")
      )

  })

  output$download_data <- downloadHandler(
    filename <- function() {
      paste0(format(Sys.Date(), "%Y%m%d"), "-data.csv")
    },
    content <- function(file) {
      write_csv(df_locale(), file)
    },
    contentType = "text/csv"
  )

  output$table <- DT::renderDataTable({

    DT::datatable(df) %>%
      formatDate(3, "toLocaleString")

  })

}

shinyApp(ui, server)

The Buttons extention for DT does not currently have the ability to be customised with R. Changing the behaviour may be possible with javascript, you can read here about the API.


来源: stackexchange

问:
Are immutable objects good practice?
Should I make my classes immutable where possible?

I once read the book "Effective Java" by Joshua Bloch and he recommended to make all business objects immutable for various reasons. (for example thread safety)
Does this apply for C# too?

Do you try to make your objects immutable, so you have less problems when working with them?
Or is it not worth the inconvenience you have to create them?

答:
Off the top of my head, I can't think of a reason for immutable objects making thread safe code somehow "better".

If I want an object to be thread safe, I will either put a lock around it or I will make a copy of it and update the reference once I'm done working on it. I typically wouldn't want a new object for every little change.

For me, immutable strings create more headaches for threading than it helps.

I actually went out of my way to make an "in-place" "ToUpper" using unsafe code isntead of the built in String.ToUpper(). It runs about 4 times faster and consumes 1/2 the peak memory.

ContentLicense: CC BY-SA 2.5

Title: Are immutable objects good practice?


问:
Updating time without refreshing the page with Javascript
I'm building an app that displays the current time without have to refresh.
I'm calling the time below, but when I display it I have to refresh the page to update the time. How do I continuously update the time?</p>

```<code>function GetTime(){
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();

        if (hour>=12){                  //Adding endings
                suffix = "P.M.";}
        else{
                suffix = "A.M.";}

minute = addZero(minute);       //Call addZero function
hour = removeMilitary(hour);    //Call removeMilitary Function

var fullTime = hour + ":" + minute + " " + suffix;  //Combine hour minute and the suffix

        function addZero(number){
                        if (number<10){
                            number = "0" + number;
                        }
                        return number;
        }

        function removeMilitary(hour){ //This function can be removed if desired by user.

            if (hour > 0 && hour <= 12) {
                hour = "" + hour;
            } else if (hour > 12) {
                hour = "" + (hour - 12);
            } else if (hour == 0) {
                hour= "12";
            }
            return hour;
        }
return fullTime;

}
</code>```

答: setInterval (GetTime, 1000) will call your function every second (1000 milliseconds) to get the time. You don't show how you're putting the time on the page, so you'll need to incorporate that as well. </p>

ContentLicense: CC BY-SA 3.0

Body:
I'm building an app that displays the current time without have to refresh.
I'm calling the time below, but when I display it I have to refresh the page to update the time. How do I continuously update the time?

function GetTime(){
var today = new Date();
var hour = today.getHours();
var minute = today.getMinutes();

        if (hour>=12){                  //Adding endings
                suffix = "P.M.";}
        else{
                suffix = "A.M.";}

minute = addZero(minute);       //Call addZero function
hour = removeMilitary(hour);    //Call removeMilitary Function

var fullTime = hour + ":" + minute + " " + suffix;  //Combine hour minute and the suffix

        function addZero(number){
                        if (number<10){
                            number = "0" + number;
                        }
                        return number;
        }

        function removeMilitary(hour){ //This function can be removed if desired by user.

            if (hour > 0 && hour <= 12) {
                hour = "" + hour;
            } else if (hour > 12) {
                hour = "" + (hour - 12);
            } else if (hour == 0) {
                hour= "12";
            }
            return hour;
        }
return fullTime;

}


答:
Javascript has a setInterval method.

You can get the time every second, by running your program every 1000 milliseconds:

```<code>setInterval(GetTime, 1000);
//if you incorporate updating the html
//within the getTime function
</code>```

or

```<code>setInterval(function(){
    document.getElementById("ID_of_the_time_element").innerHTML= getTime();
    //do something else
}, 1000}
</code>```

Why setInterval at 1000 ms isn't very accurate

The problem  with that is unless you start the set interval exactly on the second, your program will not change the second exactly on the second. I would recommend you get it more accurate by adjusting the interval to every 100 ms, for example. Then it would update every 100ms, which means that the most your clock will be behind is a tenth of a second.

A better solution

Setting an interval every 100ms is ok, but if you want more accuracy, setting it to 10ms isn't necessarily the best option, because repeating a task every 10ms is a pretty large burden on the computer. You could also use find the number of ms until the next second, and then use the setTimeout method to wait until the next second arrives and start the set timeout then. You would still have some computational delay(the amount of time between when it gets the number of milliseconds until the next second and it starts the setTimeout), but that's probably a lot less than 100 ms.

Title: Updating time without refreshing the page with Javascript

Body:
Javascript has a setInterval method.

You can get the time every second, by running your program every 1000 milliseconds:

setInterval(GetTime, 1000);
//if you incorporate updating the html
//within the getTime function

or

setInterval(function(){
    document.getElementById("ID_of_the_time_element").innerHTML= getTime();
    //do something else
}, 1000}

Why setInterval at 1000 ms isn't very accurate

The problem  with that is unless you start the set interval exactly on the second, your program will not change the second exactly on the second. I would recommend you get it more accurate by adjusting the interval to every 100 ms, for example. Then it would update every 100ms, which means that the most your clock will be behind is a tenth of a second.

A better solution

Setting an interval every 100ms is ok, but if you want more accuracy, setting it to 10ms isn't necessarily the best option, because repeating a task every 10ms is a pretty large burden on the computer. You could also use find the number of ms until the next second, and then use the setTimeout method to wait until the next second arrives and start the set timeout then. You would still have some computational delay(the amount of time between when it gets the number of milliseconds until the next second and it starts the setTimeout), but that's probably a lot less than 100 ms.


问:
JHipster import-jdl not generating swagger
Is it possible to generate the swagger api.yaml from JDL?

I've created and app with swagger addon and then imported entities from jdl but the swagger api.yaml is empty

答:
That specific api.yml is intended for JHipster's API First Development feature.

JHipster comes configured with Springfox, which automatically generates the Swagger docs based on the project's code. You can access the app's Swagger config after starting the app at http://localhost:8080/v2/api-docs.  It is in JSON format by default, if you need YAML you can upload it to the Swagger Editor

You can also view the docs in a built-in SwaggerUI at http://127.0.0.1:8080/#/docs, normally located under the Administration navbar menu.


问:
Why is difference between sqlContext.read.load and sqlContext.read.text?
I am only trying to read a textfile into a pyspark RDD, and I am noticing huge differences between sqlContext.read.load and sqlContext.read.text.

```<code>s3_single_file_inpath='s3a://bucket-name/file_name'

indata = sqlContext.read.load(s3_single_file_inpath, format='com.databricks.spark.csv', header='true', inferSchema='false',sep=',')
indata = sqlContext.read.text(s3_single_file_inpath)
</code>```

The sqlContext.read.load command above fails with

```<code>Py4JJavaError: An error occurred while calling o227.load.
: java.lang.ClassNotFoundException: Failed to find data source: com.databricks.spark.csv. Please find packages at http://spark-packages.org
</code>```

But the second one succeeds?

Now, I am confused by this because all of the resources I see online say to use sqlContext.read.load including this one: https://spark.apache.org/docs/1.6.1/sql-programming-guide.html.

It is not clear to me when to use which of these to use when.  Is there a clear distinction between these?

答:
The difference is:

text is a built-in input format in Spark 1.6

com.databricks.spark.csv is a third party package in Spark 1.6

To use third party Spark CSV (no longer needed in Spark 2.0) you have to follow the instructions on spark-csv site, for example provide

```<code> --packages com.databricks:spark-csv_2.10:1.5.0
</code>```

argument with spark-submit / pyspark commands.

Beyond that sqlContext.read.formatName(...) is a syntactic sugar for sqlContext.read.format("formatName") and sqlContext.read.load(..., format=formatName).

Body:
I am only trying to read a textfile into a pyspark RDD, and I am noticing huge differences between sqlContext.read.load and sqlContext.read.text.

s3_single_file_inpath='s3a://bucket-name/file_name'

indata = sqlContext.read.load(s3_single_file_inpath, format='com.databricks.spark.csv', header='true', inferSchema='false',sep=',')
indata = sqlContext.read.text(s3_single_file_inpath)

The sqlContext.read.load command above fails with

Py4JJavaError: An error occurred while calling o227.load.
: java.lang.ClassNotFoundException: Failed to find data source: com.databricks.spark.csv. Please find packages at http://spark-packages.org

But the second one succeeds?

Now, I am confused by this because all of the resources I see online say to use sqlContext.read.load including this one: https://spark.apache.org/docs/1.6.1/sql-programming-guide.html.

It is not clear to me when to use which of these to use when.  Is there a clear distinction between these?

Body:
The difference is:

text is a built-in input format in Spark 1.6

com.databricks.spark.csv is a third party package in Spark 1.6

To use third party Spark CSV (no longer needed in Spark 2.0) you have to follow the instructions on spark-csv site, for example provide

 --packages com.databricks:spark-csv_2.10:1.5.0

argument with spark-submit / pyspark commands.

Beyond that sqlContext.read.formatName(...) is a syntactic sugar for sqlContext.read.format("formatName") and sqlContext.read.load(..., format=formatName).


问:
Reactjs react-router Authenticate failling
I am new to ReactJS and sorry if this question was asked before, I don't know where to start.

I followed the Auth guidelines in:
https://reacttraining.com/react-router/web/example/auth-workflow

I am using react-router to handle navigation with ReactJS, I have an index.js file that handles the navigation and includes:

```<code>import {BrowserRouter, Redirect, Route} from 'react-router-dom';
import Auth from './components/Auth';

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    Auth.authenticate((auth) => {
      if (auth) {
        (<Component {...props}/>)
      }
      else {
        (<Redirect to={{
          pathname: '/',
          state: { from: props.location }
        }}/>)
      }
    })
  )}/>
)

const App = () => (<BrowserRouter>
  <div>
    {/* PUBLIC */}
      <Route path={'/'} exact component={Inicio}/>
      <Route path={'/login'} component={Login}/>

    {/* PRIVATE */}
      <PrivateRoute path="/dashboard" component={Dashboard}/>

  </div>
</BrowserRouter>);

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

Navigates fine, but the Authentication in Auth.authenticate((auth).. isn't working properly and throws an error.

It refers to a file that has the following:

```<code>import React from 'react';
import http from '../services/http';

const Auth = {
  authenticate(cb) {
    http.authenticate((e, auth) => {
      if (auth === true) {
        cb(true);
      }
      else {
        cb(false);
      }
    });
  }
}

export default Auth;
</code>```

http.aunthenticate is a method with a callback, that works fine.

Yet I get the following error message in the console:

```<code>> The above error occurred in the <Route> component:
>     in Route (created by PrivateRoute)
>     in PrivateRoute (created by App)
>     in MuiThemeProvider (created by App)
>     in div (created by App)
>     in Router (created by BrowserRouter)
>     in BrowserRouter (created by App)
>     in App
>
> Consider adding an error boundary to your tree to customize error
> handling behavior. Visit https://reactjs.org/docs/error-boundaries.html to learn
> more about error boundaries. react-dom.development.js:9747 Error:
> Route(...): Nothing was returned from render. This usually means a
> return statement is missing. Or, to render nothing, return null.
</code>```

Any ideas? Thanks!

答:
It loos like a simple syntax error:

```<code>const Auth = {
  authenticate(cb) {
    http.authenticate((e, auth) => {
      if (auth === true) {
        cb(true);
      }
      else {
        cb(false);
      }
    });
  }
}
</code>```

You need to define Auth as a valid React component (either a class or function). What you have there is not a valid class, function, or object.

More importantly if Auth is not rendering some jsx then it should not be a React component. HTTP requests should be defined as a class method, and called inside of a life-cycle hook, most commonly componentDidMount(). Article explaining how to make AJAX requests in react.

Body:
I am new to ReactJS and sorry if this question was asked before, I don't know where to start.

I followed the Auth guidelines in:
https://reacttraining.com/react-router/web/example/auth-workflow

I am using react-router to handle navigation with ReactJS, I have an index.js file that handles the navigation and includes:

import {BrowserRouter, Redirect, Route} from 'react-router-dom';
import Auth from './components/Auth';

const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    Auth.authenticate((auth) => {
      if (auth) {
        (<Component {...props}/>)
      }
      else {
        (<Redirect to={{
          pathname: '/',
          state: { from: props.location }
        }}/>)
      }
    })
  )}/>
)

const App = () => (<BrowserRouter>

    {/* PUBLIC */}
      <Route path={'/'} exact component={Inicio}/>
      <Route path={'/login'} component={Login}/>

    {/* PRIVATE */}
      <PrivateRoute path="/dashboard" component={Dashboard}/>

</BrowserRouter>);

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

Navigates fine, but the Authentication in Auth.authenticate((auth).. isn't working properly and throws an error.

It refers to a file that has the following:

import React from 'react';
import http from '../services/http';

const Auth = {
  authenticate(cb) {
    http.authenticate((e, auth) => {
      if (auth === true) {
        cb(true);
      }
      else {
        cb(false);
      }
    });
  }
}

export default Auth;

http.aunthenticate is a method with a callback, that works fine.

Yet I get the following error message in the console:

> The above error occurred in the <Route> component:
>     in Route (created by PrivateRoute)
>     in PrivateRoute (created by App)
>     in MuiThemeProvider (created by App)
>     in div (created by App)
>     in Router (created by BrowserRouter)
>     in BrowserRouter (created by App)
>     in App
>
> Consider adding an error boundary to your tree to customize error
> handling behavior. Visit https://reactjs.org/docs/error-boundaries.html to learn
> more about error boundaries. react-dom.development.js:9747 Error:
> Route(...): Nothing was returned from render. This usually means a
> return statement is missing. Or, to render nothing, return null.

Any ideas? Thanks!

Body:
It loos like a simple syntax error:

const Auth = {
  authenticate(cb) {
    http.authenticate((e, auth) => {
      if (auth === true) {
        cb(true);
      }
      else {
        cb(false);
      }
    });
  }
}

You need to define Auth as a valid React component (either a class or function). What you have there is not a valid class, function, or object.

More importantly if Auth is not rendering some jsx then it should not be a React component. HTTP requests should be defined as a class method, and called inside of a life-cycle hook, most commonly componentDidMount(). Article explaining how to make AJAX requests in react.


问:
PHP on an IIS server
I have designed a PHP based website which needs to run on a local server. Unfortunately I have developed this on a WAMP server using Apache. The machine on which this website will be placed on only supports the IIS server and I am not allowed to install Apache on this this machine.

How do I run PHP code on an IIS server?

答:
http://php.iis.net/

With IIS 7, a lot of the apache/iis gaps have been closed. Like mod_rewrite is available in IIS 7 (http://www.iis.net/download/urlrewrite)

Title: PHP on an IIS server


问:
scroll effect with labels using delay C#
I have a problem. I need to create a scroll effect with labels. The essence is to put the value to label with 1 sec delay.
I have a function which generates for each label number of the array. But it occurs immediately and I tried to make a delay. I used Timer but it doesn't give me any results or I just don't know how to use it correctly. Also tried to use Thread.Sleep() but it doesn't give me expected result.

```<code>public void generator() // присваивание текстбоксам значений
    {
        int[] array = getUniqueRandomArray(1, 81, 20).ToArray();
        green = 0;

        for (int i = 0; i < array.Length; i++)
        {
            panel1.Controls[i].Text = array[i].ToString();
            Thread.Sleep(350);
            panel1.Controls[i].Refresh();

            foreach (DataGridViewRow currentRow in dataGridView1.Rows)
            {
                foreach (DataGridViewCell currentCell in currentRow.Cells)
                {
                    if (Convert.ToInt32(currentCell.Value) == array[i] && currentCell.Style.BackColor == Color.Yellow)
                    {
                        currentCell.Style.BackColor = Color.Green;
                        green++;
                        panel1.Controls[i].BackColor = Color.Green;
                    }

                }
            }
        }
    }
</code>```

getUniqueRandomArray(1, 81, 20) - this function generates an array from 1 to 80 and returns 20 numbers.

When I use Thread.Sleep(350) I press the button and the form is freezing then each label gets a value from an array with delay 350ms. If I press this button one more time the current value replaces previous value without cleaning previous values though I clean them with:

```<code>for (int i = 0; i < panel1.Controls.Count; i++)
        {
            panel1.Controls[i].BackColor = Color.White;
            panel1.Controls[i].Text = null;
        }
</code>```

It is my actual result. But I expect to do described instructions without freezing from and in another thread that will allow me to use form while such circle is run.

And finally I'll try to explain more clearly:

I have 20 labels and 20 numbers. I need to assign each label the number with some delay - label1 = "1" -> (wait 1s) -> label2 = "2" -> (wait 1s) ... etc.

I would be grateful for help :)

答:
Just make you generator() an async one:

```<code>generator();

private async void generator()
{
   //(...)

   for (int i = 0; i < array.Length; i++)
   {
      panel1.Controls[i].Text = array[i].ToString();
      panel1.Controls[i].Refresh();
      await Task.Run(async () => await Task.Delay(1000));

      //(...)

   }
}
</code>```

About the comments:

```<code>await Task.Run(async () => await Task.Delay(1000))
</code>```

is a non-blocking awaiter. It is possible, depending on the context, that the second Task might be context-unaware. If that is the case, this can be solved using ConfigureAwait().

```<code>await Task.Run(async () => await Task.Delay(1200).ConfigureAwait(true)).ConfigureAwait(true);
</code>```

The second async in await Task.Run(async () => await Task.Delay(1000)); works as an Unwrap() method.

Usually, Task.Factory.StartNew() starts a new Task that runs in a different thread, and it returns immediately.
But using .Unwrap() on a Task<Task><TResult> gives you back a Task<TResult>, a proxy to the completion of the inner Task:

```<code>bool _task1 = await Task.Factory.StartNew(async delegate
{
   await Task.Delay(1000);
   return true;
}, TaskScheduler.Default).Unwrap<bool>();
</code>```

So, followind the same logic, one can substitute the Unwrap() method with a new awaiter.

```<code>bool _task2 = await await Task.Factory.StartNew(async delegate
{
   await Task.Delay(1000);
   return true;
}, TaskScheduler.Default);
</code>```

Now Task.Factory.StartNew() returns a Task<Task<bool>>.

If you Await Task<Task<bool>>, it returns a Task<bool>, and again awaiting that Task, a bool is returned.

But, if you don't need a type result:

```<code>await await Task.Factory.StartNew(async delegate
{
   await Task.Delay(1000);
}, TaskScheduler.Default);
</code>```

Which is functionally equivalent to:

```<code>await Task.Run(async () => await Task.Delay(1000))
</code>```

Body:
I have a problem. I need to create a scroll effect with labels. The essence is to put the value to label with 1 sec delay.
I have a function which generates for each label number of the array. But it occurs immediately and I tried to make a delay. I used Timer but it doesn't give me any results or I just don't know how to use it correctly. Also tried to use Thread.Sleep() but it doesn't give me expected result.

public void generator() // присваивание текстбоксам значений
    {
        int[] array = getUniqueRandomArray(1, 81, 20).ToArray();
        green = 0;

        for (int i = 0; i < array.Length; i++)
        {
            panel1.Controls[i].Text = array[i].ToString();
            Thread.Sleep(350);
            panel1.Controls[i].Refresh();

            foreach (DataGridViewRow currentRow in dataGridView1.Rows)
            {
                foreach (DataGridViewCell currentCell in currentRow.Cells)
                {
                    if (Convert.ToInt32(currentCell.Value) == array[i] && currentCell.Style.BackColor == Color.Yellow)
                    {
                        currentCell.Style.BackColor = Color.Green;
                        green++;
                        panel1.Controls[i].BackColor = Color.Green;
                    }

                }
            }
        }
    }

getUniqueRandomArray(1, 81, 20) - this function generates an array from 1 to 80 and returns 20 numbers.

When I use Thread.Sleep(350) I press the button and the form is freezing then each label gets a value from an array with delay 350ms. If I press this button one more time the current value replaces previous value without cleaning previous values though I clean them with:

for (int i = 0; i < panel1.Controls.Count; i++)
        {
            panel1.Controls[i].BackColor = Color.White;
            panel1.Controls[i].Text = null;
        }

It is my actual result. But I expect to do described instructions without freezing from and in another thread that will allow me to use form while such circle is run.

And finally I'll try to explain more clearly:

I have 20 labels and 20 numbers. I need to assign each label the number with some delay - label1 = "1" -> (wait 1s) -> label2 = "2" -> (wait 1s) ... etc.

I would be grateful for help :)

Body:
Just make you generator() an async one:

generator();

private async void generator()
{
   //(...)

   for (int i = 0; i < array.Length; i++)
   {
      panel1.Controls[i].Text = array[i].ToString();
      panel1.Controls[i].Refresh();
      await Task.Run(async () => await Task.Delay(1000));

      //(...)

   }
}

About the comments:

await Task.Run(async () => await Task.Delay(1000))

is a non-blocking awaiter. It is possible, depending on the context, that the second Task might be context-unaware. If that is the case, this can be solved using ConfigureAwait().

await Task.Run(async () => await Task.Delay(1200).ConfigureAwait(true)).ConfigureAwait(true);

The second async in await Task.Run(async () => await Task.Delay(1000)); works as an Unwrap() method.

Usually, Task.Factory.StartNew() starts a new Task that runs in a different thread, and it returns immediately.
But using .Unwrap() on a Task<Task><TResult> gives you back a Task<TResult>, a proxy to the completion of the inner Task:

bool _task1 = await Task.Factory.StartNew(async delegate
{
   await Task.Delay(1000);
   return true;
}, TaskScheduler.Default).Unwrap<bool>();

So, followind the same logic, one can substitute the Unwrap() method with a new awaiter.

bool _task2 = await await Task.Factory.StartNew(async delegate
{
   await Task.Delay(1000);
   return true;
}, TaskScheduler.Default);

Now Task.Factory.StartNew() returns a Task<Task<bool>>.

If you Await Task<Task<bool>>, it returns a Task<bool>, and again awaiting that Task, a bool is returned.

But, if you don't need a type result:

await await Task.Factory.StartNew(async delegate
{
   await Task.Delay(1000);
}, TaskScheduler.Default);

Which is functionally equivalent to:

await Task.Run(async () => await Task.Delay(1000))


问:
how to build the following dictionary from a json file?
Hello I am working with a json file that looks as follows:

```<code>{
    "workspace_id": "car-dashboard-en",
    "name": "Car Dashboard - Sample",
    "created": "2017-03-20T21:24:41.498Z",
    "intents": [
      {
        "intent": "about_VA",
        "created": "2017-03-14T02:02:16.290Z",
        "updated": "2017-03-14T02:02:16.290Z",
        "examples": [
          {
            "text": "any music reccomendation?",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
          {
            "text": "can you recommend ood jazz music?",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
          {
            "text": "cloud you recommend music?",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
          {
            "text": "your name",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          }
        ],
        "description": null
      },
      {
        "intent": "capabilities",
        "created": "2017-03-14T02:02:16.290Z",
        "updated": "2017-03-14T02:02:16.290Z",
        "examples": [
          {
            "text": "adapt to current weather condition",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
          {
            "text": "book a flight for NY on sunday",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },

          {
            "text": "can you change lanes",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
</code>```

I have one json that has a part called 'intents' this part is composed by several intents and every intent has one list of values called 'text',

I would like to extract from this file a dictionary as follows:

```<code>dictionary = {'intent_name':[text1,text1,text3,...],'intent_name2':[text1,text2,text3,...],...}
</code>```

the key of this dictionary is the name of the intent associated and the values is every text of this intent,

Unfortunately I am a beginner working with json files, so I tried:

```<code>import json

with open('workspace-car-dashboard-en.json') as json_file:
    data = json.load(json_file)
</code>```

with the following code I am extracting and printing all the text values as follows:

```<code>for element in data['intents']:
    for element2 in element['examples']:
        print(element2['text'])
</code>```

I got:

```<code>any music reccomendation?
can you recommend ood jazz music?
cloud you recommend music?
do you hate
Do you like
do you love
</code>```

However I am not able to build the dictionary on the fly and making an append to all the text values, so I really would like to appreciate support to achieve this difficult task.
I was not able to include the complete json file since it is very large so I hope this example is enough.

答:
Create a new empty dict. Add key of each intent name and set value of an empty list.
Then insert each text key value from the loop using examples text that you created.</p>

```<code>import json

with open('workspace-car-dashboard-en.json') as json_file:
    data = json.load(json_file)

new_dic = {}
for element in data['intents']:
    new_dic[element['intent']] = []
    for element2 in element['examples']:
        new_dic[element['intent']] += [element2['text']]
</code>```

Body:
Hello I am working with a json file that looks as follows:

{
    "workspace_id": "car-dashboard-en",
    "name": "Car Dashboard - Sample",
    "created": "2017-03-20T21:24:41.498Z",
    "intents": [
      {
        "intent": "about_VA",
        "created": "2017-03-14T02:02:16.290Z",
        "updated": "2017-03-14T02:02:16.290Z",
        "examples": [
          {
            "text": "any music reccomendation?",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
          {
            "text": "can you recommend ood jazz music?",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
          {
            "text": "cloud you recommend music?",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
          {
            "text": "your name",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          }
        ],
        "description": null
      },
      {
        "intent": "capabilities",
        "created": "2017-03-14T02:02:16.290Z",
        "updated": "2017-03-14T02:02:16.290Z",
        "examples": [
          {
            "text": "adapt to current weather condition",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },
          {
            "text": "book a flight for NY on sunday",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },

          {
            "text": "can you change lanes",
            "created": "2017-03-14T02:02:16.290Z",
            "updated": "2017-03-14T02:02:16.290Z"
          },

I have one json that has a part called 'intents' this part is composed by several intents and every intent has one list of values called 'text',

I would like to extract from this file a dictionary as follows:

dictionary = {'intent_name':[text1,text1,text3,...],'intent_name2':[text1,text2,text3,...],...}

the key of this dictionary is the name of the intent associated and the values is every text of this intent,

Unfortunately I am a beginner working with json files, so I tried:

import json

with open('workspace-car-dashboard-en.json') as json_file:
    data = json.load(json_file)

with the following code I am extracting and printing all the text values as follows:

for element in data['intents']:
    for element2 in element['examples']:
        print(element2['text'])

I got:

any music reccomendation?
can you recommend ood jazz music?
cloud you recommend music?
do you hate
Do you like
do you love

However I am not able to build the dictionary on the fly and making an append to all the text values, so I really would like to appreciate support to achieve this difficult task.
I was not able to include the complete json file since it is very large so I hope this example is enough.

Body:
Create a new empty dict. Add key of each intent name and set value of an empty list.
Then insert each text key value from the loop using examples text that you created.

import json

with open('workspace-car-dashboard-en.json') as json_file:
    data = json.load(json_file)

new_dic = {}
for element in data['intents']:
    new_dic[element['intent']] = []
    for element2 in element['examples']:
        new_dic[element['intent']] += [element2['text']]


问:
Pattern for dealing with mapping API objects to UI model objects
I am switching to use the new HttpClient in angular.

The API am calling returns json data in one format. I want to take this data and transform it into a  typescript model class suitable for the UI to work with.

The way I did this before was by using the map function e.g.

```<code>        return this.httpClient.get(url, { headers: headers })
        .map(mapFunction)
        .catch(errorFunction);
</code>```

Where the map function does the heavy lifting of transforming the api response intro a model object e.g.

```<code> const mapFunction =
            (response: Response) => {
                const data = response.json();
                const contacts: Contact[] = [];
                let i = 0;
                for (const result of data.resourceResults) {
                    i = i + 1;
                    const contact: Contact = new Contact();
                    contact.role = result.r
</code>```

To me this seems quite cumbersome and I am basically looking for a way to map objects from the api response type to the ui model type without having to use a custom map function for each request.

答:
There is no way to do custom mapping without, well, explicitly specifying what needs to be mapped. It's either you tell the server-side to return a UI friendly response, or you need to do the mapping yourself at the client side.

If you want to map the response on the client side, you can leverage on Typescript classes, and use its constructor to quickly generate the items you want:

```<code>export class Contact {
    public name:string;
    public roles:any;
    constructor(name:string, roles: any) {
        //specify your own constructor logic
        this.name=name;
        this.roles=roles
    }
}
</code>```

and now you can write in your mapFunction to explicitly convert the response to a list of Contacts. Also, you can use array's .map() to iterate through the objects, without writing a for loop :

```<code>public mapFunction = (response: Response) => {
    const data = response.json();
    const resource = data.resourceResults;
    //map it
    return resource.map(result => new Contact(result.n, result.r))
}
</code>```

Cumbersome or not, I think its subjective. But definitely you can write your code in a more elegant way.

Body:
I am switching to use the new HttpClient in angular.

The API am calling returns json data in one format. I want to take this data and transform it into a  typescript model class suitable for the UI to work with.

The way I did this before was by using the map function e.g.

        return this.httpClient.get(url, { headers: headers })
        .map(mapFunction)
        .catch(errorFunction);

Where the map function does the heavy lifting of transforming the api response intro a model object e.g.

 const mapFunction =
            (response: Response) => {
                const data = response.json();
                const contacts: Contact[] = [];
                let i = 0;
                for (const result of data.resourceResults) {
                    i = i + 1;
                    const contact: Contact = new Contact();
                    contact.role = result.r

To me this seems quite cumbersome and I am basically looking for a way to map objects from the api response type to the ui model type without having to use a custom map function for each request.

Body:
There is no way to do custom mapping without, well, explicitly specifying what needs to be mapped. It's either you tell the server-side to return a UI friendly response, or you need to do the mapping yourself at the client side.

If you want to map the response on the client side, you can leverage on Typescript classes, and use its constructor to quickly generate the items you want:

export class Contact {
    public name:string;
    public roles:any;
    constructor(name:string, roles: any) {
        //specify your own constructor logic
        this.name=name;
        this.roles=roles
    }
}

and now you can write in your mapFunction to explicitly convert the response to a list of Contacts. Also, you can use array's .map() to iterate through the objects, without writing a for loop :

public mapFunction = (response: Response) => {
    const data = response.json();
    const resource = data.resourceResults;
    //map it
    return resource.map(result => new Contact(result.n, result.r))
}

Cumbersome or not, I think its subjective. But definitely you can write your code in a more elegant way.


问:
what is the fastest way of loading images?
I have about 200,000 high resolution images, and loading such high quality images every time is time consuming.
Preloading all images might occupy too much memory.
How about saving each images into .npz file format and loading .npz instead of .jpg?  Would it be boosting speed?</p>

答:
You do not need to load all the image to memory at once. Considering also that we need to do data augmentation on the dataset during model training, it is impossible to load all images.

In PyTorch, you can use Dataset to store your training and validation set. The Dataset class has a parameter transforms(e.g., Scale, RandomCrop, etc.), which is used to transform the training image on the fly during training. Several ready-made dataset are also provided by torchvision package, see here.

Basic methold

PyTorch's builtin Dataloader has a num_worker, which is used to control how many subprocess you use for loading the data. Since your dataset is not so huge, that would be enough for your need. About how to set the appropriate number of worker, see here.

More references

There are discussion on PyTorch forum on fast image loading, use post1 and post2 as a start.

ContentLicense: CC BY-SA 4.0


问:
What exactly is Spring Framework for?
I hear a lot about Spring, people are saying all over the web that Spring is a good framework for web development. What exactly is Spring Framework for in a nutshell? Why should I used it over just plain Java.</p>

答:
Spring is a lightweight and flexible framework compare to J2EE.

Spring container act as a inversion of control.

Spring uses AOP i.e. proxies and Singleton, Factory and Template Method Design patterns.

Tiered architectures: Separation of concerns and Reusable layers and Easy maintenance.

Title: What exactly is Spring Framework for?


问:
NoClassDefFoundError Java When all fines exists in the classpath
```<code>$ ls
Dockerfile  Service1.class  Service1.java  socket.jar  tp/

$ java Service1 -jar socket.jar
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: real/connector/view/FunctionHandler
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: real.connector.view.FunctionHandler
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more
</code>```

I have put everything in place. Still seem to getting this error. Can anyone please suggest

答:
Setting CLASSPATH helped.
I set CLASSPATH as export CLASSPATH=/c/Users/Sufi/docker/socker.jar**:.**

I had missed :. in the end. Now its working good.

Body:
$ ls
Dockerfile  Service1.class  Service1.java  socket.jar  tp/

$ java Service1 -jar socket.jar
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: real/connector/view/FunctionHandler
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: real.connector.view.FunctionHandler
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more

I have put everything in place. Still seem to getting this error. Can anyone please suggest


问:
How do I use a Peekable iterator in a filter closure?
I need to find only the numbers where the next number is the same:  [1,2,2,3,4,4] should produce [2,4]. Since I need to peek at the next number, I figured I'd try out using a Peekable iterator and write a filter.

```<code>fn main() {
    let xs = [1, 2, 2, 3, 4, 4];
    let mut iter = xs.iter().peekable();

    let pairs = iter.filter(move |num| {
        match iter.peek() {
            Some(next) => num == next,
            None       => false,
        }
    });

    for num in pairs {
        println!("{}", num);
    }
}
</code>```

I get an error:

error[E0382]: capture of moved value: `iter`
 --> src/main.rs:6:15
  |
5 |     let pairs = iter.filter(move |num| {
  |                 ---- value moved here
6 |         match iter.peek() {
  |               ^^^^ value captured here after move
  |
  = note: move occurs because `iter` has type `std::iter::Peekable<std::slice::Iter<'_, i32>>`, which does not implement the `Copy` trait
```

I think this is because iter is being used by the closure, but it hasn't borrowed it, and it can't copy it.

How do I solve this problem of wanting to refer to the iterator inside a filter?

答:
refer to the iterator inside a filter

I don't believe you can. When you call filter, it takes ownership of the base iterator:

```<code>fn filter<P>(self, predicate: P) -> Filter<Self, P>
where
    P: FnMut(&Self::Item) -> bool,
</code>```

Once you do that, it's gone. There is no more iter. In some similar cases, you can use Iterator::by_ref to mutably borrow the iterator, drive it for a while, then refer back to the original. That won't work in this case because the inner iterator would need to borrow it mutably a second time, which is disallowed.

find only the numbers where the next number is the same.

```<code>extern crate itertools;

use itertools::Itertools;

fn main() {
    let input = [1, 2, 2, 3, 4, 4];

    let pairs = input
        .iter()
        .tuple_windows()
        .filter_map(|(a, b)| if a == b { Some(a) } else { None });

    let result: Vec<_> = pairs.cloned().collect();
    assert_eq!(result, [2, 4]);
}
</code>```

Or if you wanted something using only the standard library:

```<code>fn main() {
    let xs = [1, 2, 2, 3, 4, 4];

    let mut prev = None;
    let pairs = xs.iter().filter_map(move |curr| {
        let next = if prev == Some(curr) { Some(curr) } else { None };
        prev = Some(curr);
        next
    });

    let result: Vec<_> = pairs.cloned().collect();
    assert_eq!(result, [2, 4]);
}
</code>```

Body:
I need to find only the numbers where the next number is the same:  [1,2,2,3,4,4] should produce [2,4]. Since I need to peek at the next number, I figured I'd try out using a Peekable iterator and write a filter.

fn main() {
    let xs = [1, 2, 2, 3, 4, 4];
    let mut iter = xs.iter().peekable();

    let pairs = iter.filter(move |num| {
        match iter.peek() {
            Some(next) => num == next,
            None       => false,
        }
    });

    for num in pairs {
        println!("{}", num);
    }
}

I get an error:

error[E0382]: capture of moved value: `iter`
 --> src/main.rs:6:15
  |
5 |     let pairs = iter.filter(move |num| {
  |                 ---- value moved here
6 |         match iter.peek() {
  |               ^^^^ value captured here after move
  |
  = note: move occurs because `iter` has type `std::iter::Peekable<std::slice::Iter<'_, i32>>`, which does not implement the `Copy` trait

I think this is because iter is being used by the closure, but it hasn't borrowed it, and it can't copy it.

How do I solve this problem of wanting to refer to the iterator inside a filter?

Body:
refer to the iterator inside a filter

I don't believe you can. When you call filter, it takes ownership of the base iterator:

fn filter<P>(self, predicate: P) -> Filter<Self, P>
where
    P: FnMut(&Self::Item) -> bool,

Once you do that, it's gone. There is no more iter. In some similar cases, you can use Iterator::by_ref to mutably borrow the iterator, drive it for a while, then refer back to the original. That won't work in this case because the inner iterator would need to borrow it mutably a second time, which is disallowed.

find only the numbers where the next number is the same.

extern crate itertools;

use itertools::Itertools;

fn main() {
    let input = [1, 2, 2, 3, 4, 4];

    let pairs = input
        .iter()
        .tuple_windows()
        .filter_map(|(a, b)| if a == b { Some(a) } else { None });

    let result: Vec<_> = pairs.cloned().collect();
    assert_eq!(result, [2, 4]);
}

Or if you wanted something using only the standard library:

fn main() {
    let xs = [1, 2, 2, 3, 4, 4];

    let mut prev = None;
    let pairs = xs.iter().filter_map(move |curr| {
        let next = if prev == Some(curr) { Some(curr) } else { None };
        prev = Some(curr);
        next
    });

    let result: Vec<_> = pairs.cloned().collect();
    assert_eq!(result, [2, 4]);
}


问:
How to addTarget to UIButton without sender
I have a function...

```<code>func MyFunc (_ sender: AnyObject) {
    let n = sender.tag! //do stuff with 'n'
}
</code>```

which I connect when creating my NewButton...

```<code>NewButton.addTarget(self, action: #selector(Main.MyFunc(_:)), for: .touchUpInside)
</code>```

I'd like to call MyFunc in other areas of my code without a sender. Is it possible to .addTarget to a Button without using sender?

Such as....

```<code>NewButton.addTarget(self, action: #selector(Main.MyFunc(n: 5)), for: .touchUpInside)
</code>```

and...

```<code>func MyFunc (n: Int) {
    //do stuff with 'n'
}
</code>```

I know one solution would be a routing function like...

```<code>func router (_ sender: AnyObject) {
    MyFunc(n: sender.tag!)
}
</code>```

But I'm wondering if there's a more elegant way.

答:
Since the function takes a sender of type AnyObject you can use any object as an argument to the function. You will then just need to conditionally cast it to the type you want.

```<code>let button = UIButton()
button.addTarget(self, action: #selector(touched(_:)), for: .touchUpInside)

touched(1 as AnyObject) // Works

@objc func touched(_ sender: AnyObject) {
    if let casted = sender as? Int {
        // Do something with casted as an Int
    } else if let casted = sender as? UIButton {
        // do something with casted.tag
    }
}
</code>```

Body:
I have a function...

func MyFunc (_ sender: AnyObject) {
    let n = sender.tag! //do stuff with 'n'
}

which I connect when creating my NewButton...

NewButton.addTarget(self, action: #selector(Main.MyFunc(_:)), for: .touchUpInside)

I'd like to call MyFunc in other areas of my code without a sender. Is it possible to .addTarget to a Button without using sender?

Such as....

NewButton.addTarget(self, action: #selector(Main.MyFunc(n: 5)), for: .touchUpInside)

and...

func MyFunc (n: Int) {
    //do stuff with 'n'
}

I know one solution would be a routing function like...

func router (_ sender: AnyObject) {
    MyFunc(n: sender.tag!)
}

But I'm wondering if there's a more elegant way.

Body:
Since the function takes a sender of type AnyObject you can use any object as an argument to the function. You will then just need to conditionally cast it to the type you want.

let button = UIButton()
button.addTarget(self, action: #selector(touched(_:)), for: .touchUpInside)

touched(1 as AnyObject) // Works

@objc func touched(_ sender: AnyObject) {
    if let casted = sender as? Int {
        // Do something with casted as an Int
    } else if let casted = sender as? UIButton {
        // do something with casted.tag
    }
}


问:
Regex - Match up until there's an equal amount of 2 specific characters
For example if I have the following sentence:

a cat bit a dog on the butt before running away

If the 2 characters I want to use are 'a' and 'b' then I want to match up until the point where there are equal amounts of 'a' and 'b' like the following:

a cat bit a dog on the butt b

In the above case, the sentence has 5 a's and 3 b's. I want to much up to the point where I have 3 a's and 3 b's.

Thank you for the help.

答:
var a = 0,
    b = 0;
var result = 0;
var patten = /./g;
for (;patten.exec("a cat bit a dog on the butt before running away") != null;) {
    if (RegExp['$&'] == "a") {
        a++;
  if (a == b) {
   result = patten.lastIndex;
        }
    }
    if (RegExp['$&'] == "b") {
        b++;
        if (a == b) {
            result = patten.lastIndex;
        }
    }
}
console.log("1~" + result);
console.log("a cat bit a dog on the butt before running away".slice(0,result));```

by the way, 朕也会功夫。

Body:
var a = 0,
    b = 0;
var result = 0;
var patten = /./g;
for (;patten.exec("a cat bit a dog on the butt before running away") != null;) {
    if (RegExp['$&'] == "a") {
        a++;
  if (a == b) {
   result = patten.lastIndex;
        }
    }
    if (RegExp['$&'] == "b") {
        b++;
        if (a == b) {
            result = patten.lastIndex;
        }
    }
}
console.log("1~" + result);
console.log("a cat bit a dog on the butt before running away".slice(0,result));

by the way, 朕也会功夫。


问:
*** glibc detected *** ms2: free(): invalid pointer: 0xb7526ff4 ***
I keep getting this error and I'm not sure how to correct it as I am given no errors in my code editors. I have looked up similar issues, but I am still having trouble to understand how to apply the solutions here. I've tried altering my code for several hours now, but to no avail. Any help would be appreciated. I have provided my .h and .cpp files below.

ErrorMessage.h

```<code>#ifndef SICT_ERRORMESSAGE_H
#define SICT_ERRORMESSAGE_H
#include <iostream>

namespace sict {
    class ErrorMessage {
        char* message_; //pointer that holds the address of the message stored in current object
    public:
        explicit ErrorMessage(const char* errorMessage = nullptr); //receive address of a C-style nullterminate string holding an error message
        ErrorMessage(const ErrorMessage& em) = delete; //deleted copy constructor that prevents copying of an ErrorMessage object
        ErrorMessage& operator=(const ErrorMessage& em) = delete; //deleted assignment operator that prevents assignment of ErrorMessage object to current object
        virtual ~ErrorMessage(); //deallocates any memory that has been dynamically allocated by the current object
        void clear(); //clears any message stored by current object and initialize object to safe, empty state
        bool isClear() const; //return true if object is in a safe, empty state
        void message(const char* str); //stores a copy of the C-style string pointed to by str
        const char* message() const; //return address of the message stored in current object
    };
    //helper operator
      std::ostream& operator<<(std::ostream& os, const ErrorMessage& err);
}
#endif
</code>```

ErrorMessage.cpp

```<code>#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include "ErrorMessage.h"

namespace sict {

    ErrorMessage::ErrorMessage(const char* errorMessage) {
    if(errorMessage == nullptr) {
        message_ = nullptr;
    }
    else {
            message(errorMessage);
    }
    }

    ErrorMessage::~ErrorMessage() {
    delete [] message_;
    }

    void ErrorMessage::clear() {
    delete [] message_;
    message_ = nullptr;
    }

    bool ErrorMessage::isClear() const {
        if(message_ == nullptr) {
            return true;
        }
        else {
            return false;
        }
    }

    void ErrorMessage::message(const char* str) {
        delete [] message_;
        message_ = new char[strlen(str) + 1];
        strcpy(message_, str);
    }

    const char* ErrorMessage::message() const {
        return message_;
    }

    std::ostream& operator<<(std::ostream& os, const ErrorMessage& err) {
    if(!err.isClear()) {
          os << err.message();
    }
    return os;
    }
}
</code>```

答:
It's not surprising your code made it through editor syntax checks and compilation - it's valid code.  It's just got an incorrect pointer somewhere.

This may mean that your'e accidentally dereferencing something , or perhaps passing a value somewhere you should be passing a pointer.  You should get a compile time warning about that kind of stuff.

Another possibility is that you're failing to initialize some pointer, and its value happens to be 0xb75....

Clearly, neither you nor I are not likely to guess from whence this error originates.  As Sam Varshavchik pointed out in a comment, you don't even know if  the code you posted is the source of the error.   Even if you guess your way through this one ( or perhaps keenly observe, Sam ), it's just plain silly to try to write C++ that way.

What you need is a debugger.  A debugger is a program you run your program within, and it keeps track of the program's state so that when you have a memory violation, the debugger can produce a backtrace showing where in your source code the error occurred.  You also have to compile your program with debugging support, so that the debugger has markers it can use to refer back to the source code.

It's a process far beyond the scope of your question, but one that's easy to learn about once you know what you're going for.  Look for one that integrates with your IDE, if possible, as you're leveraging your development environment heavily.  It's not unlikely that you already have it set up- you might just need to use it.  Search for C++ debugging in the context of your editor first - if it turns up nothing, consider searching under your compiler suite, whatever that may be ( if your'e using open source, you're probably using gcc, and the matching debugger is gdb ).

You're about to gain a far more accurate understanding of what it is to program C / C++.  Good luck.

Body:
I keep getting this error and I'm not sure how to correct it as I am given no errors in my code editors. I have looked up similar issues, but I am still having trouble to understand how to apply the solutions here. I've tried altering my code for several hours now, but to no avail. Any help would be appreciated. I have provided my .h and .cpp files below.

ErrorMessage.h

#ifndef SICT_ERRORMESSAGE_H
#define SICT_ERRORMESSAGE_H
#include <iostream>

namespace sict {
    class ErrorMessage {
        char* message_; //pointer that holds the address of the message stored in current object
    public:
        explicit ErrorMessage(const char* errorMessage = nullptr); //receive address of a C-style nullterminate string holding an error message
        ErrorMessage(const ErrorMessage& em) = delete; //deleted copy constructor that prevents copying of an ErrorMessage object
        ErrorMessage& operator=(const ErrorMessage& em) = delete; //deleted assignment operator that prevents assignment of ErrorMessage object to current object
        virtual ~ErrorMessage(); //deallocates any memory that has been dynamically allocated by the current object
        void clear(); //clears any message stored by current object and initialize object to safe, empty state
        bool isClear() const; //return true if object is in a safe, empty state
        void message(const char* str); //stores a copy of the C-style string pointed to by str
        const char* message() const; //return address of the message stored in current object
    };
    //helper operator
      std::ostream& operator<<(std::ostream& os, const ErrorMessage& err);
}
#endif

ErrorMessage.cpp

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include "ErrorMessage.h"

namespace sict {

    ErrorMessage::ErrorMessage(const char* errorMessage) {
    if(errorMessage == nullptr) {
        message_ = nullptr;
    }
    else {
            message(errorMessage);
    }
    }

    ErrorMessage::~ErrorMessage() {
    delete [] message_;
    }

    void ErrorMessage::clear() {
    delete [] message_;
    message_ = nullptr;
    }

    bool ErrorMessage::isClear() const {
        if(message_ == nullptr) {
            return true;
        }
        else {
            return false;
        }
    }

    void ErrorMessage::message(const char* str) {
        delete [] message_;
        message_ = new char[strlen(str) + 1];
        strcpy(message_, str);
    }

    const char* ErrorMessage::message() const {
        return message_;
    }

    std::ostream& operator<<(std::ostream& os, const ErrorMessage& err) {
    if(!err.isClear()) {
          os << err.message();
    }
    return os;
    }
}


问:
Validating Saml Response From OneLogin

I'm trying to validate a Saml Response from OneLogin and am running into an intermittent issue. It seems that when the GUID value in InResponseTo begins with a number, validation of the token fails with an exception message: ID4128: The value is not a valid SAML ID. Parameter name: value. However, when the GUID begins with a letter, the token is parsed successfully.

My code:

```<code> public Saml2SecurityToken GetToken(string token)
    {
        var doc = new XmlDocument();
        doc.LoadXml(token);
        var assertionList = doc.GetElementsByTagName("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion");

        var handlers = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
        var securityTokenXml = assertionList[0].OuterXml;

        using (var stringReader = new StringReader(securityTokenXml))
        {
            using (var xmlreader = XmlReader.Create(stringReader))
            {
                return (Saml2SecurityToken) handlers.ReadToken(xmlreader);
            }
        }
    }
</code>```

My token:

```<code><saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.0" ID="pfx74145d78-55a9-dd78-00a0-2ee76d06a900" IssueInstant="2017-12-04T17:46:32Z">
<saml:Issuer>https://app.onelogin.com/saml/123</saml:Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
        <ds:Reference URI="#pfx74145d78-55a9-dd78-00a0-2ee76d06a900">
            <ds:Transforms>
                <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
            <ds:DigestValue>111</ds:DigestValue>
        </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>abc...</ds:SignatureValue>
    <ds:KeyInfo>
        <ds:X509Data>
            <ds:X509Certificate>abc...</ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</ds:Signature>
<saml:Subject>
    <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">nameHere</saml:NameID>
    <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
        <saml:SubjectConfirmationData NotOnOrAfter="2017-12-04T17:49:32Z" Recipient="http://localhost/" InResponseTo="7ee0ebbd-3827-4e53-adc5-b8ec35917f2d" />
    </saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2017-12-04T17:43:32Z" NotOnOrAfter="2017-12-04T17:49:32Z">
    <saml:AudienceRestriction>
        <saml:Audience>AudienceName</saml:Audience>
    </saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2017-12-04T17:46:31Z" SessionNotOnOrAfter="2017-12-05T17:46:32Z" SessionIndex="_fd124dd0-bb48-0135-5d75-0a8402be19a0">
    <saml:AuthnContext>
        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
    </saml:AuthnContext>
</saml:AuthnStatement>
</code>```

Full Stack Trace:

```<code>at System.IdentityModel.Tokens.Saml2Id..ctor(String value)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadSubjectConfirmationData(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadSubjectConfirmationData(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadSubjectConfirmation(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadSubject(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadAssertion(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadToken(XmlReader reader)
at System.IdentityModel.Tokens.SecurityTokenHandlerCollection.ReadToken(XmlReader reader)
</code>```

Is there another way to read/validate this? Or can the InResponseTo be ignored/removed somehow?

Thanks

答:
If OneLogin is sending unsolicted responses with IDs that start with a number, then they are not compliant with spec. IDs are of the xsd:ID datatype and have a specific definition: it must start with a letter or underscore, and can only contain letters, digits, underscores, hyphens, and periods.

However, looking at this, they are sending that in the InResponseTo field... Which is the ID you sent them in your AuthnRequest... So, you need to fix your code, because they are being nice and just accepting what you sent them. You certainly should fix this so you're compliant.

Title: Validating Saml Response From OneLogin

Body:
I'm trying to validate a Saml Response from OneLogin and am running into an intermittent issue. It seems that when the GUID value in InResponseTo begins with a number, validation of the token fails with an exception message: ID4128: The value is not a valid SAML ID. Parameter name: value. However, when the GUID begins with a letter, the token is parsed successfully.

My code:

 public Saml2SecurityToken GetToken(string token)
    {
        var doc = new XmlDocument();
        doc.LoadXml(token);
        var assertionList = doc.GetElementsByTagName("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion");

        var handlers = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
        var securityTokenXml = assertionList[0].OuterXml;

        using (var stringReader = new StringReader(securityTokenXml))
        {
            using (var xmlreader = XmlReader.Create(stringReader))
            {
                return (Saml2SecurityToken) handlers.ReadToken(xmlreader);
            }
        }
    }

My token:

<saml:Assertion xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Version="2.0" ID="pfx74145d78-55a9-dd78-00a0-2ee76d06a900" IssueInstant="2017-12-04T17:46:32Z">
<saml:Issuer>https://app.onelogin.com/saml/123</saml:Issuer>
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
        <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" />
        <ds:Reference URI="#pfx74145d78-55a9-dd78-00a0-2ee76d06a900">
            <ds:Transforms>
                <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" />
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256" />
            <ds:DigestValue>111</ds:DigestValue>
        </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>abc...</ds:SignatureValue>
    <ds:KeyInfo>
        <ds:X509Data>
            <ds:X509Certificate>abc...</ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</ds:Signature>
<saml:Subject>
    <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">nameHere</saml:NameID>
    <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
        <saml:SubjectConfirmationData NotOnOrAfter="2017-12-04T17:49:32Z" Recipient="http://localhost/" InResponseTo="7ee0ebbd-3827-4e53-adc5-b8ec35917f2d" />
    </saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2017-12-04T17:43:32Z" NotOnOrAfter="2017-12-04T17:49:32Z">
    <saml:AudienceRestriction>
        <saml:Audience>AudienceName</saml:Audience>
    </saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2017-12-04T17:46:31Z" SessionNotOnOrAfter="2017-12-05T17:46:32Z" SessionIndex="_fd124dd0-bb48-0135-5d75-0a8402be19a0">
    <saml:AuthnContext>
        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>
    </saml:AuthnContext>
</saml:AuthnStatement>

Full Stack Trace:

at System.IdentityModel.Tokens.Saml2Id..ctor(String value)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadSubjectConfirmationData(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadSubjectConfirmationData(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadSubjectConfirmation(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadSubject(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadAssertion(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadToken(XmlReader reader)
at System.IdentityModel.Tokens.SecurityTokenHandlerCollection.ReadToken(XmlReader reader)

Is there another way to read/validate this? Or can the InResponseTo be ignored/removed somehow?

Thanks


问:
Pizzicato JS - No Frequency Data
I would like to use Pizzicato JS, with Three JS to create a sound visualizer. But for some reason after I get the frequency data, it's returning a frequency of 0 for each band. Is there something that I'm missing in order to get these frequencies so I can them manipulate my meshes with Three JS, please let me know?. I've attached a screenshot of my console window and pasted my code below for reference.

```<code>var context = Pizzicato.context;
var analyser = context.createAnalyser();

var ambient = new Pizzicato.Sound('./mp3/ambient.mp3', playAmbient);
ambient.loop = true;
ambient.volume = 1;
ambient.connect(analyser);

var frequencyData = new Uint8Array(analyser.frequencyBinCount);
console.log("Frequency Data: " , frequencyData);
console.log("Frequency Data Length: " , frequencyData.length);`

function playAmbient(e)
{
    console.log("playAmbient();");
    ambient.play();
}
</code>```

Thanks

答:
So I figured it out, I was expecting the frequency data to return back a array of frequencies for each band when doing a console.log(). When in reality I had to receive my frequency data using the getByteFrequencyData method. I've pasted my new set of code to reference the issue of the undefined data.</p>

```<code>context = Pizzicato.context;
analyser = context.createAnalyser();

sound = new Pizzicato.Sound(params, playAmbient);
sound.volume = 1;
sound.connect(analyser);

function playAmbient(e)
{
    console.log("playAmbient();");
    ambient.play();
}
setInterval(function () {
    try{
        var bufferLength = analyser.frequencyBinCount;
        frequencyData = new Uint8Array(bufferLength);

        // The statement below was missing, and in return it will then
        // update my frequencies for each band given from my
        // frequencyData.
        analyser.getByteFrequencyData(frequencyData);

        // Now I'm seeing the frequencies update in my console.log window
        // when each interval is fired.
        console.log(frequencyData);
    }catch(error){
        console.log(error);
    }
}, 500);
</code>```

Title: Pizzicato JS - No Frequency Data

Body:
I would like to use Pizzicato JS, with Three JS to create a sound visualizer. But for some reason after I get the frequency data, it's returning a frequency of 0 for each band. Is there something that I'm missing in order to get these frequencies so I can them manipulate my meshes with Three JS, please let me know?. I've attached a screenshot of my console window and pasted my code below for reference.

var context = Pizzicato.context;
var analyser = context.createAnalyser();

var ambient = new Pizzicato.Sound('./mp3/ambient.mp3', playAmbient);
ambient.loop = true;
ambient.volume = 1;
ambient.connect(analyser);

var frequencyData = new Uint8Array(analyser.frequencyBinCount);
console.log("Frequency Data: " , frequencyData);
console.log("Frequency Data Length: " , frequencyData.length);`

function playAmbient(e)
{
    console.log("playAmbient();");
    ambient.play();
}

Thanks

Body:
So I figured it out, I was expecting the frequency data to return back a array of frequencies for each band when doing a console.log(). When in reality I had to receive my frequency data using the getByteFrequencyData method. I've pasted my new set of code to reference the issue of the undefined data.

context = Pizzicato.context;
analyser = context.createAnalyser();

sound = new Pizzicato.Sound(params, playAmbient);
sound.volume = 1;
sound.connect(analyser);

function playAmbient(e)
{
    console.log("playAmbient();");
    ambient.play();
}
setInterval(function () {
    try{
        var bufferLength = analyser.frequencyBinCount;
        frequencyData = new Uint8Array(bufferLength);

        // The statement below was missing, and in return it will then
        // update my frequencies for each band given from my
        // frequencyData.
        analyser.getByteFrequencyData(frequencyData);

        // Now I'm seeing the frequencies update in my console.log window
        // when each interval is fired.
        console.log(frequencyData);
    }catch(error){
        console.log(error);
    }
}, 500);


问:
How to properly cleanup Cassandra after stress testing?
I've been tasked with standing up and prep'ing our production Cassandra cluster (3.11.1). Everything was fine, loaded in a few hundred million records with the stress testing tool, great. However after I was done I did a "DROP KEYSPACE keyspace1;" (the space used by the stress test) assuming this was like MySQL and the space would be cleaned up.

Now I've run nodetools cleanup, flush, truncatehints, cleansnapshots and just about every other command variation I can find. The disk usage is still ~30GB per node and nothing seems to be going on in Cassandra.

So #1 - How do I recover the diskspace that is being absorbed by the now deleted keyspace?

And #2 - How should I have deleted this data, if this was the "wrong way"?

答: After you drop the keyspace you can delete its directory in your data directory. Which would clean it up, there isnt a command to do that.</p>


问:
Execute command on all puppet nodes
I would like execute below simple command in all of my nodes which returns me whether symbolic links are available using puppet facter.

'ls -l | grep lrw | grep data'

How to run this command and collect the results from one client ?

I do not have puppet master and only have puppet node installed in all my client machines.

答:
You can simple use pdsh to run remotely the command you want on any node you want, I don’t think you have to mes with any puppet stuff to accomplish you’re task </p>

<p>Check it out this to get an idea how it works :) </p>

Title: Execute command on all puppet nodes

Body:
You can simple use pdsh to run remotely the command you want on any node you want, I don’t think you have to mes with any puppet stuff to accomplish you’re task

Check it out this to get an idea how it works :)


问:
using sed from a seperate file
I have a project that I have to use a random number to alter a password. If the number is lower than value given it changes that letter. If it is higher the letter stays the same. My issue is that I am having problems finding information about using sed from another file to change the letter. Now this is not needed, but I feel that it will be cleaner in my opinion. Now my question is how could I call the file from my bash script that will use sed to substitute a letter. I just think sticking 26 sed commands in my script is a little much when I could place it in a separate file. If you know a better way that is fine.

Basic what I need either a better way. Or a way of calling a file and storing sed commands in a separate file from a bash script. And a way to pass just a single character, so if it is the second a in HaloStack, the sec command will not change the first because it would have already been changed possibly.

Below is what I have. I am working on the sed script right now. But I do not know of the way to send it only one character to change.

```<code>#!/bin/bash

#FUNCTIONS
##Random word grabber
passwdget () {
wget -qO- http://creativitygames.net/random-word-generator/randomwords/$wordamount | grep -o 'randomword_[1-9]\">[a-z]*' | awk -F ">" '{print $2}' > test.txt
}

#parses the words from one file
oneline () {
paste -s test.txt | sed 's/[[:blank:]]//g' > testnospace.txt
rm test.txt
mv testnospace.txt test.txt
}

passwdrnd () {
# Declare array
passwdstr=$(cat test.txt)
}

#VARIABLES
wordamount=4
complexity=0.0

#GET OPTIONS
while getopts ":n:t:" opt; do
    case ${opt} in
        n ) wordamount="$OPTARG";;
        t ) complexity="$OPTARG";;
        \?) ;;#invalad option
        : ) ;;#missing arguments for an option
    esac
done

#MAIN PROGRAM
passwdget
oneline
passwdrnd
echo $passwdstr

exit 0

#Use next information for getting a random number between 0.0 - 1.0
#awk -v seed=$RANDOM 'BEGIN{srand(seed);print rand()}'

#Get position echo ${var:position:length}
</code>```

Sample word list that needs to be altered in different ways.

```<code>pimplefrogsoapchimp
</code>```

答:
I'm not sure if I understood the question correctly, but if so, this seems to work:

```<code>#!/bin/bash

#FUNCTIONS
##Random word grabber
passwdget () {
wget -qO- http://creativitygames.net/random-word-generator/randomwords/$wordamount | grep -o 'randomword_[1-9]\">[a-z]*' | awk -F ">" '{print $2}' > tes$
}

#parses the words from one file
oneline () {
paste -s test.txt | sed 's/[[:blank:]]//g' > testnospace.txt
rm test.txt
mv testnospace.txt test.txt
}

passwdrnd () {
# Declare array
randchar=255;
passwdstr=$(cat test.txt)
randnum=$(dd if=/dev/urandom count=1 bs=1 2>/dev/null| od -a -i | head -n 2 | tail -n 1 | awk '{print $1}')
chars="abcdefghijklmnopqrstuvwxyz";
if [ $randnum -ge 127 ]; then
randchar=255;
while [ $randchar -ge 27 ]; do
randchar=$(dd if=/dev/urandom count=1 bs=1 2>/dev/null| od -a -i | head -n 2 | tail -n 1 | awk '{print $1}')
done;
onechar=`echo $chars | cut -c $randchar`
fi;
#if [ $randnum -le 127 ]; then
#false;
#fi;
}

#VARIABLES
wordamount=4
complexity=0.0

#GET OPTIONS
while getopts ":n:t:" opt; do
    case ${opt} in
        n ) wordamount="$OPTARG";;
        t ) complexity="$OPTARG";;
        \?) ;;#invalad option
        : ) ;;#missing arguments for an option
    esac
done

#MAIN PROGRAM
passwdget
oneline
passwdrnd
#echo $passwdstr
echo $passwdstr
spacing=500;
while [ $spacing -ge `echo $passwdstr | wc -c` ]; do
spacing=$(dd if=/dev/urandom count=1 bs=1 2>/dev/null| od -a -i | head -n 2 | tail -n 1 | awk '{print $1}')
done;
other=`expr $spacing - 2`
fpart=`echo $passwdstr | cut -c -$other`
spart=`echo $passwdstr | cut -c $spacing-`;
echo $fpart$onechar$spart

exit 0

#Use next information for getting a random number between 0.0 - 1.0
#awk -v seed=$RANDOM 'BEGIN{srand(seed);print rand()}'
</code>```

It will use some random to take a character out of what is pulled from wget and change one of them if a random between 0 and 255 returns higher or lower than 127; then it will put the first part in a varaible, a random character in another variable, and the second part in the third variable and print it.

Title: using sed from a seperate file

Body:
I have a project that I have to use a random number to alter a password. If the number is lower than value given it changes that letter. If it is higher the letter stays the same. My issue is that I am having problems finding information about using sed from another file to change the letter. Now this is not needed, but I feel that it will be cleaner in my opinion. Now my question is how could I call the file from my bash script that will use sed to substitute a letter. I just think sticking 26 sed commands in my script is a little much when I could place it in a separate file. If you know a better way that is fine.

Basic what I need either a better way. Or a way of calling a file and storing sed commands in a separate file from a bash script. And a way to pass just a single character, so if it is the second a in HaloStack, the sec command will not change the first because it would have already been changed possibly.

Below is what I have. I am working on the sed script right now. But I do not know of the way to send it only one character to change.

#!/bin/bash

#FUNCTIONS
##Random word grabber
passwdget () {
wget -qO- http://creativitygames.net/random-word-generator/randomwords/$wordamount | grep -o 'randomword_[1-9]\">[a-z]*' | awk -F ">" '{print $2}' > test.txt
}

#parses the words from one file
oneline () {
paste -s test.txt | sed 's/[[:blank:]]//g' > testnospace.txt
rm test.txt
mv testnospace.txt test.txt
}

passwdrnd () {
# Declare array
passwdstr=$(cat test.txt)
}

#VARIABLES
wordamount=4
complexity=0.0

#GET OPTIONS
while getopts ":n:t:" opt; do
    case ${opt} in
        n ) wordamount="$OPTARG";;
        t ) complexity="$OPTARG";;
        \?) ;;#invalad option
        : ) ;;#missing arguments for an option
    esac
done

#MAIN PROGRAM
passwdget
oneline
passwdrnd
echo $passwdstr

exit 0

#Use next information for getting a random number between 0.0 - 1.0
#awk -v seed=$RANDOM 'BEGIN{srand(seed);print rand()}'

#Get position echo ${var:position:length}

Sample word list that needs to be altered in different ways.

pimplefrogsoapchimp

Body:
I'm not sure if I understood the question correctly, but if so, this seems to work:

#!/bin/bash

#FUNCTIONS
##Random word grabber
passwdget () {
wget -qO- http://creativitygames.net/random-word-generator/randomwords/$wordamount | grep -o 'randomword_[1-9]\">[a-z]*' | awk -F ">" '{print $2}' > tes$
}

#parses the words from one file
oneline () {
paste -s test.txt | sed 's/[[:blank:]]//g' > testnospace.txt
rm test.txt
mv testnospace.txt test.txt
}

passwdrnd () {
# Declare array
randchar=255;
passwdstr=$(cat test.txt)
randnum=$(dd if=/dev/urandom count=1 bs=1 2>/dev/null| od -a -i | head -n 2 | tail -n 1 | awk '{print $1}')
chars="abcdefghijklmnopqrstuvwxyz";
if [ $randnum -ge 127 ]; then
randchar=255;
while [ $randchar -ge 27 ]; do
randchar=$(dd if=/dev/urandom count=1 bs=1 2>/dev/null| od -a -i | head -n 2 | tail -n 1 | awk '{print $1}')
done;
onechar=`echo $chars | cut -c $randchar`
fi;
#if [ $randnum -le 127 ]; then
#false;
#fi;
}

#VARIABLES
wordamount=4
complexity=0.0

#GET OPTIONS
while getopts ":n:t:" opt; do
    case ${opt} in
        n ) wordamount="$OPTARG";;
        t ) complexity="$OPTARG";;
        \?) ;;#invalad option
        : ) ;;#missing arguments for an option
    esac
done

#MAIN PROGRAM
passwdget
oneline
passwdrnd
#echo $passwdstr
echo $passwdstr
spacing=500;
while [ $spacing -ge `echo $passwdstr | wc -c` ]; do
spacing=$(dd if=/dev/urandom count=1 bs=1 2>/dev/null| od -a -i | head -n 2 | tail -n 1 | awk '{print $1}')
done;
other=`expr $spacing - 2`
fpart=`echo $passwdstr | cut -c -$other`
spart=`echo $passwdstr | cut -c $spacing-`;
echo $fpart$onechar$spart

exit 0

#Use next information for getting a random number between 0.0 - 1.0
#awk -v seed=$RANDOM 'BEGIN{srand(seed);print rand()}'

It will use some random to take a character out of what is pulled from wget and change one of them if a random between 0 and 255 returns higher or lower than 127; then it will put the first part in a varaible, a random character in another variable, and the second part in the third variable and print it.


问:
How do you make sure in angular 2+ that clicking on a button whose route is the same as the current page reloads the page?
The first question that I must answer, why would I complain about that. You are already there, right?

I have two reasons why I need a reload to take place, But, I'll only mention the first.

1) my user clicks on the link, he does not realize the link he chose is the same as the current page. His button clicks and does the wavy animation but nothing is carried out after that. User thinks the link is broken. But If the page were to reload, he would not take this as a flaw.

Is there anyway in angular to tell the router that if you are on /xyx and the user clicks on /xyz link, the app should reload.

答:
Do you mean this one? </p>

```<code>if (url === window.location.href) {
    window.location.reload();
} else {
    this.router.navigate([url]);
}
</code>```

Body:
Do you mean this one?

if (url === window.location.href) {
    window.location.reload();
} else {
    this.router.navigate([url]);
}


问:
External authentication providers and authenticating requests to RESTful API
I'm working on adding google login to my web app. It's a RESTful app, so once a user is logged in, each individual request must be authenticated with a token.

Currently, I create my own tokens using JWT. I can add useful information to the token object to help with state management.

My question is: once I add google as an authentication provider, do I then need send every request to Google to be authenticated, rather than authenticating it on my own server? Do I then lose the ability to customize the content of the token?

With external authentication providers, is it normal to manage separate JWTs for calls to your RESTful API?

答: Normally, you'll have the login action use the third party to identify the user. Your internal code will probably create/store/fetch an app local user profile of some sort, and you'll create your JWT based on that. Further calls to your API bearing a valid token are then trusted to have already been authenticated and therefore need no further calls to the auth provider. </p>


问:
Can you get a custom action by clicking an HTML link in a TextView?
I'd like to have an HTML link in a TextView start an activity in my app.

There are plenty of answers about how to do this, but it seems that most of them end up using a non-standard URI scheme (such as the package name) and catching an ACTION_VIEW for this.

There are also plenty of answers in a slightly different context saying don't do this... there is already a perfectly good intent URI scheme in Android, and you can define custom actions within that scheme.

My problem is that I can't put the two together, in that all that I can convince clicking on an HTML link in a TextView to do is generate an ACTION_VIEW.  Is there any way to get an intent with a custom action here?

EDIT
OK, the TextView is assigned a Spannable that has a URLSpan for each ....  And URLSpan has:

```<code>@Override
public void onClick(View widget) {
    Uri uri = Uri.parse(getURL());
    Context context = widget.getContext();
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
    try {
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Log.w("URLSpan", "Actvity was not found for intent, " + intent.toString());
    }
}
</code>```

So yeah, looks like I'm stuck with a VIEW action.  Thanks everyone.

答: Not possible, would require rewriting too much low-level code.</p>

Body:
I'd like to have an HTML link in a TextView start an activity in my app.

There are plenty of answers about how to do this, but it seems that most of them end up using a non-standard URI scheme (such as the package name) and catching an ACTION_VIEW for this.

There are also plenty of answers in a slightly different context saying don't do this... there is already a perfectly good intent URI scheme in Android, and you can define custom actions within that scheme.

My problem is that I can't put the two together, in that all that I can convince clicking on an HTML link in a TextView to do is generate an ACTION_VIEW.  Is there any way to get an intent with a custom action here?

EDIT
OK, the TextView is assigned a Spannable that has a URLSpan for each ....  And URLSpan has:

@Override
public void onClick(View widget) {
    Uri uri = Uri.parse(getURL());
    Context context = widget.getContext();
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
    try {
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Log.w("URLSpan", "Actvity was not found for intent, " + intent.toString());
    }
}

So yeah, looks like I'm stuck with a VIEW action.  Thanks everyone.