问:
Parsing and formatting JSON array from SQL Datareader JavaScript
I am populating a javascriptarray from a datareaderin c#. The c# code is here:

```<code>public string ConvertDataTabletoString() {
  DataTable dt = new DataTable();
  //
  SqlConnection conn = new SqlConnection();
  SqlCommand cmd = new SqlCommand();
  string connStr = ConfigurationManager.ConnectionStrings["FurnitureDB"].ConnectionString;
  conn.ConnectionString = connStr;
  conn.Open();
  cmd.CommandType = System.Data.CommandType.StoredProcedure;
  cmd.Connection = conn;
  cmd.CommandText = "GetLatLongPins_active";
  SqlDataReader datareader = cmd.ExecuteReader();
  //var dt = new DataTable();
  dt.Load(datareader);

  //con.Open();
  System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter(cmd);
  da.Fill(dt);
  System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
  List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
  Dictionary<string, object> row;

  foreach(DataRow dr in dt.Rows) {
    row = new Dictionary<string, object>();
    foreach(DataColumn col in dt.Columns) {
      row.Add(col.ColumnName, dr[col]);
    }
    rows.Add(row);
  }

  return serializer.Serialize(rows);
}
</code>```

The array that is returned looks like this:

```<code>var markers = JSON.parse('[{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":40.554306,"Longitude":-81.921422,"Active":true},{"Latitude":40.906651,"Longitude":-97.093629,"Active":true},{"Latitude":29.431261,"Longitude":-97.171709,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":40.554306,"Longitude":-81.921422,"Active":true},{"Latitude":40.906651,"Longitude":-97.093629,"Active":true},{"Latitude":29.431261,"Longitude":-97.171709,"Active":true}]');
</code>```

I need to parse it out so that it looks like this for the Google Maps API:

```<code>var waypts = [{
  location: '34.257179, -119.234190',
  stopover: true
}, {
  location: '34.257179, -119.234190',
  stopover: true
}, {
  location: '40.554306, -81.921422',
  stopover: true
}, {
  location: '40.906651, -97.093629',
  stopover: true
}, {
  location: '29.431261, -97.171709',
  stopover: true
}, ]
</code>```

I have tried a number of variations, if I cut it back to only one piece I can create the result I want, for example:

```<code>var obj = JSON.parse('{"Latitude":34.257179,"Longitude":-119.234190,"Active":true}');
document.getElementById("demo").innerHTML = 'Location:' + obj.Latitude + ',' + obj.Longitude + ',' + 'stopover:true';
'
</code>```

This produces the output I need for Google Maps

Location:34.257179,-119.23419,stopover:true

But when I try to do a loop over the data I'm struggling to make it work. One of my attempts looks like this:

```<code>var obj = JSON.parse('{"Latitude":34.257179,"Longitude":-119.234190,"Active":true}', {
  "Latitude": 29.431261,
  "Longitude": -97.171709,
  "Active": true
}]
');

for (i = 0; i < obj.length; i++) {
  x += obj.Latitude[i] + "<br>";
}

document.getElementById("demo").innerHTML = x;
</code>```

I'm testing by sending the output to an output window.  When I run the code above I get nothing, no output.  I've tried to correlate my example to the many available examples, but haven't had success.  Thanks for any recommendations.

Here is a stack snippet based on the request, I hadn't used that before, but I do see my code is generating an error. That should be helpful.  I'll continue to look at that as well.

<!DOCTYPE html>

Create Object from JSON String

```

Body:
I am populating a javascriptarray from a datareaderin c#. The c# code is here:

public string ConvertDataTabletoString() {
  DataTable dt = new DataTable();
  //
  SqlConnection conn = new SqlConnection();
  SqlCommand cmd = new SqlCommand();
  string connStr = ConfigurationManager.ConnectionStrings["FurnitureDB"].ConnectionString;
  conn.ConnectionString = connStr;
  conn.Open();
  cmd.CommandType = System.Data.CommandType.StoredProcedure;
  cmd.Connection = conn;
  cmd.CommandText = "GetLatLongPins_active";
  SqlDataReader datareader = cmd.ExecuteReader();
  //var dt = new DataTable();
  dt.Load(datareader);

  //con.Open();
  System.Data.SqlClient.SqlDataAdapter da = new SqlDataAdapter(cmd);
  da.Fill(dt);
  System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
  List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
  Dictionary<string, object> row;

  foreach(DataRow dr in dt.Rows) {
    row = new Dictionary<string, object>();
    foreach(DataColumn col in dt.Columns) {
      row.Add(col.ColumnName, dr[col]);
    }
    rows.Add(row);
  }

  return serializer.Serialize(rows);
}

The array that is returned looks like this:

var markers = JSON.parse('[{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":40.554306,"Longitude":-81.921422,"Active":true},{"Latitude":40.906651,"Longitude":-97.093629,"Active":true},{"Latitude":29.431261,"Longitude":-97.171709,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":40.554306,"Longitude":-81.921422,"Active":true},{"Latitude":40.906651,"Longitude":-97.093629,"Active":true},{"Latitude":29.431261,"Longitude":-97.171709,"Active":true}]');

I need to parse it out so that it looks like this for the Google Maps API:

var waypts = [{
  location: '34.257179, -119.234190',
  stopover: true
}, {
  location: '34.257179, -119.234190',
  stopover: true
}, {
  location: '40.554306, -81.921422',
  stopover: true
}, {
  location: '40.906651, -97.093629',
  stopover: true
}, {
  location: '29.431261, -97.171709',
  stopover: true
}, ]

I have tried a number of variations, if I cut it back to only one piece I can create the result I want, for example:

var obj = JSON.parse('{"Latitude":34.257179,"Longitude":-119.234190,"Active":true}');
document.getElementById("demo").innerHTML = 'Location:' + obj.Latitude + ',' + obj.Longitude + ',' + 'stopover:true';
'

This produces the output I need for Google Maps

Location:34.257179,-119.23419,stopover:true

But when I try to do a loop over the data I'm struggling to make it work. One of my attempts looks like this:

var obj = JSON.parse('{"Latitude":34.257179,"Longitude":-119.234190,"Active":true}', {
  "Latitude": 29.431261,
  "Longitude": -97.171709,
  "Active": true
}]
');

for (i = 0; i < obj.length; i++) {
  x += obj.Latitude[i] + "
";
}

document.getElementById("demo").innerHTML = x;

I'm testing by sending the output to an output window.  When I run the code above I get nothing, no output.  I've tried to correlate my example to the many available examples, but haven't had success.  Thanks for any recommendations.

Here is a stack snippet based on the request, I hadn't used that before, but I do see my code is generating an error. That should be helpful.  I'll continue to look at that as well.

<!DOCTYPE html>

Create Object from JSON String

Body:
You could use Array#map:

Then, if your input is:

var obj = JSON.parse('[{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":40.554306,"Longitude":-81.921422,"Active":true},{"Latitude":40.906651,"Longitude":-97.093629,"Active":true},{"Latitude":29.431261,"Longitude":-97.171709,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":40.554306,"Longitude":-81.921422,"Active":true},{"Latitude":40.906651,"Longitude":-97.093629,"Active":true},{"Latitude":29.431261,"Longitude":-97.171709,"Active":true}]');

By using:

var waypts = obj.map(function(x) {
  return {
    location: x.Latitude + ", " + x.Longitude,
    stopover: true
  };
});

The result will be:

[
  {
    "location": "34.257179, -119.23419",
    "stopover": true
  },
  {
    "location": "34.257179, -119.23419",
    "stopover": true
  },
  {
    "location": "40.554306, -81.921422",
    "stopover": true
  },
  {
    "location": "40.906651, -97.093629",
    "stopover": true
  },
  {
    "location": "29.431261, -97.171709",
    "stopover": true
  },
  {
    "location": "34.257179, -119.23419",
    "stopover": true
  },
  {
    "location": "34.257179, -119.23419",
    "stopover": true
  },
  {
    "location": "40.554306, -81.921422",
    "stopover": true
  },
  {
    "location": "40.906651, -97.093629",
    "stopover": true
  },
  {
    "location": "29.431261, -97.171709",
    "stopover": true
  }
]

Something like this:

(function() {
  var obj = JSON.parse('[{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":40.554306,"Longitude":-81.921422,"Active":true},{"Latitude":40.906651,"Longitude":-97.093629,"Active":true},{"Latitude":29.431261,"Longitude":-97.171709,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":34.257179,"Longitude":-119.234190,"Active":true},{"Latitude":40.554306,"Longitude":-81.921422,"Active":true},{"Latitude":40.906651,"Longitude":-97.093629,"Active":true},{"Latitude":29.431261,"Longitude":-97.171709,"Active":true}]');

  var waypts = obj.map(function(x) {
    return {
      location: x.Latitude + ", " + x.Longitude,
      stopover: true
    };
  });
  console.log(waypts);
})();

.as-console-wrapper {
  position: absolute;
  top: 0;
}


来源: stackexchange

问:
Resetting plotly event_data upon radio button select in shiny
I have an interactively displayed text in shiny, that captures the click event from a plotly plot. If nothing is clicked, a default text is displayed, once a point is clicked, its corresponding values are displayed.

However, I also have a radio button to select what is pictured in the plot. The problem is, when I change the selected radio button, the interactively displayed text is not correct anymore, since the plot changes and this is not captured, as you can see in the simplified example below.
Therefore, I would like for the event_data to be reset (and hence show the default text) whenever I select a different option in the radio button.

I know there are ways to create a separate 'reset' button (e.g. with shinyjs package, see here), yet I wonder whether it is possible to somehow couple this reset functionality to the radio button.

```<code>library(ggplot2)
library(shiny)
library(shinydashboard)
library(plotly)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(plotlyOutput("first"),
          radioButtons("radbut", "Choose:", c("Sepal" = "sepal","Petal" =
"petal"))
      ),
      box(textOutput("second"))
    )
  )
)

server <- function(input, output, session) {
  output$first <- renderPlotly({
    if (input$radbut == "sepal") {
      gp <- ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) +
        geom_point()
    } else {
      gp <- ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) +
        geom_point()
    }
    ggplotly(gp, source = "select")
  })
  output$second <- renderText({
    clicked <- event_data("plotly_click", source = "select")
    if (is.null(clicked)) {
      text = "Select a value"
    } else {
      text = paste("You clicked:", input$radbut,
                   clicked[[3]],",", clicked[[4]], sep = " ")
    }
    text
  })
}

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

答:
This is a possibile solution (workaround) using reactive values. I think there must me a more elegant soluting but was not able to find it.

Hope this helps!

```<code>    library(ggplot2)
    library(shiny)
    library(shinydashboard)
    library(plotly)

    ui <- dashboardPage(
            dashboardHeader(),
            dashboardSidebar(),
            dashboardBody(
                    fluidRow(
                            box(plotlyOutput("first"),
                                radioButtons("radbut", "Choose:", c("Sepal" = "sepal","Petal" =
                                                                            "petal"))
                            ),
                            box(textOutput("second"))
                    )
            )
    )

    server <- function(input, output, session) {
            defaults <- reactiveValues(part = "Sepal", text = "")
            output$first <- renderPlotly({
                    defaults$text = "Select a value"

                    if (input$radbut == "sepal") {
                            defaults$part = "Sepal"

                            gp <- ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) +
                                    geom_point()
                    } else {
                            defaults$part = "Petal"
                            gp <- ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) +
                                    geom_point()
                    }
                    ggplotly(gp, source = "select")
            })
            clicked <- reactive({
                    event_data("plotly_click", source = "select")
            })
            observeEvent(clicked(), {
                    defaults$text = paste("You clicked:", defaults$part,
                                 clicked()[[3]],",", clicked()[[4]], sep = " ")
            })
            output$second <- renderText({
                    defaults$text
            })
    }

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

ContentLicense: CC BY-SA 3.0

Body:
I have an interactively displayed text in shiny, that captures the click event from a plotly plot. If nothing is clicked, a default text is displayed, once a point is clicked, its corresponding values are displayed.

However, I also have a radio button to select what is pictured in the plot. The problem is, when I change the selected radio button, the interactively displayed text is not correct anymore, since the plot changes and this is not captured, as you can see in the simplified example below.
Therefore, I would like for the event_data to be reset (and hence show the default text) whenever I select a different option in the radio button.

I know there are ways to create a separate 'reset' button (e.g. with shinyjs package, see here), yet I wonder whether it is possible to somehow couple this reset functionality to the radio button.

library(ggplot2)
library(shiny)
library(shinydashboard)
library(plotly)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(plotlyOutput("first"),
          radioButtons("radbut", "Choose:", c("Sepal" = "sepal","Petal" =
"petal"))
      ),
      box(textOutput("second"))
    )
  )
)

server <- function(input, output, session) {
  output$first <- renderPlotly({
    if (input$radbut == "sepal") {
      gp <- ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) +
        geom_point()
    } else {
      gp <- ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) +
        geom_point()
    }
    ggplotly(gp, source = "select")
  })
  output$second <- renderText({
    clicked <- event_data("plotly_click", source = "select")
    if (is.null(clicked)) {
      text = "Select a value"
    } else {
      text = paste("You clicked:", input$radbut,
                   clicked[[3]],",", clicked[[4]], sep = " ")
    }
    text
  })
}

shinyApp(ui, server)

Body:
This is a possibile solution (workaround) using reactive values. I think there must me a more elegant soluting but was not able to find it.

Hope this helps!

    library(ggplot2)
    library(shiny)
    library(shinydashboard)
    library(plotly)

    ui <- dashboardPage(
            dashboardHeader(),
            dashboardSidebar(),
            dashboardBody(
                    fluidRow(
                            box(plotlyOutput("first"),
                                radioButtons("radbut", "Choose:", c("Sepal" = "sepal","Petal" =
                                                                            "petal"))
                            ),
                            box(textOutput("second"))
                    )
            )
    )

    server <- function(input, output, session) {
            defaults <- reactiveValues(part = "Sepal", text = "")
            output$first <- renderPlotly({
                    defaults$text = "Select a value"

                    if (input$radbut == "sepal") {
                            defaults$part = "Sepal"

                            gp <- ggplot(data = iris, aes(x = Sepal.Width, y = Sepal.Length)) +
                                    geom_point()
                    } else {
                            defaults$part = "Petal"
                            gp <- ggplot(data = iris, aes(x = Petal.Width, y = Petal.Length)) +
                                    geom_point()
                    }
                    ggplotly(gp, source = "select")
            })
            clicked <- reactive({
                    event_data("plotly_click", source = "select")
            })
            observeEvent(clicked(), {
                    defaults$text = paste("You clicked:", defaults$part,
                                 clicked()[[3]],",", clicked()[[4]], sep = " ")
            })
            output$second <- renderText({
                    defaults$text
            })
    }

    shinyApp(ui, server)


问:
Is the ReplicaSet name necessary in MongoClientURI Connection String?
I am confused about the use/need of the MongoDB connection string replicaSet option, when specifying a client URI for connection to a MongoDB replica set from a Java application.

I have 3 node instances of MongoDB running comprising the replica set, and each is specified as being a member of the same replica set.  I would like to connect to the replica set from my Java application.  I am confused from the documentation I have read, if it is even necessary to specify the replica set name in the connection string when I give a list of more than 2 hostnames.

Here is how I start my 3 node MongoDB instances.

Server1$: mongod --replSet "rs0"

Server2$: mongod --replSet "rs0"

Server3$: mongod --replSet "rs0"

I assume a negotiation then occurs, and a Primary is elected, and the remaining
are marked as Secondaries.

I would then want to connect to the replica set via the MongoClient call from my Java application. Is the actual replica set name even needed?  And do I need to list each member of the replica set, or does the MongoDB driver only need a single member of the replica set to determine the rest?

MongoClient mongoClient = new MongoClient(
  new MongoClientURI(
    "mongodb://Server1,Server2,Server3/?replicaSet=rs0"
  )
);
```

Do I need the replicaSet option?

答:
If you don't specify the replicaset, it connects in 'standalone' mode, and you lose replicaset features on the application end (no failing over). So if the server you connect to were to failover to another one, your application would not follow and reconnect to the new primary.

From the docs:

When connecting to a replica set it is important to give a seed list
  of at least two mongod instances. If you only provide the connection
  point of a single mongod instance, and omit the replicaSet, the client
  will create a standalone connection.

Body:
I am confused about the use/need of the MongoDB connection string replicaSet option, when specifying a client URI for connection to a MongoDB replica set from a Java application.

I have 3 node instances of MongoDB running comprising the replica set, and each is specified as being a member of the same replica set.  I would like to connect to the replica set from my Java application.  I am confused from the documentation I have read, if it is even necessary to specify the replica set name in the connection string when I give a list of more than 2 hostnames.

Here is how I start my 3 node MongoDB instances.

Server1$: mongod --replSet "rs0"

Server2$: mongod --replSet "rs0"

Server3$: mongod --replSet "rs0"

I assume a negotiation then occurs, and a Primary is elected, and the remaining
are marked as Secondaries.

I would then want to connect to the replica set via the MongoClient call from my Java application. Is the actual replica set name even needed?  And do I need to list each member of the replica set, or does the MongoDB driver only need a single member of the replica set to determine the rest?

MongoClient mongoClient = new MongoClient(
  new MongoClientURI(
    "mongodb://Server1,Server2,Server3/?replicaSet=rs0"
  )
);

Do I need the replicaSet option?


问:
Testing a function from a module with Jasmine
I have a module "test.js" which looks like this;

```<code>export default function main(){
   sub_main();
}

export function sub_main(){
 //Do something
}
</code>```

I would like to test the method sub_main in Jasmine. I have tried to import sub_main() function to test in Jasmine using import statement but Jasmine complies "Unexpected token import" then I used the require statement. It now complies about export keyword in test.js module.

答:
This should help get you on the right path. You may want to look up some info on CommonJS modules as it looks like that is what you need to be using.

```<code>module.exports = {
    main: function() {
        this.sub_main();
    },

    sub_main: function() {
        return 'It Works!';
    }
}
</code>```

And a working test example:

```<code>it('should work', function() {
  const sub_main = require('./path/to/myModule').sub_main;
  const itWorks = sub_main();

  expect(itWorks).toEqual('It Works!');
});
</code>```

Body:
I have a module "test.js" which looks like this;

export default function main(){
   sub_main();
}

export function sub_main(){
 //Do something
}

I would like to test the method sub_main in Jasmine. I have tried to import sub_main() function to test in Jasmine using import statement but Jasmine complies "Unexpected token import" then I used the require statement. It now complies about export keyword in test.js module.

Body:
This should help get you on the right path. You may want to look up some info on CommonJS modules as it looks like that is what you need to be using.

module.exports = {
    main: function() {
        this.sub_main();
    },

    sub_main: function() {
        return 'It Works!';
    }
}

And a working test example:

it('should work', function() {
  const sub_main = require('./path/to/myModule').sub_main;
  const itWorks = sub_main();

  expect(itWorks).toEqual('It Works!');
});


问:
Faster way to read RSS through Javascript/PHP
Got another fun one for you all today.

I have working code that pulls from various RSS feeds and orders them by which of them has most recent pubdate.

The issues I have is that it is slow. It slows down the loading of the site. Not only that, because it's all hosted server side, it slows down the response if multiple people are accessing the site simultaneously.

So, I'd like to convert this into either a JavaScript function, which would then fill the  tag's innerHTML to what's pulled back from the database or another option that I would love for anyone to suggest (If it's faster).

Without further adieu: The Code:

PHP

```<code>function RSSFeeder() {
    $client = buildCon();
    //Query removed, simply gets the RSS URL from the database
    $query = "";
    $result = $client ->run($query);
    $RSSList = array();
    foreach($result ->getRecords() as $record)
    {
        $ComicArray = array();
        $ComicName = $record ->value('Name');
        $RSS = $record ->value('RSS');
        $URL = $record ->value('URL');
        $content = file_get_contents($RSS);
        $x = new SimpleXmlElement($content);
        for ($i = 0; $i < 1; $i++) {
            $profile = $x ->channel ->item[$i];
            $pubDate = $profile ->{ "pubDate"};
        }
        $ComicArray['URL'] = $URL;
        $ComicArray['Comic'] = $ComicName;
        $ComicArray['pubDate'] = $pubDate;
        $RSSList[] = $ComicArray;
    }

    #usort($RSSList, "sortFunction");
    usort($RSSList, "compareRSSTimes");

    return $RSSList;
}
</code>```

At the end, you probably saw the usort method, so here it is:

```<code>function compareRSSTimes($a, $b) {
    $a = strtotime($a['pubDate']);
    $b = strtotime($b['pubDate']);

    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
}
</code>```

From there, the array is sent back to a PHP script that builds the output based on the chronological order of updates.  It works fine. It just takes a little while to load the page and I'm worried about the sustainability of my terribad server if/when more users access the page.

Suggestions?

答:
You could probably get away with doing this every so often, instead of every single time. If not able to use a database, using an oldschool method of just wrapping the 'heavy bits' in a cache file storage can work very quickly.

An example of that:

```<code>function RSSFeeder() {
    $cachefile = '/path/to/RSSList.json';// <- must be local server path, not a URL
    if (filemtime($cachefile) < strtotime('now -1 minute')) {
        // if stale, rebuild it

        // .. do your normal building of the $RSSList here ..

        file_put_contents($cachefile,json_encode($RSSList));
        return $RSSList;
    } else {
        // else output cache
        return json_decode(file_get_contents($cachefile),true);
    }
}
</code>```

It could be more elegant... or use a bloated over the top fully featured library to do the same thing.

But this works, is self mending, only updates when called for, doesn't require a cron job, and is a weee bit faster than opening a db connection, querying the db, and outputting the data stored... but not huge enough. So your preference is more important there.

Body:
Got another fun one for you all today.

I have working code that pulls from various RSS feeds and orders them by which of them has most recent pubdate.

The issues I have is that it is slow. It slows down the loading of the site. Not only that, because it's all hosted server side, it slows down the response if multiple people are accessing the site simultaneously.

So, I'd like to convert this into either a JavaScript function, which would then fill the  tag's innerHTML to what's pulled back from the database or another option that I would love for anyone to suggest (If it's faster).

Without further adieu: The Code:

PHP

function RSSFeeder() {
    $client = buildCon();
    //Query removed, simply gets the RSS URL from the database
    $query = "";
    $result = $client ->run($query);
    $RSSList = array();
    foreach($result ->getRecords() as $record)
    {
        $ComicArray = array();
        $ComicName = $record ->value('Name');
        $RSS = $record ->value('RSS');
        $URL = $record ->value('URL');
        $content = file_get_contents($RSS);
        $x = new SimpleXmlElement($content);
        for ($i = 0; $i < 1; $i++) {
            $profile = $x ->channel ->item[$i];
            $pubDate = $profile ->{ "pubDate"};
        }
        $ComicArray['URL'] = $URL;
        $ComicArray['Comic'] = $ComicName;
        $ComicArray['pubDate'] = $pubDate;
        $RSSList[] = $ComicArray;
    }

    #usort($RSSList, "sortFunction");
    usort($RSSList, "compareRSSTimes");

    return $RSSList;
}

At the end, you probably saw the usort method, so here it is:

function compareRSSTimes($a, $b) {
    $a = strtotime($a['pubDate']);
    $b = strtotime($b['pubDate']);

    if ($a == $b) {
        return 0;
    }
    return ($a > $b) ? -1 : 1;
}

From there, the array is sent back to a PHP script that builds the output based on the chronological order of updates.  It works fine. It just takes a little while to load the page and I'm worried about the sustainability of my terribad server if/when more users access the page.

Suggestions?

Body:
You could probably get away with doing this every so often, instead of every single time. If not able to use a database, using an oldschool method of just wrapping the 'heavy bits' in a cache file storage can work very quickly.

An example of that:

function RSSFeeder() {
    $cachefile = '/path/to/RSSList.json';// <- must be local server path, not a URL
    if (filemtime($cachefile) < strtotime('now -1 minute')) {
        // if stale, rebuild it

        // .. do your normal building of the $RSSList here ..

        file_put_contents($cachefile,json_encode($RSSList));
        return $RSSList;
    } else {
        // else output cache
        return json_decode(file_get_contents($cachefile),true);
    }
}

It could be more elegant... or use a bloated over the top fully featured library to do the same thing.

But this works, is self mending, only updates when called for, doesn't require a cron job, and is a weee bit faster than opening a db connection, querying the db, and outputting the data stored... but not huge enough. So your preference is more important there.


问:
changing select's parent li elements class
I have selects in list items. onchange of select, if selected options value is empty, I would like to give the parent li element a "isnotselected" class, else if selected option's value is not empty, I would like to give the parent li element a "isselected" class. How can I do this via jQuery?</p>

```<code><ul>
  <li>
    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>
  </li>
  <li>
    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>
  </li>
  <li>
    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>
  </li>
  <li>
    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>
  </li>
</ul>
</code>```

答:
Very simple:</p>

```<code>var classes = ['isnotselected', 'isselected'];
$('ul li select').change(function() {
    $(this).closest('li')
           .removeClass(classes.join(' '))
           .addClass(classes[Number(this.value.length > 0)]);
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have selects in list items. onchange of select, if selected options value is empty, I would like to give the parent li element a "isnotselected" class, else if selected option's value is not empty, I would like to give the parent li element a "isselected" class. How can I do this via jQuery?

    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>

    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>

    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>

    <select>
      <option value="">Select Value</option>
      <option value="1">Value 1</option>
      <option value="2">Value 2</option>
    </select>

Body:
Very simple:

var classes = ['isnotselected', 'isselected'];
$('ul li select').change(function() {
    $(this).closest('li')
           .removeClass(classes.join(' '))
           .addClass(classes[Number(this.value.length > 0)]);
});


问:
How is reactive programming different than event-driven programming?
I am learning reactive programming and functional reactive programming in JavaScript. I am very confused.

Wikipedia says that there are various ways to write reactive code such as imperative, OORP and functional. I want to know if event-driven is just an another way to write reactive code?

How is reactive programming related to Promises? I think promises is an alternative to event-driven and callback hell.

答: Reactive programming is all about streams, it could be streams of events, or anything else. It is on emitting/announcing these streams or subscribing/watching these streams or stream transformations that lead to some events. So both programming paradigms are related. </p>


问:
How to undo a merge on Bitbucket?
I've created a merge (into the 'master' branch) that's now on a Bitbucket repo. Long story short: I need to undo that merge.

I know that you can do this at the Github site itself, but Bitbucket doesn't have that feature. I'm not clear on how to do this with Git without causing a mess.

答:
A "Revert pull request" feature was implemented in Bitbucket in 2017.

To revert a pull request:

From the pull request, click the Revert button in the top right.
(Optional) From the Revert pull request dialog, change the Branch name for the new branch you're about to create.

Click the Revert button.
Once you click Revert, Bitbucket creates the new branch. Even if you cancel the pull request, the revert branch remains in the repository.

The Create a pull request page opens with the revert branch as the source. After you add your reviewers and make additional changes, click Create.

Source: the docs.

Title: How to undo a merge on Bitbucket?

ContentLicense: CC BY-SA 4.0


问:
How to get DATETIME and store to time_t using MySQL Connector/C++?
I'm using MySQL Connector/C++ as library to get result from MySQL database. I'm using C++11 standard. I want to get a DATETIME field (named jointime) from database and store it as time_t variable in follow:

```<code>#include <cstdlib>
#include <iostream>
#include <ctime>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
    auto driver = sql::mysql::get_mysql_driver_instance();
    auto con = driver->connect("tcp://127.0.0.1:3306", "user", "password");
    con->setSchema("mydb");
    auto stmt = con->createStatement();

    auto res = stmt->executeQuery("SELECT * from users;");
    while (res->next()) {
        string username = res->getString("username");
        time_t jt ; // res->get???
        ...
    }
    delete res;
    delete stmt;
    delete con;
}
</code>```

How should I get jointime and assign it to time_t jt?

There isn't getDateTime() or relative method.

答:
Try something like this:</p>

```<code>Time var = new Time();
jt = var.time();
</code>```

Body:
I'm using MySQL Connector/C++ as library to get result from MySQL database. I'm using C++11 standard. I want to get a DATETIME field (named jointime) from database and store it as time_t variable in follow:

#include <cstdlib>
#include <iostream>
#include <ctime>
#include "mysql_connection.h"
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
int main(void)
{
    auto driver = sql::mysql::get_mysql_driver_instance();
    auto con = driver->connect("tcp://127.0.0.1:3306", "user", "password");
    con->setSchema("mydb");
    auto stmt = con->createStatement();

    auto res = stmt->executeQuery("SELECT * from users;");
    while (res->next()) {
        string username = res->getString("username");
        time_t jt ; // res->get???
        ...
    }
    delete res;
    delete stmt;
    delete con;
}

How should I get jointime and assign it to time_t jt?

There isn't getDateTime() or relative method.

Body:
Try something like this:

Time var = new Time();
jt = var.time();


问:
Render Vue.js @click directive outside of html tag
I have a link set up like so:

```<code><a href="#" @click="modal=true">Open modal</a>
</code>```

And here's the data:

```<code>export default {
    data () {
        return {
            modal: false
        }
    }
}
</code>```

Is there a workaround to trigger the click event, without actually having to place the @click directly in the tag? The expected result would be the same however the @click would be defined elsewhere in the vue instance.

答:
You could try this:</p>

```<code>export default {
  data () {
    return {
      modal: false
    }
  },
  mounted () {
    var self = this;
    this.$el.querySelector('a').addEventListener('click', function () {
        Vue.set(self, 'modal', true);
    });
  }
}
</code>```

Body:
I have a link set up like so:

Open modal

And here's the data:

export default {
    data () {
        return {
            modal: false
        }
    }
}

Is there a workaround to trigger the click event, without actually having to place the @click directly in the tag? The expected result would be the same however the @click would be defined elsewhere in the vue instance.

Body:
You could try this:

export default {
  data () {
    return {
      modal: false
    }
  },
  mounted () {
    var self = this;
    this.$el.querySelector('a').addEventListener('click', function () {
        Vue.set(self, 'modal', true);
    });
  }
}


问:
What does getContext.getCollection() return in CosmosDB stored procedure?
I have written a simple stored procedure to query a collection and return response but when I execute it as node.js script I get 400 error code and following error message:

"PartitionKey extracted from document doesn't match the one specified in the header"

When getContext().getCollection.getSelfLink() value is printed I get dbs/3Mk0AA==/colls/3Mk0AOWMbw0=/ but my database and collection Ids are some other values.

Any kind of help will be much appreciated.

答:
Yes, Thanks for the help guys!!

Incase anyone else tries, adding partition key while executing the stored procedure worked for me. The code is,

```<code>client.executeStoredProcedure('/dbs/<database-id>/colls/<collection-id>/sprocs/<storedproc-id>', <input to the procedure(if any)>, { partitionKey: <partition-field-id> }, callback);
</code>```

Body:
Yes, Thanks for the help guys!!

Incase anyone else tries, adding partition key while executing the stored procedure worked for me. The code is,

client.executeStoredProcedure('/dbs/<database-id>/colls/<collection-id>/sprocs/<storedproc-id>', <input to the procedure(if any)>, { partitionKey: <partition-field-id> }, callback);


问:
When building apk in Android Studio, APK size increased by big margin i.e. from 3 mb to 20mb

APK size increased after building, apk size increased from 3 mb to 20mb.
its due to lib as seen in circle.
How to remove these lib files??

https://i.stack.imgur.com/6ZCp5.png

```<code>apply plugin: 'com.android.application'

    android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "csdevbin.dua"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 6
        versionName "4.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            debuggable true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
</code>```

My dependencies

```<code>implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'com.google.android.gms:play-services-ads:11.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
testCompile 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-core:11.0.2'
implementation 'com.startapp:inapp-sdk:3.6.7'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.1'
implementation 'com.android.support:cardview-v7:27.0.2'
</code>```

答: If your code uses these libraries then there is no way to remove them. But you can use ProGuard to reduce the size of your app. Can you post your build.gardle file?

Body:
APK size increased after building, apk size increased from 3 mb to 20mb.
its due to lib as seen in circle.
How to remove these lib files??

https://i.stack.imgur.com/6ZCp5.png

apply plugin: 'com.android.application'

    android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "csdevbin.dua"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 6
        versionName "4.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }

        debug {
            debuggable true
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

My dependencies

implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'com.google.android.gms:play-services-ads:11.0.2'
implementation 'com.android.support.constraint:constraint-layout:1.0.0-beta4'
testCompile 'junit:junit:4.12'
implementation 'com.google.firebase:firebase-core:11.0.2'
implementation 'com.startapp:inapp-sdk:3.6.7'
implementation 'com.github.barteksc:android-pdf-viewer:2.8.1'
implementation 'com.android.support:cardview-v7:27.0.2'


答:
A Don't Repeat Yourself solution:

```<code>var classes = {
    'true': 'isselected',
    'false': 'isnotselected'
};

$('select').change(function () {
     var sel = !!$(this).val(); // convert value into true/false
     $(this).closest('li').addClass(classes[sel]).removeClass(classes[!sel]);
});
</code>```

Demo: http://jsfiddle.net/B5Q7m/

Alternatively but in the same style, you can rely on the fact that false converts to 0 and 'true' converts to 1, although the classes declaration isn't as descriptive:

```<code>var classes = ['isnotselected', 'isselected'];

$('select').change(function () {
    var sel = !!$(this).val();
    $(this).closest('li').addClass(classes[+sel]).removeClass(classes[+(!sel)]);
});
</code>```

Note: .parent() can be used in place of .closest('li'), but .closest is usually the safer option in case you decide to wrap the <select>s in another element later on.

Title: changing select's parent li elements class

Body:
A Don't Repeat Yourself solution:

var classes = {
    'true': 'isselected',
    'false': 'isnotselected'
};

$('select').change(function () {
     var sel = !!$(this).val(); // convert value into true/false
     $(this).closest('li').addClass(classes[sel]).removeClass(classes[!sel]);
});

Demo: http://jsfiddle.net/B5Q7m/

Alternatively but in the same style, you can rely on the fact that false converts to 0 and 'true' converts to 1, although the classes declaration isn't as descriptive:

var classes = ['isnotselected', 'isselected'];

$('select').change(function () {
    var sel = !!$(this).val();
    $(this).closest('li').addClass(classes[+sel]).removeClass(classes[+(!sel)]);
});

Note: .parent() can be used in place of .closest('li'), but .closest is usually the safer option in case you decide to wrap the <select>s in another element later on.


问:
Importing multiple (21) tabs from excel into R: Why do I keep getting this error message "Error: unexpected '}' in " }"?
I've been trying to import data from separate sheets into R so that I can use them to calculate David's Scores for individuals.

However, for some reason, I keep getting this error message:

”Error: unexpected '}' in "  }"

which, after looking online, baffles me!

Also, it gives an X next to the row number saying there is an unmatched opening bracket '(', but I cannot find any unmatched open brackets anywhere?

Below is my code:

```<code>read_excel_allsheets <- function("C:/Users/James/Desktop/Animal Behaviour Project/Interaction Data/Dominance Only Interaction Data Final.xlsx" ) {
  Sheets <- readxl::excel_sheets("C:/Users/James/Desktop/Animal Behaviour Project/Interaction Data/Dominance Only Interaction Data Final.xlsx")
  Groups <- lapply(Sheets, function(X) readxl::read_excel("C:/Users/James/Desktop/Animal Behaviour Project/Interaction Data/Dominance Only Interaction Data Final.xlsx", sheet = X))
  names(Groups) <- Sheets
}
</code>```

答:
The problem is you're trying to use a string as a parameter in the function.  I would suggest something like this instead:</p>

```<code>read_excel_allsheets <- function(file_name = "C:/Users/James/Desktop/Animal Behaviour Project/Interaction Data/Dominance Only Interaction Data Final.xlsx" ) {
  Sheets <- readxl::excel_sheets(file_name)
  Groups <-    lapply(Sheets, function(X) readxl::read_excel(file_name, sheet = X))
  names(Groups) <- Sheets
}
</code>```

Body:
I've been trying to import data from separate sheets into R so that I can use them to calculate David's Scores for individuals.

However, for some reason, I keep getting this error message:

”Error: unexpected '}' in "  }"

which, after looking online, baffles me!

Also, it gives an X next to the row number saying there is an unmatched opening bracket '(', but I cannot find any unmatched open brackets anywhere?

Below is my code:

read_excel_allsheets <- function("C:/Users/James/Desktop/Animal Behaviour Project/Interaction Data/Dominance Only Interaction Data Final.xlsx" ) {
  Sheets <- readxl::excel_sheets("C:/Users/James/Desktop/Animal Behaviour Project/Interaction Data/Dominance Only Interaction Data Final.xlsx")
  Groups <- lapply(Sheets, function(X) readxl::read_excel("C:/Users/James/Desktop/Animal Behaviour Project/Interaction Data/Dominance Only Interaction Data Final.xlsx", sheet = X))
  names(Groups) <- Sheets
}

Body:
The problem is you're trying to use a string as a parameter in the function.  I would suggest something like this instead:

read_excel_allsheets <- function(file_name = "C:/Users/James/Desktop/Animal Behaviour Project/Interaction Data/Dominance Only Interaction Data Final.xlsx" ) {
  Sheets <- readxl::excel_sheets(file_name)
  Groups <-    lapply(Sheets, function(X) readxl::read_excel(file_name, sheet = X))
  names(Groups) <- Sheets
}


问:
fanning records with left joins
I'm experiencing duplicates/fanning out of left joins.

Table Sales has a number of brands, but only two of the same brand names with different pricings: BRAND 2.

Table CSR Product also has two BRAND 2 brands, but for different states.

Table Product State Package doesn't have two BRAND 2.

I'm joining these three on brand field, yet I'm seeing for each BRAND 2 I add to a table, it multiplies the size. How can I fix this?

I need all Sales records, hence why I'm left joining on Sales. This is a smaller example of a larger problem I'm facing where the first left join was 3020 records, the second left join was 450,000 records.

My question is: If I'm LEFT JOINing to get all sales records, why does adding duplicate BRAND 2 to the other two joined tables multiply the sales records?

Sales:

```<code>brand   | pricing
----------------
BRAND 1    1
BRAND 2    2  <--- Brand 2
BRAND 2    7  <--- Brand 2
BRAND 3    3
BRAND 4    4
BRAND 5    5
BRAND 6    6
</code>```

Product State Package:

```<code>brand   | state
----------------
BRAND 5    WA
BRAND 4    AZ
BRAND 2    MO
BRAND 1    VT
BRAND 8    SD
</code>```

CSR Product:

```<code>brand   | state
----------------
BRAND 2    CT <--- Brand 2
BRAND 3    MA
BRAND 2    CA <--- Brand 2
BRAND 4    GA
BRAND 5    LA
BRAND 9    WA
</code>```

Query:

```<code>SELECT s.brand,
       tcp.brand as csr_brand,
       tpsp.brand as psp_brand
FROM   test_sales s
       LEFT JOIN test_csr_product tcp
              ON ( s.brand = tcp.brand )
       LEFT JOIN test_product_state_package tpsp
              ON ( s.brand = tpsp.brand );
</code>```

Output:

```<code> -- Need all sales records
 sales_brand | csr_brand | psp_brand
-------------+-----------+-----------
 BRAND 1     |           | BRAND 1
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 3     | BRAND 3   |
 BRAND 4     | BRAND 4   | BRAND 4
 BRAND 5     | BRAND 5   | BRAND 5
 BRAND 6     |           |
(9 rows)
</code>```

With three BRAND 2 in Sales: you can see there are duplicates for sale_price across the sales:

```<code>sales_brand | sale_price | csr_brand | psp_brand
-------------+------------+-----------+-----------
 BRAND 1     |          1 |           | BRAND 1
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 3     |          3 | BRAND 3   |
 BRAND 4     |          4 | BRAND 4   | BRAND 4
 BRAND 5     |          5 | BRAND 5   | BRAND 5
 BRAND 6     |          6 |           |
 (11 rows)
</code>```

答: Not Sure if I have understood yor problem exactly but if you consider tpsp.state, tcp.state in the result, the result rows are not really duplicated.</p>

Title: fanning records with left joins

Body:
I'm experiencing duplicates/fanning out of left joins.

Table Sales has a number of brands, but only two of the same brand names with different pricings: BRAND 2.

Table CSR Product also has two BRAND 2 brands, but for different states.

Table Product State Package doesn't have two BRAND 2.

I'm joining these three on brand field, yet I'm seeing for each BRAND 2 I add to a table, it multiplies the size. How can I fix this?

I need all Sales records, hence why I'm left joining on Sales. This is a smaller example of a larger problem I'm facing where the first left join was 3020 records, the second left join was 450,000 records.

My question is: If I'm LEFT JOINing to get all sales records, why does adding duplicate BRAND 2 to the other two joined tables multiply the sales records?

Sales:

brand   | pricing
----------------
BRAND 1    1
BRAND 2    2  <--- Brand 2
BRAND 2    7  <--- Brand 2
BRAND 3    3
BRAND 4    4
BRAND 5    5
BRAND 6    6

Product State Package:

brand   | state
----------------
BRAND 5    WA
BRAND 4    AZ
BRAND 2    MO
BRAND 1    VT
BRAND 8    SD

CSR Product:

brand   | state
----------------
BRAND 2    CT <--- Brand 2
BRAND 3    MA
BRAND 2    CA <--- Brand 2
BRAND 4    GA
BRAND 5    LA
BRAND 9    WA

Query:

SELECT s.brand,
       tcp.brand as csr_brand,
       tpsp.brand as psp_brand
FROM   test_sales s
       LEFT JOIN test_csr_product tcp
              ON ( s.brand = tcp.brand )
       LEFT JOIN test_product_state_package tpsp
              ON ( s.brand = tpsp.brand );

Output:

 -- Need all sales records
 sales_brand | csr_brand | psp_brand
-------------+-----------+-----------
 BRAND 1     |           | BRAND 1
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 2     | BRAND 2   | BRAND 2
 BRAND 3     | BRAND 3   |
 BRAND 4     | BRAND 4   | BRAND 4
 BRAND 5     | BRAND 5   | BRAND 5
 BRAND 6     |           |
(9 rows)

With three BRAND 2 in Sales: you can see there are duplicates for sale_price across the sales:

sales_brand | sale_price | csr_brand | psp_brand
-------------+------------+-----------+-----------
 BRAND 1     |          1 |           | BRAND 1
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          2 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |          7 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 2     |         10 | BRAND 2   | BRAND 2
 BRAND 3     |          3 | BRAND 3   |
 BRAND 4     |          4 | BRAND 4   | BRAND 4
 BRAND 5     |          5 | BRAND 5   | BRAND 5
 BRAND 6     |          6 |           |
 (11 rows)


问:
Catching command-line errors using %x
Whenever you want to execute something on the command line, you can use the following syntax:

```<code>%x(command to run)
</code>```

However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:

```<code>result = %x(command to run)
</code>```

and using a try-catch

```<code>begin
  %x(command to run)
rescue
  "didn't work"
end
</code>```

to no avail. How can I capture the results instead of having them printed out?

答:
Here's how to use Ruby's open3:

```<code>require 'open3'
include Open3

stdin, stdout, stderr = popen3('date')
stdin.close

puts
puts "Reading STDOUT"
print stdout.read
stdout.close

puts
puts "Reading STDERR"
print stderr.read
stderr.close
# >>
# >> Reading STDOUT
# >> Sat Jan 22 20:03:13 MST 2011
# >>
# >> Reading STDERR
</code>```

popen3 returns IO streams for STDIN, STDOUT and STDERR, allowing you to do I/O to the opened app.

Many command-line apps require their STDIN to be closed before they'll process their input.

You have to read from the returned STDOUT and STDERR pipes. They don't automatically shove content into a mystical variable.

In general, I like using a block with popen3 because it handles cleaning up behind itself.

Look through the examples in the Open3 doc. There's lots of nice functionality.

Title: Catching command-line errors using %x

Body:
Whenever you want to execute something on the command line, you can use the following syntax:

%x(command to run)

However, I want to catch an error or at least get the response so I can parse it correctly. I tried setting:

result = %x(command to run)

and using a try-catch

begin
  %x(command to run)
rescue
  "didn't work"
end

to no avail. How can I capture the results instead of having them printed out?

Body:
Here's how to use Ruby's open3:

require 'open3'
include Open3

stdin, stdout, stderr = popen3('date')
stdin.close

puts
puts "Reading STDOUT"
print stdout.read
stdout.close

puts
puts "Reading STDERR"
print stderr.read
stderr.close
# >>
# >> Reading STDOUT
# >> Sat Jan 22 20:03:13 MST 2011
# >>
# >> Reading STDERR

popen3 returns IO streams for STDIN, STDOUT and STDERR, allowing you to do I/O to the opened app.

Many command-line apps require their STDIN to be closed before they'll process their input.

You have to read from the returned STDOUT and STDERR pipes. They don't automatically shove content into a mystical variable.

In general, I like using a block with popen3 because it handles cleaning up behind itself.

Look through the examples in the Open3 doc. There's lots of nice functionality.


问:
TSQL How to select SQL records with following where condition
I have a table Test with records

```<code>ID             Date
1            12/08/2017
1            11/10/2016
1            06/09/2010
1            06/29/2009
2            05/29/2009
2            03/29/2009
2            02/29/2009
</code>```

I want to select id's where Date >2010 but I want to include all record dates
I tried this

```<code>select * from Test
where Date >='01/01/2010'
</code>```

but this return only 3 records of id 1. If only all dates of id are less than 2010 then my select query should not select that ID. if the id has one or more dates >2010 then include in select. Do I need to put in a sub query?

答:
```<code>SELECT *
FROM Test t
WHERE EXISTS ( SELECT 1
               FROM Test
               WHERE ID = t.ID
               AND Date >= '01/01/2010'
             )
</code>```

Body:
I have a table Test with records

ID             Date
1            12/08/2017
1            11/10/2016
1            06/09/2010
1            06/29/2009
2            05/29/2009
2            03/29/2009
2            02/29/2009

I want to select id's where Date >2010 but I want to include all record dates
I tried this

select * from Test
where Date >='01/01/2010'

but this return only 3 records of id 1. If only all dates of id are less than 2010 then my select query should not select that ID. if the id has one or more dates >2010 then include in select. Do I need to put in a sub query?


问:
Removing space from string crashes when checking two string for anagrams to each other
Double free or corruption is thrown when checking two string for anagrams to each  other.

My approach for checking anagrams is:

step 1: Remove all the space from Both input string.

step 2: Sort both the string.

step 3: Return false if length differ.

step 4 : Return true if all char matches.

Note

when user input with space it crash.

ex input 1 : hello world

input 2 : hello world

```<code>output : *** Error in `./a.out': double free or corruption (out): 0x00000000023ca0b0 ***
Aborted (core dumped)
</code>```

For sinlge word its work fine

```<code>#include<iostream>
#include<set>
#include<string>
#include <algorithm>

bool anagrams(std::string usr1,std::string usr2)
{
        if(usr1.length()==usr2.length())
        {

                for(std::string::size_type pos = 0 ; pos<= usr1.length()-1 ; ++pos)
                {
                        if(pos==usr1.size()-1)
                        {
                                if(usr1[pos]==usr2[pos])
                                return true;
                        }

                        if(usr1[pos]==usr2[pos])
                        {
                                continue ;
                        }
                }

        }
        return false;
}

int main()
{
        std::string userInput1;
        std::string userInput2;

        std::getline(std::cin,userInput1);
        std::getline(std::cin,userInput2);

        std::string::iterator end_pos1 = std::remove(userInput1.begin(),userInput1.end(),' ');
        userInput2.erase(end_pos1,userInput1.end());

        std::string::iterator end_pos2 = std::remove(userInput2.begin(),userInput2.end(),' ');
        userInput2.erase(end_pos2,userInput2.end());

        std::sort(userInput1.begin(),userInput1.end());
        std::sort(userInput2.begin(),userInput2.end());

        if(userInput1.empty() || userInput2.empty())
                return 0;
        if(anagrams(userInput1,userInput2))
                std::cout<<"String is anagrams"<<"\n";
        else
                std::cout<<"String  not  anagrams"<<"\n";

        return 0;
}
</code>```

答: You're erasing userInput2 twice. Change the line after your first call to remove, so that it erases userInput1 instead.

Body:
Double free or corruption is thrown when checking two string for anagrams to each  other.

My approach for checking anagrams is:

step 1: Remove all the space from Both input string.

step 2: Sort both the string.

step 3: Return false if length differ.

step 4 : Return true if all char matches.

Note

when user input with space it crash.

ex input 1 : hello world

input 2 : hello world

output : *** Error in `./a.out': double free or corruption (out): 0x00000000023ca0b0 ***
Aborted (core dumped)

For sinlge word its work fine

#include<iostream>
#include<set>
#include<string>
#include <algorithm>

bool anagrams(std::string usr1,std::string usr2)
{
        if(usr1.length()==usr2.length())
        {

                for(std::string::size_type pos = 0 ; pos<= usr1.length()-1 ; ++pos)
                {
                        if(pos==usr1.size()-1)
                        {
                                if(usr1[pos]==usr2[pos])
                                return true;
                        }

                        if(usr1[pos]==usr2[pos])
                        {
                                continue ;
                        }
                }

        }
        return false;
}

int main()
{
        std::string userInput1;
        std::string userInput2;

        std::getline(std::cin,userInput1);
        std::getline(std::cin,userInput2);

        std::string::iterator end_pos1 = std::remove(userInput1.begin(),userInput1.end(),' ');
        userInput2.erase(end_pos1,userInput1.end());

        std::string::iterator end_pos2 = std::remove(userInput2.begin(),userInput2.end(),' ');
        userInput2.erase(end_pos2,userInput2.end());

        std::sort(userInput1.begin(),userInput1.end());
        std::sort(userInput2.begin(),userInput2.end());

        if(userInput1.empty() || userInput2.empty())
                return 0;
        if(anagrams(userInput1,userInput2))
                std::cout<<"String is anagrams"<<"\n";
        else
                std::cout<<"String  not  anagrams"<<"\n";

        return 0;
}


问:
Cronjob in react JS
There is no solution for React to support cron jobs. Could you please share your solutions/alternatives for scheduling events in React?

One solution might be to find a time difference between now and scheduled time and setTimeout for that difference.

Any other ideas?

答:
setTimeout() or setInterval() would be the way to accomplish this in React. For instance, you could use setInterval() to call a function that checks if the current time is equal to a cron job's scheduled time every second or so.

However, this sounds like a job better suited for a process running on a server that can then update react when it needs to.

Title: Cronjob in react JS


答:
I assume you also want to remove the opposite class if it is present.  You need to check the .val() of the event target on the change event like so:

```<code>$('select').bind('change',function(e){
    $et = $(e.target);
    if ($et.val() === "") {
        $et.parent().removeClass('isselected')
                    .addClass('isnotselected');
    } else {
        $et.parent().removeClass('isnotselected')
                    .addClass('isselected');
    }
});
</code>```

I have created a demo here (link).

Body:
I assume you also want to remove the opposite class if it is present.  You need to check the .val() of the event target on the change event like so:

$('select').bind('change',function(e){
    $et = $(e.target);
    if ($et.val() === "") {
        $et.parent().removeClass('isselected')
                    .addClass('isnotselected');
    } else {
        $et.parent().removeClass('isnotselected')
                    .addClass('isselected');
    }
});

I have created a demo here (link).


问:
IsInArray function error: Type Mismatch VBA
When I run this, it gives me an error saying

ByRef argument type mismatch

in the if statement.

I had all of the arrays declared as variants, but that also gave me an error when I tried to run the function.

Any help would be greatly appreciated.

```<code>sub sort()

Dim rowNo As Integer
Dim colNo As Integer
Dim PIList(6) As Long
Dim GSList(2) As Long
Dim FilterList(91) As Long
Dim currCellCont As Long

rowNo = 2
colNo = 2
PIList(6) = Array(0,1,2,3,4,5)
GSList(2) = Array(6,7)
FilterList(91) = Array(89752, 89753, 89754, 89755, 89756, 89757, 89758, 89759, 89760, 89761, 89762, 89763, 89764, 89765, 89766, 89767, 89768, 89769, 89770, 89771, 89772, 89773, 89774, 89775, 89776, 89777, 89778, 89779, 89780, 89781, 89782, 89783, 89784, 89785, 89786, 89787, 89788, 89789, 89790, 89791, 89792, 89793, 89794, 89795, 89796, 89797, 89798, 89799, 89800, 89801, 89802, 89803, 89804, 89805, 89806, 89807, 89808, 89809, 89810, 89811, 89812, 89813, 89814, 89815, 89816, 89817, 89818, 89819, 89820, 89821, 89822, 89823, 89824, 89825, 89826, 89827, 89828, 89829, 89830, 89831, 89832, 89833, 89834, 89835, 89836, 89837, 89838, 89839, 89840, 89841, 89842)
currCellCont = Cells(rowNo, colNo).Value

Do Until IsEmpty(currCellCont)
    If IsInArray(currCellCont, PIList) Then
        Cells(rowNo, 9).Value = "PI"
    ElseIf IsInArray(currCellCont, GSList) Then
        Cells(rowNo, 9).Value = "GS"
    ElseIf IsInArray(currCellCont, FilterList) Then
        Cells(roNo, colNo).Value = "Filter"
    End If
    currCellCont = Cells(rowNo + 1, colNo)
Loop

End Sub

Function IsInArray(lookingFor As Long, arr As Long) As Boolean
    IsInArray = Not IsError(Application.Match(lookingFor, arr, 0))
End Function
</code>```

答:
Use variant arrays:</p>

```<code>Sub sort()

Dim rowNo As Integer
Dim colNo As Integer
Dim PIList() As Variant
Dim GSList() As Variant
Dim FilterList() As Variant
Dim currCellCont As Long

rowNo = 2
colNo = 2
PIList = Array(0, 1, 2, 3, 4, 5)
GSList = Array(6, 7)
FilterList = Array(89752, 89753, 89754, 89755, 89756, 89757, 89758, 89759, 89760, 89761, 89762, 89763, 89764, 89765, 89766, 89767, 89768, 89769, 89770, 89771, 89772, 89773, 89774, 89775, 89776, 89777, 89778, 89779, 89780, 89781, 89782, 89783, 89784, 89785, 89786, 89787, 89788, 89789, 89790, 89791, 89792, 89793, 89794, 89795, 89796, 89797, 89798, 89799, 89800, 89801, 89802, 89803, 89804, 89805, 89806, 89807, 89808, 89809, 89810, 89811, 89812, 89813, 89814, 89815, 89816, 89817, 89818, 89819, 89820, 89821, 89822, 89823, 89824, 89825, 89826, 89827, 89828, 89829, 89830, 89831, 89832, 89833, 89834, 89835, 89836, 89837, 89838, 89839, 89840, 89841, 89842)
currCellCont = ActiveSheet.Cells(rowNo, colNo).Value
With Worksheets("Sheet1") 'Change to your sheet if always the same or ActiveSheet if on various sheets.
    Do Until currCellCont = 0
        If IsInArray(currCellCont, PIList) Then
            .Cells(rowNo, 9).Value = "PI"
        ElseIf IsInArray(currCellCont, GSList) Then
            .Cells(rowNo, 9).Value = "GS"
        ElseIf IsInArray(currCellCont, FilterList) Then
            .Cells(roNo, colNo).Value = "Filter"
        End If
        rowNo = rowNo + 1
        currCellCont = .Cells(rowNo, colNo).Value
    Loop
End With

End Sub

Function IsInArray(lookingFor As Long, arr() As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(lookingFor, arr, 0))
End Function
</code>```

Body:
When I run this, it gives me an error saying

ByRef argument type mismatch

in the if statement.

I had all of the arrays declared as variants, but that also gave me an error when I tried to run the function.

Any help would be greatly appreciated.

sub sort()

Dim rowNo As Integer
Dim colNo As Integer
Dim PIList(6) As Long
Dim GSList(2) As Long
Dim FilterList(91) As Long
Dim currCellCont As Long

rowNo = 2
colNo = 2
PIList(6) = Array(0,1,2,3,4,5)
GSList(2) = Array(6,7)
FilterList(91) = Array(89752, 89753, 89754, 89755, 89756, 89757, 89758, 89759, 89760, 89761, 89762, 89763, 89764, 89765, 89766, 89767, 89768, 89769, 89770, 89771, 89772, 89773, 89774, 89775, 89776, 89777, 89778, 89779, 89780, 89781, 89782, 89783, 89784, 89785, 89786, 89787, 89788, 89789, 89790, 89791, 89792, 89793, 89794, 89795, 89796, 89797, 89798, 89799, 89800, 89801, 89802, 89803, 89804, 89805, 89806, 89807, 89808, 89809, 89810, 89811, 89812, 89813, 89814, 89815, 89816, 89817, 89818, 89819, 89820, 89821, 89822, 89823, 89824, 89825, 89826, 89827, 89828, 89829, 89830, 89831, 89832, 89833, 89834, 89835, 89836, 89837, 89838, 89839, 89840, 89841, 89842)
currCellCont = Cells(rowNo, colNo).Value

Do Until IsEmpty(currCellCont)
    If IsInArray(currCellCont, PIList) Then
        Cells(rowNo, 9).Value = "PI"
    ElseIf IsInArray(currCellCont, GSList) Then
        Cells(rowNo, 9).Value = "GS"
    ElseIf IsInArray(currCellCont, FilterList) Then
        Cells(roNo, colNo).Value = "Filter"
    End If
    currCellCont = Cells(rowNo + 1, colNo)
Loop

End Sub

Function IsInArray(lookingFor As Long, arr As Long) As Boolean
    IsInArray = Not IsError(Application.Match(lookingFor, arr, 0))
End Function

Body:
Use variant arrays:

Sub sort()

Dim rowNo As Integer
Dim colNo As Integer
Dim PIList() As Variant
Dim GSList() As Variant
Dim FilterList() As Variant
Dim currCellCont As Long

rowNo = 2
colNo = 2
PIList = Array(0, 1, 2, 3, 4, 5)
GSList = Array(6, 7)
FilterList = Array(89752, 89753, 89754, 89755, 89756, 89757, 89758, 89759, 89760, 89761, 89762, 89763, 89764, 89765, 89766, 89767, 89768, 89769, 89770, 89771, 89772, 89773, 89774, 89775, 89776, 89777, 89778, 89779, 89780, 89781, 89782, 89783, 89784, 89785, 89786, 89787, 89788, 89789, 89790, 89791, 89792, 89793, 89794, 89795, 89796, 89797, 89798, 89799, 89800, 89801, 89802, 89803, 89804, 89805, 89806, 89807, 89808, 89809, 89810, 89811, 89812, 89813, 89814, 89815, 89816, 89817, 89818, 89819, 89820, 89821, 89822, 89823, 89824, 89825, 89826, 89827, 89828, 89829, 89830, 89831, 89832, 89833, 89834, 89835, 89836, 89837, 89838, 89839, 89840, 89841, 89842)
currCellCont = ActiveSheet.Cells(rowNo, colNo).Value
With Worksheets("Sheet1") 'Change to your sheet if always the same or ActiveSheet if on various sheets.
    Do Until currCellCont = 0
        If IsInArray(currCellCont, PIList) Then
            .Cells(rowNo, 9).Value = "PI"
        ElseIf IsInArray(currCellCont, GSList) Then
            .Cells(rowNo, 9).Value = "GS"
        ElseIf IsInArray(currCellCont, FilterList) Then
            .Cells(roNo, colNo).Value = "Filter"
        End If
        rowNo = rowNo + 1
        currCellCont = .Cells(rowNo, colNo).Value
    Loop
End With

End Sub

Function IsInArray(lookingFor As Long, arr() As Variant) As Boolean
    IsInArray = Not IsError(Application.Match(lookingFor, arr, 0))
End Function


问:
groups of routes with react-router-4
My react app has 3 entry points with overlapping routes, and it is getting hard to maintain. 2 of the apps are basically just stuck in a couple places on the legacy site, until the main app has enough functionality to fully replace the main site.

I am using React router 4, and have a routes.tsx file with all my routes. But I would like to group the routes by function, and then have the routes component for each app just take what it needs.

Currently my routes look like this:

```<code>const MainAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            <Route path='/customers' component={CustomersDisplayPage} />
            <Route path='/customers/:id' component={CustomersDisplayPage} />
            <Route path='/cars' component={CarDisplayPage} />
            <Route path='/cars/:id' component={CarDisplayPage} />
        </Switch>
    );
};
</code>```

But I would like it to look like this:

```<code>const MainAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            <CustomerAppRoutes />
            <CarAppRoutes />
        </Switch>
    );

const CustomerAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route path='/customers' component={CustomersDisplayPage} />
            <Route path='/customers/:id' component={CustomersDisplayPage} />
        </Switch>
    );
};

const CarAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route path='/cars' component={CarDisplayPage} />
            <Route path='/cars/:id' component={CarDisplayPage} />
        </Switch>
    );
};
</code>```

But this causes Caroutes not to route properly. I have tried using Div's instead, and that does not work either.

答:
The solution I am currently using is to create arrays of routes:</p>

```<code>//routes.tsx
import * as React from 'react';

export interface IRoute { path: string, component: React.ComponentClass, exact?: boolean }

const CarRoutes: IRoute[] = [
   { path: '/cars', component: {CarDisplayPage} },
   { path: '/cars/:id', component: {CarDisplayPage} },
];

const CustomerRoutes: IRoute[] = [
    { path: '/customers', component: {CustomerDisplayPage} },
    { path: '/customers/:id', component: {CustomerDisplayPage} },
];

const AppRouting: React.SFC = (): JSX.Element =>
{
    const routes = []
        .concat(CarRoutes)
        .concat(CustomerRoutes);
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            {routes.map(r => <Route path={r.path} exact={r.exact===true} path={r.path} key={r.path} />)}
        </Switch>
    );
};
</code>```

Title: groups of routes with react-router-4

Body:
My react app has 3 entry points with overlapping routes, and it is getting hard to maintain. 2 of the apps are basically just stuck in a couple places on the legacy site, until the main app has enough functionality to fully replace the main site.

I am using React router 4, and have a routes.tsx file with all my routes. But I would like to group the routes by function, and then have the routes component for each app just take what it needs.

Currently my routes look like this:

const MainAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            <Route path='/customers' component={CustomersDisplayPage} />
            <Route path='/customers/:id' component={CustomersDisplayPage} />
            <Route path='/cars' component={CarDisplayPage} />
            <Route path='/cars/:id' component={CarDisplayPage} />
        </Switch>
    );
};

But I would like it to look like this:

const MainAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            <CustomerAppRoutes />
            <CarAppRoutes />
        </Switch>
    );

const CustomerAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route path='/customers' component={CustomersDisplayPage} />
            <Route path='/customers/:id' component={CustomersDisplayPage} />
        </Switch>
    );
};

const CarAppRoutes: React.SFC = (): JSX.Element =>
{
    return (
        <Switch>
            <Route path='/cars' component={CarDisplayPage} />
            <Route path='/cars/:id' component={CarDisplayPage} />
        </Switch>
    );
};

But this causes Caroutes not to route properly. I have tried using Div's instead, and that does not work either.

Body:
The solution I am currently using is to create arrays of routes:

//routes.tsx
import * as React from 'react';

export interface IRoute { path: string, component: React.ComponentClass, exact?: boolean }

const CarRoutes: IRoute[] = [
   { path: '/cars', component: {CarDisplayPage} },
   { path: '/cars/:id', component: {CarDisplayPage} },
];

const CustomerRoutes: IRoute[] = [
    { path: '/customers', component: {CustomerDisplayPage} },
    { path: '/customers/:id', component: {CustomerDisplayPage} },
];

const AppRouting: React.SFC = (): JSX.Element =>
{
    const routes = []
        .concat(CarRoutes)
        .concat(CustomerRoutes);
    return (
        <Switch>
            <Route exact path='/' component={HomePage} />
            {routes.map(r => <Route path={r.path} exact={r.exact===true} path={r.path} key={r.path} />)}
        </Switch>
    );
};


问:
How can i set up screen lock with a password programmatically?
Is there any one that can help me with a code to set a password to lock the screen ? thx</p>

答:
Android N is not working , See Here

Note: This API has been limited as of N for device admins that are not device owner and not profile owner. The password can now only be changed if there is currently no password set. Device owner and profile owner can still do this when user is unlocked and does not have a managed profile.


问:
RSPEC throws NameError: uninitialized constant error for shared module after Rails 5 upgrade
I recently upgraded to Rails 5 and am encountering an error on development that is (what I expect, anyway) related to loading a shared module.

The error is Rspec: NameError: uninitialized constant ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES and occurs when running Rspec tests that use a method that uses a shared module.

The path for the shared module is: lib/shared/truthy.rb and the module code is below.

module Shared
  module Truthy
    def self.boolean(value)
      ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES.include?(value)
    end
  end
end

The path for the file that uses the method that accesses this module is: engines/events/app/controllers/events/events_controller.rband the method that uses the shared module is below.

def official_event?
   Shared::Truthy.boolean(params[:event][:official])
 end

This wasn't throwing any error prior to upgrading to Rails 5, so it's safe to say there's no issue with the Rspec test.

Thanks in advance for any input.

答: I found out that this error is a result of Rails 5 removing uses of ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES. </p>


问:
C++ - Create Tree rekursively with map
I would like to create a tree where each node represents a single charakter, the leaf-nodes represent the string created by the chars which lead up to this leaf-node. My approach (maybe the class names are a bit missleading, this is just a quick prototype, Foo is the Base-class, Bar is a node and BarBar a leaf-node):

```<code>class Foo{
public:
    virtual void print() = 0;
};

class BarBar : public Foo {
public:
    BarBar(int mData) : data(mData){};
    int data;

    void print(){
        cout << data << endl;
    }
};

class Bar : public Foo {
public:
    map<char,Foo*> ptr;
    void insert(char c, Foo* f){
        ptr.insert(pair<char,Foo*>(c,f));
    }
    void procStr(char* str, int dat){
        if(str[0] != '\0'){
            Bar b;
            insert(str[0],b); //error "Invalid arguments 'Candidates are:void insert(char, Foo *)'"
            str++;
            b.procStr(str,dat);
        } else {
            BarBar bar(dat);
            insert('^',bar); //error "Invalid arguments 'Candidates are:void insert(char, Foo *)'"
        }
    }
    void print(){
        for (auto& kv : ptr){
            cout << kv.first << endl;
            kv.second->print();
        }
    }
}

int main(){
    Bar root;
    root.procStr("Hello",42);
    root.print();
    return 0;
}
</code>```

My expected output would be:

```<code>H
e
l
l
o
</code>```

But instead I get:

```<code>H
Ä
</code>```

and the program crashes.

The program crashes at:

```<code>Foo& res = kv.second;
res.print(); //<<-- Program crashes
</code>```

答:
```<code>BarBar bar(dat);

            insert('^',bar); //error "Invalid arguments 'Candidates are:void insert(char, Foo *)'"
</code>```

Your function takes a Foo* but you are passing an instance (still a local instance at that, so even if you passed &bar it would be invalid by the time you use it).

A map is really not the right structure for this problem, look up order statistic trees, they provide ordering without sorting which is what you are after here. That is, an OS tree can store  'o', 'h' as readily as 'h', 'o'.

Title: C++ - Create Tree rekursively with map

Body:
I would like to create a tree where each node represents a single charakter, the leaf-nodes represent the string created by the chars which lead up to this leaf-node. My approach (maybe the class names are a bit missleading, this is just a quick prototype, Foo is the Base-class, Bar is a node and BarBar a leaf-node):

class Foo{
public:
    virtual void print() = 0;
};

class BarBar : public Foo {
public:
    BarBar(int mData) : data(mData){};
    int data;

    void print(){
        cout << data << endl;
    }
};

class Bar : public Foo {
public:
    map<char,Foo*> ptr;
    void insert(char c, Foo* f){
        ptr.insert(pair<char,Foo*>(c,f));
    }
    void procStr(char* str, int dat){
        if(str[0] != '\0'){
            Bar b;
            insert(str[0],b); //error "Invalid arguments 'Candidates are:void insert(char, Foo *)'"
            str++;
            b.procStr(str,dat);
        } else {
            BarBar bar(dat);
            insert('^',bar); //error "Invalid arguments 'Candidates are:void insert(char, Foo *)'"
        }
    }
    void print(){
        for (auto& kv : ptr){
            cout << kv.first << endl;
            kv.second->print();
        }
    }
}

int main(){
    Bar root;
    root.procStr("Hello",42);
    root.print();
    return 0;
}

My expected output would be:

H
e
l
l
o

But instead I get:

H
Ä

and the program crashes.

The program crashes at:

Foo& res = kv.second;
res.print(); //<<-- Program crashes

Body:
BarBar bar(dat);

            insert('^',bar); //error "Invalid arguments 'Candidates are:void insert(char, Foo *)'"

Your function takes a Foo* but you are passing an instance (still a local instance at that, so even if you passed &bar it would be invalid by the time you use it).

A map is really not the right structure for this problem, look up order statistic trees, they provide ordering without sorting which is what you are after here. That is, an OS tree can store  'o', 'h' as readily as 'h', 'o'.


问:
Why do I need to use the new Paging library? (Android Architecture Components)
I am really interested in newly introduced Android Architecture Components. But I can't say that I understand what is the 'Paging' library about.

It looks like it's purpose is to provide help with data pagination. But isn't that already an easy thing? Like I can just hold some integer values somewhere in my code and then use them later in my network / room database query.

It's clear that I am missing something here. Please help me understand the need of Paging library

答:
The paging library is indeed for use with data pagination for a data source, this data source can be as simple as a single table in a database or as complex as multiple tables and multiple network api sources as set out in your own custom data source class.

The pagination library not only provides smooth pagination from your data source, but it also provides seamless background updates to the individual recycler view items already shown. I personally hate calling notifyDataSetChanged when unsure of how many items are being changed, and I look forward to the opportunity to have the currently shown list diffed against the requested list form a background thread, with items individually inserted, removed, and updated where necessary.

The full architecture from the pagedListAdapter to the datasource, perfectly separates each concern (making testing easier), and if followed provides a way for a commonly used (and often poorly implemented) aspect of android to be implemented well. This improves individual software quality, user and developer experience (It's fairly simple), and enhances the android brand as a whole (by improving android software quality as a whole).


问:
Hide url parameters from php
```<code><a href="rate.php?winner=<?=$images[0]->image_id?>&loser=<?=$images[1]->image_id?>"></a>
</code>```

This is main page index.php

This was my main page. Before uploading to php file parameters can be changed using inspect element and this is a problem.

This is rate.php

```<code><?php

include('mysql.php');
include('functions.php');

// If rating - update the database
if ($_GET['winner'] && $_GET['loser']) {

// Get the winner
$result = $conn->query("SELECT * FROM images WHERE image_id = ".$_GET['winner']." ");
$winner = $result->fetch_object();

// Get the loser
$result = $conn->query("SELECT * FROM images WHERE image_id = ".$_GET['loser']." ");
$loser = $result->fetch_object();

// Update the winner score
$winner_expected = expected($loser->score, $winner->score);
$winner_new_score = win($winner->score, $winner_expected);
    //test print "Winner: ".$winner->score." - ".$winner_new_score." - ".$winner_expected."<br>";
$conn->query("UPDATE images SET score = ".$winner_new_score.", wins = wins+1 WHERE image_id = ".$_GET['winner']);

// Update the loser score
$loser_expected = expected($winner->score, $loser->score);
$loser_new_score = loss($loser->score, $loser_expected);
    //test print "Loser: ".$loser->score." - ".$loser_new_score." - ".$loser_expected."<br>";
$conn->query("UPDATE images SET score = ".$loser_new_score.", losses = losses+1  WHERE image_id = ".$_GET['loser']);

// Insert battle
$conn->query("INSERT INTO battles SET winner = ".$_GET['winner'].", loser = ".$_GET['loser']." ");

// Back to the frontpage
header('location: /');

}

?>
</code>```

I just want that parameters can be modified while sending data to php file

答:
You need to add some extra verification/validation to your code. That's regardless if you're using GET or POST to pass the data.

You can set a session per call that defines what ID's the user are allowed to pass. It works like a basic CSRF protection:

It can be something like the below:

On the voting page:

```<code><?php
// Start sessions (should always be in the top
session_start();

// Get the image id's some how. Let's use these as an example
// This could just as well be strings or what ever it is you're posting
$image1 = 1;
$image2 = 2;

// Generate a pseudo random token
$token = bin2hex(random_bytes(16));

// Store the image references in a session with the token as name
$_SESSION[$token] = [$image1, $image2];
?>

// HTML that sends the image references and the token (important)
</code>```

On the page that receives the data:

```<code><?php
// Again, start sessions;
session_start();

// Check that all parameters are there
if (!isset($_POST['winner'], $_POST['loser'], $_POST['token'])) {
    die('Invalid request');
}

$winner = $_POST['winner'];
$looser = $_POST['loser'];
$token  = $_POST['token'];

// Check if the session is set. If not, then the call didn't come from your page
if (!$token || empty($_SESSION[$token])) {
    die('We have a CSRF attack');
}

// Check if both image references exists in session. If not, then someone have change the values
if (!in_array($winner, $_SESSION[$token]) || !in_array($loser, $_SESSION[$token])) {
    die('Invalid image references! We have a cheater!');
}

// Remove the token from the session so the user can't repeat the call
unset($_SESSION[$token]);

// Do your DB stuff using Prepared Statements.
</code>```

This is an untested example, so it might not work straight out of the gate, but it shows you a technique that can be used.

Important

You are currently wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Specially since you're not escaping the user inputs at all!

Title: Hide url parameters from php

Body:
<a href="rate.php?winner=<?=$images[0]->image_id?>&loser=<?=$images[1]->image_id?>">

This is main page index.php

This was my main page. Before uploading to php file parameters can be changed using inspect element and this is a problem.

This is rate.php

<?php

include('mysql.php');
include('functions.php');

// If rating - update the database
if ($_GET['winner'] && $_GET['loser']) {

// Get the winner
$result = $conn->query("SELECT * FROM images WHERE image_id = ".$_GET['winner']." ");
$winner = $result->fetch_object();

// Get the loser
$result = $conn->query("SELECT * FROM images WHERE image_id = ".$_GET['loser']." ");
$loser = $result->fetch_object();

// Update the winner score
$winner_expected = expected($loser->score, $winner->score);
$winner_new_score = win($winner->score, $winner_expected);
    //test print "Winner: ".$winner->score." - ".$winner_new_score." - ".$winner_expected."
";
$conn->query("UPDATE images SET score = ".$winner_new_score.", wins = wins+1 WHERE image_id = ".$_GET['winner']);

// Update the loser score
$loser_expected = expected($winner->score, $loser->score);
$loser_new_score = loss($loser->score, $loser_expected);
    //test print "Loser: ".$loser->score." - ".$loser_new_score." - ".$loser_expected."
";
$conn->query("UPDATE images SET score = ".$loser_new_score.", losses = losses+1  WHERE image_id = ".$_GET['loser']);

// Insert battle
$conn->query("INSERT INTO battles SET winner = ".$_GET['winner'].", loser = ".$_GET['loser']." ");

// Back to the frontpage
header('location: /');

}

?>

I just want that parameters can be modified while sending data to php file

Body:
You need to add some extra verification/validation to your code. That's regardless if you're using GET or POST to pass the data.

You can set a session per call that defines what ID's the user are allowed to pass. It works like a basic CSRF protection:

It can be something like the below:

On the voting page:

<?php
// Start sessions (should always be in the top
session_start();

// Get the image id's some how. Let's use these as an example
// This could just as well be strings or what ever it is you're posting
$image1 = 1;
$image2 = 2;

// Generate a pseudo random token
$token = bin2hex(random_bytes(16));

// Store the image references in a session with the token as name
$_SESSION[$token] = [$image1, $image2];
?>

// HTML that sends the image references and the token (important)

On the page that receives the data:

<?php
// Again, start sessions;
session_start();

// Check that all parameters are there
if (!isset($_POST['winner'], $_POST['loser'], $_POST['token'])) {
    die('Invalid request');
}

$winner = $_POST['winner'];
$looser = $_POST['loser'];
$token  = $_POST['token'];

// Check if the session is set. If not, then the call didn't come from your page
if (!$token || empty($_SESSION[$token])) {
    die('We have a CSRF attack');
}

// Check if both image references exists in session. If not, then someone have change the values
if (!in_array($winner, $_SESSION[$token]) || !in_array($loser, $_SESSION[$token])) {
    die('Invalid image references! We have a cheater!');
}

// Remove the token from the session so the user can't repeat the call
unset($_SESSION[$token]);

// Do your DB stuff using Prepared Statements.

This is an untested example, so it might not work straight out of the gate, but it shows you a technique that can be used.

Important

You are currently wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Specially since you're not escaping the user inputs at all!


问:
Reading Words from a File and Writing Them on The Same Line
I have a file that contains a word per a line. Each sentence is separated by an empty line. I want to read the file and write the whole words of a sentence on the same line. For example:

```<code>This
is
a
sample
input

Hello
World
!!
</code>```

The desired output is:

```<code>This is a sample input
Hello World !!
</code>```

I try this:

```<code>file = open('Words.txt', "r")
Writfile = open('Sent.txt','w')

for line in file:
    if line in ['\n']:
        Writfile.write('\n')
    else:
        Writfile.write(line + " ",)
</code>```

答:
Do something like this:

```<code>input = """This
is
a
sample
input

Hello
World
!!
"""

import StringIO
fi = StringIO.StringIO(input)
lines = fi.read().split("\n")
one_line = " ".join(lines)
print one_line
</code>```

will output:

This is a sample input  Hello World !!

The StringIO is there only to fake the reading of a file

Body:
I have a file that contains a word per a line. Each sentence is separated by an empty line. I want to read the file and write the whole words of a sentence on the same line. For example:

This
is
a
sample
input

Hello
World
!!

The desired output is:

This is a sample input
Hello World !!

I try this:

file = open('Words.txt', "r")
Writfile = open('Sent.txt','w')

for line in file:
    if line in ['\n']:
        Writfile.write('\n')
    else:
        Writfile.write(line + " ",)

Body:
Do something like this:

input = """This
is
a
sample
input

Hello
World
!!
"""

import StringIO
fi = StringIO.StringIO(input)
lines = fi.read().split("\n")
one_line = " ".join(lines)
print one_line

will output:

This is a sample input  Hello World !!

The StringIO is there only to fake the reading of a file


问:
Serial point to point protocol but with 8 bytes instead of 16
I was looking at answers in Simple serial point-to-point communication protocol and it doesn't help me enough with my issue. I am also trying to communicate data between a computer and an 8-bit microcontroller at first, then eventually I want to communicate the one microcontroller to about 40 others via wireless radio modules. Basically one is designated as a master and the rest are slaves.

speed is an issue

The issue at hand is speed. because communication of every packet needs to be done at least 4x a second back and forth between the master and each slave.

Let's assume baud rate for data is 9600bps. That's 960 bytes a second.

If I used 16-byte packets then: 40 (slaves) times 16 (bytes) times 2 (ways) = 640. Divide that into 960 and that would mean well more than 1/2 a second. Not good.

If I used 8-byte packets then: 40 (slaves) times 8 (bytes) times 2 (ways) = 320. Divide that into 960 and that would mean 1/3 second. It's so-so.

But the thing is I need to watch my baud because too high of baud might mean missed data at larger distances, but you can see the speed difference between an 8 and 16 byte packet.

packet format idea

In my design, I may have a need to transmit a number in the low millions so that will use 24-bits which fits in my idea. But here's my initial idea:

```<code>Byte 1: Recipient address 0-255
Byte 2: Sender address 0-255
Byte 3: Command
Byte 4-6: Data
Byte 7-8: 16-bit fletcher checksum of above data
</code>```

I don't mind if the above format is adjusted, just as long as I have at least 6 bits to identify the sender and receiver (since I'll only deal with 40 units), and the data with command included should be at least 4 bytes total.

How should I modify my data packet idea so that even the device that just turned on in the middle of reception can be in sync with the next set of data? Is there a way without stripping a bit from each data byte?

答:
Rely on the check sum! My packet would consists of:

Recipient's address (0..40) XORed with 0x55

Sender's address (0..40) XORed with 0xAA

Command Byte

Data Byte 0

Data Byte 1

Data Byte 2

CRC8 sum, as suggested by Vroomfondel

Every receiver should have a sliding window of the last seven received bytes. When a byte was shifted in, that window should checked if it is valid:

Are the two addresses in the valid range?

Is it a valid command?

Is the CRC correct?

Especially the last one should safely reject packets on which the receiver hopped on off-sync.

If you have less than 32 command codes, you may go down to six bytes per packet: 40[Senders] times 40[Receivers] times 32[Commands] evaluates to 51200, which would fit into 16 bits instead of 24.

Don't forget to turn off the parity bit!

Update 2017-12-09: Here a receiving function:

```<code>typedef uint8_t U8;

void ByteReceived(U8 Byte)
{
   static U8 Buf[7]; //Bytes received so far
   static U8 BufBC=0;

   Buf[BufBC++] = Byte;

   if (BufBC<7) return; //Msg incomplete

   /*** Seven Byte Message received ***/

   //Check Addresses
   U8 Adr;
   Adr = Buf[0] ^ 0x55; if (Adr >= 40) goto Fail;
   Adr = Buf[1] ^ 0xAA; if (Adr >= 40) goto Fail;

   if (Buf[2] > ???) goto Fail; //Check Cmd

   if (CalcCRC8(Buf, 6) != Buf[6]) goto Fail;

   Evaluate(...);

   BufBC=0; //empty Buf[]
   return;
Fail:
   //Seven Byte Msg invalid -> chop off first byte, could use memmove()
   Buf[0] = Buf[1];
   Buf[1] = Buf[2];
   Buf[2] = Buf[3];
   Buf[3] = Buf[4];
   Buf[4] = Buf[5];
   Buf[5] = Buf[6];
   BufBC  = 6;
}
</code>```

Body:
I was looking at answers in Simple serial point-to-point communication protocol and it doesn't help me enough with my issue. I am also trying to communicate data between a computer and an 8-bit microcontroller at first, then eventually I want to communicate the one microcontroller to about 40 others via wireless radio modules. Basically one is designated as a master and the rest are slaves.

speed is an issue

The issue at hand is speed. because communication of every packet needs to be done at least 4x a second back and forth between the master and each slave.

Let's assume baud rate for data is 9600bps. That's 960 bytes a second.

If I used 16-byte packets then: 40 (slaves) times 16 (bytes) times 2 (ways) = 640. Divide that into 960 and that would mean well more than 1/2 a second. Not good.

If I used 8-byte packets then: 40 (slaves) times 8 (bytes) times 2 (ways) = 320. Divide that into 960 and that would mean 1/3 second. It's so-so.

But the thing is I need to watch my baud because too high of baud might mean missed data at larger distances, but you can see the speed difference between an 8 and 16 byte packet.

packet format idea

In my design, I may have a need to transmit a number in the low millions so that will use 24-bits which fits in my idea. But here's my initial idea:

Byte 1: Recipient address 0-255
Byte 2: Sender address 0-255
Byte 3: Command
Byte 4-6: Data
Byte 7-8: 16-bit fletcher checksum of above data

I don't mind if the above format is adjusted, just as long as I have at least 6 bits to identify the sender and receiver (since I'll only deal with 40 units), and the data with command included should be at least 4 bytes total.

How should I modify my data packet idea so that even the device that just turned on in the middle of reception can be in sync with the next set of data? Is there a way without stripping a bit from each data byte?

Body:
Rely on the check sum! My packet would consists of:

Recipient's address (0..40) XORed with 0x55

Sender's address (0..40) XORed with 0xAA

Command Byte

Data Byte 0

Data Byte 1

Data Byte 2

CRC8 sum, as suggested by Vroomfondel

Every receiver should have a sliding window of the last seven received bytes. When a byte was shifted in, that window should checked if it is valid:

Are the two addresses in the valid range?

Is it a valid command?

Is the CRC correct?

Especially the last one should safely reject packets on which the receiver hopped on off-sync.

If you have less than 32 command codes, you may go down to six bytes per packet: 40[Senders] times 40[Receivers] times 32[Commands] evaluates to 51200, which would fit into 16 bits instead of 24.

Don't forget to turn off the parity bit!

Update 2017-12-09: Here a receiving function:

typedef uint8_t U8;

void ByteReceived(U8 Byte)
{
   static U8 Buf[7]; //Bytes received so far
   static U8 BufBC=0;

   Buf[BufBC++] = Byte;

   if (BufBC<7) return; //Msg incomplete

   /*** Seven Byte Message received ***/

   //Check Addresses
   U8 Adr;
   Adr = Buf[0] ^ 0x55; if (Adr >= 40) goto Fail;
   Adr = Buf[1] ^ 0xAA; if (Adr >= 40) goto Fail;

   if (Buf[2] > ???) goto Fail; //Check Cmd

   if (CalcCRC8(Buf, 6) != Buf[6]) goto Fail;

   Evaluate(...);

   BufBC=0; //empty Buf[]
   return;
Fail:
   //Seven Byte Msg invalid -> chop off first byte, could use memmove()
   Buf[0] = Buf[1];
   Buf[1] = Buf[2];
   Buf[2] = Buf[3];
   Buf[3] = Buf[4];
   Buf[4] = Buf[5];
   Buf[5] = Buf[6];
   BufBC  = 6;
}