问:
Getting current week of current month
I found a javascript and a php script to get current week of the month base on the entire year. That's great but im a little confused. I would like to know whether if it's week 1,2,3,4 of current month not entire year. How should I got about that?

javascript

```<code>/**
 * Returns the week number for this date.  dowOffset is the day of week the week
 * "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
 * the week returned is the ISO 8601 week number.
 * @param int dowOffset
 * @return int
 */
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

    dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
    var newYear = new Date(this.getFullYear(),0,1);
    var day = newYear.getDay() - dowOffset; //the day of week the year begins on
    day = (day >= 0 ? day : day + 7);
    var daynum = Math.floor((this.getTime() - newYear.getTime() -
    (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
    var weeknum;
    //if the year starts before the middle of a week
    if(day < 4) {
        weeknum = Math.floor((daynum+day-1)/7) + 1;
        if(weeknum > 52) {
            nYear = new Date(this.getFullYear() + 1,0,1);
            nday = nYear.getDay() - dowOffset;
            nday = nday >= 0 ? nday : nday + 7;
            /*if the next year starts before the middle of
              the week, it is week #1 of that year*/
            weeknum = nday < 4 ? 1 : 53;
        }
    }
    else {
        weeknum = Math.floor((daynum+day-1)/7);
    }
    return weeknum;
};
</code>```

Usage

```<code>var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());
</code>```

答:
This works at getting the current week of the month for those who only want to know which week from 1 to 5.

script

```<code>var d = new Date();
var date = d.getDate();
var day = d.getDay();

var weekOfMonth = Math.ceil((date + 6 - day)/7);

document.getElementById('week').value = weekOfMonth;
</code>```

markup

```<code><input type='text' id='week' value=''>
</code>```

Title: Getting current week of current month

Body:
I found a javascript and a php script to get current week of the month base on the entire year. That's great but im a little confused. I would like to know whether if it's week 1,2,3,4 of current month not entire year. How should I got about that?

javascript

/**
 * Returns the week number for this date.  dowOffset is the day of week the week
 * "starts" on for your locale - it can be from 0 to 6. If dowOffset is 1 (Monday),
 * the week returned is the ISO 8601 week number.
 * @param int dowOffset
 * @return int
 */
Date.prototype.getWeek = function (dowOffset) {
/*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

    dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
    var newYear = new Date(this.getFullYear(),0,1);
    var day = newYear.getDay() - dowOffset; //the day of week the year begins on
    day = (day >= 0 ? day : day + 7);
    var daynum = Math.floor((this.getTime() - newYear.getTime() -
    (this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
    var weeknum;
    //if the year starts before the middle of a week
    if(day < 4) {
        weeknum = Math.floor((daynum+day-1)/7) + 1;
        if(weeknum > 52) {
            nYear = new Date(this.getFullYear() + 1,0,1);
            nday = nYear.getDay() - dowOffset;
            nday = nday >= 0 ? nday : nday + 7;
            /*if the next year starts before the middle of
              the week, it is week #1 of that year*/
            weeknum = nday < 4 ? 1 : 53;
        }
    }
    else {
        weeknum = Math.floor((daynum+day-1)/7);
    }
    return weeknum;
};

Usage

var mydate = new Date(2011,2,3); // month number starts from 0
// or like this
var mydate = new Date('March 3, 2011');
alert(mydate.getWeek());

Body:
This works at getting the current week of the month for those who only want to know which week from 1 to 5.

script

var d = new Date();
var date = d.getDate();
var day = d.getDay();

var weekOfMonth = Math.ceil((date + 6 - day)/7);

document.getElementById('week').value = weekOfMonth;

markup

<input type='text' id='week' value=''>


来源: stackexchange

问:
How can I convert pixel data in QImage to another format?
I receive an instance of QImage with arbitrary QImage::Format. How can I create another instance of QImage with a particular QImage::Format of my choosing so that the actual image data is converted from the arbitrary format to my format?

Example:

```<code>QImage convertFormat(const QImage &inputImage, QImage::format outputFormat)
{
    // What comes here?
}

//Usage
QImage converted = convertFormat(mySourceImage, QImage::Format_Grayscale8);
</code>```

I am looking for a way to do this with existing code in Qt if possible (as opposed to writing my own pixel format conversion routines working on the low level).

答: Why not use convertToFormat? It has nearly the same syntax as you requested, though it's a member of QImage so you'd only pass in the format.

ContentLicense: CC BY-SA 3.0

Body:
I receive an instance of QImage with arbitrary QImage::Format. How can I create another instance of QImage with a particular QImage::Format of my choosing so that the actual image data is converted from the arbitrary format to my format?

Example:

QImage convertFormat(const QImage &inputImage, QImage::format outputFormat)
{
    // What comes here?
}

//Usage
QImage converted = convertFormat(mySourceImage, QImage::Format_Grayscale8);

I am looking for a way to do this with existing code in Qt if possible (as opposed to writing my own pixel format conversion routines working on the low level).


问:
which version of firefox do we need for Selenium 3.3.1?
which version of firefox do we need for Selenium 3.3.1?? I'm trying to use firefox 51 with selenium 3.3.1 and I'm not able to launch the application please let me know which browser do we need to use for selenium 3.3.1</p>

答:
Firefox 51/52 works well with GeckoDriver 0.15.0 and Selenium 3.3.1. You would need to download correct version of GeckoDriver based on whether Firefox is 32-bit or 64-bit in Windows. Also, you may need to provide Firefox Binary which can be done with FirefoxOptions class.

```<code>    FirefoxOptions options = new FirefoxOptions();
    options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");

    FirefoxDriver driver = new FirefoxDriver(options);
    driver.get("http://www.google.com");
</code>```

Refer this article for more details - http://www.automationtestinghub.com/selenium-3-0-launch-firefox-with-geckodriver/

Body:
Firefox 51/52 works well with GeckoDriver 0.15.0 and Selenium 3.3.1. You would need to download correct version of GeckoDriver based on whether Firefox is 32-bit or 64-bit in Windows. Also, you may need to provide Firefox Binary which can be done with FirefoxOptions class.

    FirefoxOptions options = new FirefoxOptions();
    options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");

    FirefoxDriver driver = new FirefoxDriver(options);
    driver.get("http://www.google.com");

Refer this article for more details - http://www.automationtestinghub.com/selenium-3-0-launch-firefox-with-geckodriver/


问:
JavaScript Sort compare function fails in Internet Explorer
I have a function which orders dates based on a pivot. Note that this function ignores the year of the supplied dates. For example, given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.  The problem seems to be with my sort compare function which works perfectly fine in Chrome and Firefox, however fails in IE.  The resulting statsDataPoints (Array) does not get sorted.

This is what the dates array looks like:

[{"Min":"6.0", "Mean":"10.8", "Max":"32.1", "StdDev":"7.5", "LowerPercentile":"6.7", "Median":"8.0", "UpperPercentile":"11.2", "_Name":"30-Mar"}, {"Min":"6.0", "Mean":"11.1", "Max":"31.7", "StdDev":"7.4", "LowerPercentile":"7.3", "Median":"8.7", "UpperPercentile":"11.1", "_Name":"31-Mar"}, {"Min":"6.0", "Mean":"10.9", "Max":"31.4", "StdDev":"7.3", "LowerPercentile":"7.2", "Median":"8.4", "UpperPercentile":"11.0", "_Name":" 1-Apr"}, ... ]```
</div>
</div>
</p>

<p>This is my function:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/**
 * Returns a function which orders dates based on a pivot. Note that this function ignores the year of the
 * supplied dates. It is easiest to illustrate how this function works with an example:
 * Given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.
 *
 * @param {Array}  dates    An array of objects containing a date key.
 * @param {String} pivot    The pivot date we are sorting from (should be in the same format as dateKey)
 */

var dummyYear = 2000;
var pivot = moment(readingStartDate).format("DD-MMM");
pivot = moment(pivot, "DD-MMM").year(dummyYear);

statsDataPoints.sort(function(aDate, bDate) {

 var a = moment(aDate["_Name"], "DD-MMM").year(dummyYear).toDate();
 var b = moment(bDate["_Name"], "DD-MMM").year(dummyYear).toDate();

 if (((a < pivot) && (pivot < b)) || (a > b)) {
  return 1;
 } else if (((b < pivot) && (pivot < a)) || (a < b)) {
  return -1;
 }
 return 0;

});</code>```

答:
Thanks @CBroe, @yBrodsky and @Bergi for your replies.  I managed to resolve this by simplifying my code, and not using a sort, which is unfortunate but IE just wasn't handling the sort compare function really well.

Given that my data series was in the correct order, I just simply shifted my data points to the end of the array to ensure that my series start on current date.

To clarify this, this is how I do this:

// shift series by number of days since start of the year
var startOfYeat = moment().startOf('year');
var curDate = moment();
var daysSinceStartOfYear = curDate.diff(startOfYeat, 'days');

for (i = 0; i < daysSinceStartOfYear; i++) {
    statsDataPoints.push(statsDataPoints.shift());
}```

It is a shame that IE doesn't seem to support a simple compare function, so if anyone has other ideas as to why the sort fails in IE do leave a comment here.

Body:
I have a function which orders dates based on a pivot. Note that this function ignores the year of the supplied dates. For example, given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.  The problem seems to be with my sort compare function which works perfectly fine in Chrome and Firefox, however fails in IE.  The resulting statsDataPoints (Array) does not get sorted.

This is what the dates array looks like:

[{"Min":"6.0", "Mean":"10.8", "Max":"32.1", "StdDev":"7.5", "LowerPercentile":"6.7", "Median":"8.0", "UpperPercentile":"11.2", "_Name":"30-Mar"}, {"Min":"6.0", "Mean":"11.1", "Max":"31.7", "StdDev":"7.4", "LowerPercentile":"7.3", "Median":"8.7", "UpperPercentile":"11.1", "_Name":"31-Mar"}, {"Min":"6.0", "Mean":"10.9", "Max":"31.4", "StdDev":"7.3", "LowerPercentile":"7.2", "Median":"8.4", "UpperPercentile":"11.0", "_Name":" 1-Apr"}, ... ]

This is my function:

/**
 * Returns a function which orders dates based on a pivot. Note that this function ignores the year of the
 * supplied dates. It is easiest to illustrate how this function works with an example:
 * Given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.
 *
 * @param {Array}  dates    An array of objects containing a date key.
 * @param {String} pivot    The pivot date we are sorting from (should be in the same format as dateKey)
 */

var dummyYear = 2000;
var pivot = moment(readingStartDate).format("DD-MMM");
pivot = moment(pivot, "DD-MMM").year(dummyYear);

statsDataPoints.sort(function(aDate, bDate) {

 var a = moment(aDate["_Name"], "DD-MMM").year(dummyYear).toDate();
 var b = moment(bDate["_Name"], "DD-MMM").year(dummyYear).toDate();

 if (((a < pivot) && (pivot  b)) {
  return 1;
 } else if (((b < pivot) && (pivot < a)) || (a < b)) {
  return -1;
 }
 return 0;

});

Body:
Thanks @CBroe, @yBrodsky and @Bergi for your replies.  I managed to resolve this by simplifying my code, and not using a sort, which is unfortunate but IE just wasn't handling the sort compare function really well.

Given that my data series was in the correct order, I just simply shifted my data points to the end of the array to ensure that my series start on current date.

To clarify this, this is how I do this:

// shift series by number of days since start of the year
var startOfYeat = moment().startOf('year');
var curDate = moment();
var daysSinceStartOfYear = curDate.diff(startOfYeat, 'days');

for (i = 0; i < daysSinceStartOfYear; i++) {
    statsDataPoints.push(statsDataPoints.shift());
}

It is a shame that IE doesn't seem to support a simple compare function, so if anyone has other ideas as to why the sort fails in IE do leave a comment here.


问:
socket.io emit in loop until client responds?
I would like to emit a message to the client every X seconds until the client clicks a button and acknowledges receipt.

Any ideas on how I might accomplish this? New to Node but I am hoping I can get this done with Node and Sockets.io.

Thanks in advance for any insight or help to get me in the right direction.

答:
This is a simple setup just to give you an idea of how to do it:

node server (very basic, only socket.io, nothing else):

```<code>const io = require('socket.io')(3000);
const interval = 1000;
io.on('connection', function (socket) {
    console.log(socket.id + ' has connected');
    var foo = setInterval (function () {
        socket.emit('foo');
    }, interval);
    socket.on('confirmed', function () {
        console.log('confirmation received from ' + socket.id);
        clearInterval(foo);
    });
});
console.log('socket.io server started at port 3000');
</code>```

index.html (open it in your browser and see what happens):

```<code><!doctype html>
<html>
  <head>
    <title>Testing socket.io</title>
  </head>
  <body>
    <button id="button">Confirm</button>
    <p id="socket">waiting...</p>
    <p id="alert">foos counter: </p>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
    <script>
        var socket = io("http://localhost:3000");
        var counter;
        socket.on('connect', function() {
          counter = 0;
          document.getElementById("socket").innerHTML = "connected";
          document.getElementById("button").addEventListener("click", function () {
              socket.emit("confirmed");
          });
      });
      socket.on('foo', function() {
          counter++;
          document.getElementById("alert").innerHTML = "foos counter: " + counter;
      });
    </script>
  </body>
</html>
</code>```

Body:
This is a simple setup just to give you an idea of how to do it:

node server (very basic, only socket.io, nothing else):

const io = require('socket.io')(3000);
const interval = 1000;
io.on('connection', function (socket) {
    console.log(socket.id + ' has connected');
    var foo = setInterval (function () {
        socket.emit('foo');
    }, interval);
    socket.on('confirmed', function () {
        console.log('confirmation received from ' + socket.id);
        clearInterval(foo);
    });
});
console.log('socket.io server started at port 3000');

index.html (open it in your browser and see what happens):

<!doctype html>
<html>
  <head>
    <title>Testing socket.io</title>
  </head>
  <body>
    <button id="button">Confirm</button>
    <p id="socket">waiting...</p>
    <p id="alert">foos counter: </p>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.min.js"></script>
    <script>
        var socket = io("http://localhost:3000");
        var counter;
        socket.on('connect', function() {
          counter = 0;
          document.getElementById("socket").innerHTML = "connected";
          document.getElementById("button").addEventListener("click", function () {
              socket.emit("confirmed");
          });
      });
      socket.on('foo', function() {
          counter++;
          document.getElementById("alert").innerHTML = "foos counter: " + counter;
      });
    </script>
  </body>
</html>


问:
In-line R expression returns incorrect value
If the R code in Rmd file reuses the same variable name, the inline r expressions seem to return the last value of this variable regardless of the location of the inline expression. Is there away to avoid this behavior except for making sure the same variable name is not reused in different parts of the document?

The reproducible example

```<code>---
title: "R Notebook"
output: html_notebook
---

```{r}
df <- cars
nrow(df)
```

The dataset has `r nrow(df)` rows.

```{r}
df <- iris
nrow(df)
```

The dataset has `r nrow(df)` rows.
</code>```

This produces the following output

I am using:
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

rmarkdown_1.4
knitr_1.15.1

答:
The problem is that in your header, you are "previewing" your file, which does not actually run your code from scratch. You have to knit it to HTML to have it run so that your in-line code is correct.

Problem Header

```<code>---
title: "R Notebook"
output: html_notebook
---
</code>```

Solution Header

```<code>---
title: "R Notebook"
output:
    html_document: default
    html_notebook: default
---
</code>```

Other Notes

The previous solution has two problems. First, from the RMarkdown documentation, "Inline expressions do not take knitr options" (see end of http://rmarkdown.rstudio.com/lesson-4.html)

Second, the previous answer's YAML is not formatted properly forcing RStudio to actually knit the file. The proper formatting would generate the same problem you are having

```<code>---
title: "R Notebook"
output:
    html_notebook: default
---
</code>```

Body:
If the R code in Rmd file reuses the same variable name, the inline r expressions seem to return the last value of this variable regardless of the location of the inline expression. Is there away to avoid this behavior except for making sure the same variable name is not reused in different parts of the document?

The reproducible example

---
title: "R Notebook"
output: html_notebook
---

```{r}
df <- cars
nrow(df)
```

The dataset has `r nrow(df)` rows.

```{r}
df <- iris
nrow(df)
```

The dataset has `r nrow(df)` rows.

This produces the following output

I am using:
R version 3.3.2 (2016-10-31)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1

rmarkdown_1.4
knitr_1.15.1

Body:
The problem is that in your header, you are "previewing" your file, which does not actually run your code from scratch. You have to knit it to HTML to have it run so that your in-line code is correct.

Problem Header

---
title: "R Notebook"
output: html_notebook
---

Solution Header

---
title: "R Notebook"
output:
    html_document: default
    html_notebook: default
---

Other Notes

The previous solution has two problems. First, from the RMarkdown documentation, "Inline expressions do not take knitr options" (see end of http://rmarkdown.rstudio.com/lesson-4.html)

Second, the previous answer's YAML is not formatted properly forcing RStudio to actually knit the file. The proper formatting would generate the same problem you are having

---
title: "R Notebook"
output:
    html_notebook: default
---


问:
search string with array of values with PHP
I am trying to search a list of files and only perform work on the files that have names that contain a few values in an array.  I am hoping to not have to loop through the array each time I have a new filename.

ala-

```<code>$needle = array('blah', 'bleh');
foreach($file_list as $file)
{
    foreach($needle as $need)
       if(strstr($file, $need) !== false)
          {
             // do something...
          }
}
</code>```

I just need to know if one of the strings in the array is in the filename, not the location of the string.

I would like to use something similar to strstr() but it does not allow an array to be used as the needle.

i.e.-

```<code>if(strstr($haystack, array('blah', 'bleh')))
{
   // do something...
}
</code>```

I would prefer to stay away from regular expressions, it seems to be a sledge for a hammer's job.  any ideas?

答:
Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() instead as it will be faster.
http://php.net/manual/en/function.preg-match.php</p>

```<code>$needle = array('blah', 'bleh');

foreach ($file_list as $file) {

    $result = $this->searchStrpos($file, $needle);

        if ($result !== false) {

            // do something...
        }
    }

/**
 *
 * @param String $string String search
 * @param mixed $needle
 * @param Boolean $onlyFirst return true but
 * @return Boolean Return boolean for search
 */
private function searchStrpos($string, $needle, $onlyFirst = true) {
    if (is_array($needle)) {
        foreach ($needle as $item) {
            $result = strpos($string, $item);
            if ($result !== false && $onlyFirst) {
                break;
            }
        }
    } else {
        $result = strpos($string, $needle);
    }

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

ContentLicense: CC BY-SA 2.5

Body:
I am trying to search a list of files and only perform work on the files that have names that contain a few values in an array.  I am hoping to not have to loop through the array each time I have a new filename.

ala-

$needle = array('blah', 'bleh');
foreach($file_list as $file)
{
    foreach($needle as $need)
       if(strstr($file, $need) !== false)
          {
             // do something...
          }
}

I just need to know if one of the strings in the array is in the filename, not the location of the string.

I would like to use something similar to strstr() but it does not allow an array to be used as the needle.

i.e.-

if(strstr($haystack, array('blah', 'bleh')))
{
   // do something...
}

I would prefer to stay away from regular expressions, it seems to be a sledge for a hammer's job.  any ideas?

Body:
Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() instead as it will be faster.
http://php.net/manual/en/function.preg-match.php

$needle = array('blah', 'bleh');

foreach ($file_list as $file) {

    $result = $this->searchStrpos($file, $needle);

        if ($result !== false) {

            // do something...
        }
    }

/**
 *
 * @param String $string String search
 * @param mixed $needle
 * @param Boolean $onlyFirst return true but
 * @return Boolean Return boolean for search
 */
private function searchStrpos($string, $needle, $onlyFirst = true) {
    if (is_array($needle)) {
        foreach ($needle as $item) {
            $result = strpos($string, $item);
            if ($result !== false && $onlyFirst) {
                break;
            }
        }
    } else {
        $result = strpos($string, $needle);
    }

    return $result;
}


问:
Find shortest path in maze with landmines and limited lives
I've encountered a problem I'm having a bit of trouble solving. I am trying to write a program that solves an m by n grid maze that has landmines in it. The tricky part is that the player/maze runner has a L >= 1 number of lives, meaning they can step on a maximum of L - 1 landmines before they will die on the next landmine.

Further details:

-Each cell can be connected to any of the adjacent cells. All connections are two-way.

-We can assume that the maze has a correct path from start to end given the number of lives.

-The maze can contain loops or 'islands' where two paths from a given cell lead to the same cell.

My current thoughts:

I have tried a variety of approaches to this problem. There is the obvious brute force solution which involves traversing every possible path and taking the one with the lowest distance. But that is exponential time. I feel that there may be a Dijkstra-like or A*-like solution that leads to O(n + vlogv) time. Vanilla Dijkstra or A* do not lead to solutions for this problem since the state of the graph effectively changes depending on how it is traversed. I have also tried a variety of breadth first search + tracing back to start using priority queue. These schemes, after further investigation, can lead to exponential time.

The most promising idea I've come up with so far involves parsing each maze into a graph and performing a modified Dijkstra. Each cell with three or more connections will be a node. Each cell with two connections is part of a path. Each cell with one connection can be discarded. The end result is a graph. You then perform something similar to Dijkstra, but I have not yet clarified a solution.

I can only guess that this solution requires an algorithm that is efficient in the best case but can become exponential in the worst case.

答:
Consider the maze to be a graph with a node for every clear square, and an edge between each pair of connected squares.

Let N be the number of nodes in the graph.  Assign each edge a cost of N*k+1, where k is the number of land mines it touches (either 0, 1, or 2).  This ensures that moving over a landmine will cost 2N more than moving over a clear square.

Now use Dijkstra's algorithm to find the shortest path through the graph.


问:
C++ Any way to print maximum double (8 bytes) value with full precision without changing it to long long?
I have an issue when printing the value with 'cout'. I would like to see value "9223372036854775807" in console but I just keep on getting "9223372036854775800" and same happens with negative values. I also want user to enter this as a maximum value and want to keep decimal places.

--------------- these will be the minimum and maximum value

```<code>double al = scnd_num_min(num1, Oprt);
al = al * (-1);
double ah = scnd_num_max(num1, Oprt);
</code>```

-------------- and this is where I print these values

```<code>cout << "Please enter a value within a range of: " << "\n" << fixed << al;
cout << " and " << ah << " : ";
</code>```

And that is one function to get value:

```<code>    double scnd_num_max(double num1, char Oprt)
    {
    double max1 = 9223372036854775807;
    double max2 = 9223372036854775806;
    double min1 = -9223372036854775806;
    switch(Oprt)
    {
    case '+':
        if (num1 <= 0)
            return max1;
        else
            return (max1 - num1);
    case '-':
        if (num1 >= -1)
            return max1;
        else
            return ((max1 - (num1 * (-1)))+1);
    case '*':
        if ((num1 < min1) || (num1 > max2))
            return 1;
        else if (num1 == 0)
            return max2;
        else if (num1 > 0)
            return (max2 / num1);
        else
            return (max2 / (num1 * (-1)));
    case '/':
        return max2;
    }
}
</code>```

Pretty same is for negative value.

答:
A double is 64 bit wide, but it cannot hold every value that a long long (also 64bit) can hold, because a floating point number consists of a sign bit, an exponent and a mantissa. The mantissa for double is 52bit wide, so you can be sure that every 52bit (actually 53 because of the sign bit) wide integer can be stored without loss of precision in a double, for the rest you may loose precision.

edit: By the way, double max is 1.79769e+308, see this link

Body:
I have an issue when printing the value with 'cout'. I would like to see value "9223372036854775807" in console but I just keep on getting "9223372036854775800" and same happens with negative values. I also want user to enter this as a maximum value and want to keep decimal places.

--------------- these will be the minimum and maximum value

double al = scnd_num_min(num1, Oprt);
al = al * (-1);
double ah = scnd_num_max(num1, Oprt);

-------------- and this is where I print these values

cout << "Please enter a value within a range of: " << "\n" << fixed << al;
cout << " and " << ah << " : ";

And that is one function to get value:

    double scnd_num_max(double num1, char Oprt)
    {
    double max1 = 9223372036854775807;
    double max2 = 9223372036854775806;
    double min1 = -9223372036854775806;
    switch(Oprt)
    {
    case '+':
        if (num1 <= 0)
            return max1;
        else
            return (max1 - num1);
    case '-':
        if (num1 >= -1)
            return max1;
        else
            return ((max1 - (num1 * (-1)))+1);
    case '*':
        if ((num1 < min1) || (num1 > max2))
            return 1;
        else if (num1 == 0)
            return max2;
        else if (num1 > 0)
            return (max2 / num1);
        else
            return (max2 / (num1 * (-1)));
    case '/':
        return max2;
    }
}

Pretty same is for negative value.


问:
ready state problem with ajax and jquery
i have the following problem. I'm trying to load a set of tab loading dinamically with jQuery.
When I get the new contents (via POST) the tabs() function abort and don't build the
tabs. I'm using this functions:

```<code>$(document).ready(function() {
    var array_with_alias_id = $.getJSON("/getAliasForMatchAll/", null,
        function (data){
            array = data.aliases_id;
            load(array);
        });
    $("#next_left").click(function(){next_left()});

    //load(array_with_alias_id);
});

function next_left(){
    if(j >= array.length-1){
        var l = j
    } else {
        var l = j+=1;
    }
    $("#alias_id_left").val(list_left[l]);
    $("#merge_alias_id_left").val(list_left[l]);
    $.post("/visor/",{"alias_id":list_left[l],"position":"L"},
            function(data){
                $("#tabsL").html(data).ready(function(){
                    $("#tabsL").tabs();
                });
            });
}
</code>```

I think that my problem is an ajax problem and i have read this [0],
but i can't give with the solution.
The function next_left() it works only one time. I think that the document for
this function is ready, but when i load the tabs it doesnt work
(i think that tab call the method abort, because if i see the html with firebug
it change, but not all).

Any clue?

[0]http://docs.jquery.com/Tutorials:AJAX_and_Events

答:
Try replacing  $("#next_left").click(function(){next_left()}); with:

```<code>$("#next_left").live('click', function(){next_left()});
</code>```

Body:
i have the following problem. I'm trying to load a set of tab loading dinamically with jQuery.
When I get the new contents (via POST) the tabs() function abort and don't build the
tabs. I'm using this functions:

$(document).ready(function() {
    var array_with_alias_id = $.getJSON("/getAliasForMatchAll/", null,
        function (data){
            array = data.aliases_id;
            load(array);
        });
    $("#next_left").click(function(){next_left()});

    //load(array_with_alias_id);
});

function next_left(){
    if(j >= array.length-1){
        var l = j
    } else {
        var l = j+=1;
    }
    $("#alias_id_left").val(list_left[l]);
    $("#merge_alias_id_left").val(list_left[l]);
    $.post("/visor/",{"alias_id":list_left[l],"position":"L"},
            function(data){
                $("#tabsL").html(data).ready(function(){
                    $("#tabsL").tabs();
                });
            });
}

I think that my problem is an ajax problem and i have read this [0],
but i can't give with the solution.
The function next_left() it works only one time. I think that the document for
this function is ready, but when i load the tabs it doesnt work
(i think that tab call the method abort, because if i see the html with firebug
it change, but not all).

Any clue?

[0]http://docs.jquery.com/Tutorials:AJAX_and_Events

Body:
Try replacing  $("#next_left").click(function(){next_left()}); with:

$("#next_left").live('click', function(){next_left()});


问:
Is my if statement/code-test correct Swift
My instructor said that this code test should evaluate to:

```<code> parrotTrouble(isTalking: true, hour: 6) → true
 parrotTrouble(isTalking: true, hour: 7) → false
 parrotTrouble(isTalking: false, hour: 6) → false
</code>```

In xcode, mine is true, false, true.
With the code given, this seems true. I'm not sure, though. What am I doing wrong if anything?

Question:
"We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble."

```<code> func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {

    if hour < 7 {
        return true
    } else if hour > 20 {
        return true
    } else {
    return false
    }
}

parrotTrouble(isTalking: true, hour: 6)
parrotTrouble(isTalking: true, hour: 7)
parrotTrouble(isTalking: false, hour: 6)
</code>```

答:
You need to check isTalking as well as the hour:

Here's the real simple version:

```<code>func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {
    return isTalking && (hour < 7 || hour > 20)
}
</code>```

The longer version:

```<code>func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {
    if isTalking {
        if hour < 7 {
            return true
        } else if hour > 20 {
            return true
        }
    }
    return false
}
</code>```

Body:
My instructor said that this code test should evaluate to:

 parrotTrouble(isTalking: true, hour: 6) → true
 parrotTrouble(isTalking: true, hour: 7) → false
 parrotTrouble(isTalking: false, hour: 6) → false

In xcode, mine is true, false, true.
With the code given, this seems true. I'm not sure, though. What am I doing wrong if anything?

Question:
"We have a loud talking parrot. The "hour" parameter is the current hour time in the range 0..23. We are in trouble if the parrot is talking and the hour is before 7 or after 20. Return true if we are in trouble."

 func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {

    if hour < 7 {
        return true
    } else if hour > 20 {
        return true
    } else {
    return false
    }
}

parrotTrouble(isTalking: true, hour: 6)
parrotTrouble(isTalking: true, hour: 7)
parrotTrouble(isTalking: false, hour: 6)

Body:
You need to check isTalking as well as the hour:

Here's the real simple version:

func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {
    return isTalking && (hour < 7 || hour > 20)
}

The longer version:

func parrotTrouble(isTalking: Bool, hour: Int) -> Bool {
    if isTalking {
        if hour < 7 {
            return true
        } else if hour > 20 {
            return true
        }
    }
    return false
}


问:
copy a float texture with webgl2
I can no longer find any trace of copyTexImage2D in the specification of webgl2 : https://www.khronos.org/registry/webgl/specs/latest/2.0/

A few months ago I had asked the question of how to make a float-texture copy. With webgl version 1.0 this was not possible with copyTexImage2D (float type is not supported)
So I made a texture copy by building a simple shader.

I imagined that the restriction on the float32 type was lifted with webgl2. But I do not find any occurrence of the word "copyTexImage2D" in the specification of webgl 2.

How does it work? The specification of webgl2 gives only the novelties or new polymorphism functions since webgl1 ?

In short, with webgl2,  is a more efficient method to copy a texture ?

(In my slow, very slow, understanding of webgl2 I have not yet addressed the interesting novelty of feedback)

答:
WebGL2s spec just adds to WebGL1. From the WebGL2 spec right near the beginning

This document should be read as an extension to the WebGL 1.0 specification. It will only describe the differences from 1.0.

Similarly it also says

The remaining sections of this document are intended to be read in conjunction with the OpenGL ES 3.0 specification (3.0.4 at the time of this writing, available from the Khronos OpenGL ES API Registry). Unless otherwise specified, the behavior of each method is defined by the OpenGL ES 3.0 specification.

So, copyTexImage2D is still there.

Your blitFramebuffer solution works though

Title: copy a float texture with webgl2


问:
Installing Python via Ansible when no Python version exists on target machine
I am attempting to install Python onto a virtual machine (let refer to this as the 'target machine') with ansible-playbook. The target machine has no version of Python installed at all (lightweight Unix version)

From my understanding, most ansible modules will require the target machine to have Python installed on it. However, the raw module does not.

I can't seem to even get the most basic command to work with the raw module, it seems that ansirble is still looking for Python on the target machine. If I manually ssh into the target machine and install Python, then the ansible-playbook begins to work.

Error message:

```<code>fatal: [dev]: FAILED! =>
{"changed": false, "failed": true,
 "module_stderr": "Shared connection to 192.168.99.100 closed.\r\n",
 "module_stdout": "/bin/sh: /usr/bin/python: not found\r\n",
 "msg": "MODULE FAILURE", "rc": 0}
</code>```

file /host_vars/dev.yml:

```<code>#NOTE: I can manually ssh in with the details without a problem
ansible_ssh_port: 22
ansible_user: docker
ansible_ssh_host: 192.168.99.100
ansible_ssh_private_key_file: ~/.docker/machine/machines/default/id_rsa
</code>```

file playbook.yml:

```<code>- hosts: all
  tasks:
  - name: test the raw module
    raw: echo "Hello World"
</code>```

file hosts:

```<code>dev
</code>```

Command I ran:

```<code>ansible-playbook -i ./hosts ./playbook.yml
</code>```

Why is the raw command looking for Python?

How can I run command with Ansible without the target machine having Python?

答:
It's not the raw module, but fact-gathering that tries to run Python.

Add:

```<code>gather_facts: no
</code>```

Body:
I am attempting to install Python onto a virtual machine (let refer to this as the 'target machine') with ansible-playbook. The target machine has no version of Python installed at all (lightweight Unix version)

From my understanding, most ansible modules will require the target machine to have Python installed on it. However, the raw module does not.

I can't seem to even get the most basic command to work with the raw module, it seems that ansirble is still looking for Python on the target machine. If I manually ssh into the target machine and install Python, then the ansible-playbook begins to work.

Error message:

fatal: [dev]: FAILED! =>
{"changed": false, "failed": true,
 "module_stderr": "Shared connection to 192.168.99.100 closed.\r\n",
 "module_stdout": "/bin/sh: /usr/bin/python: not found\r\n",
 "msg": "MODULE FAILURE", "rc": 0}

file /host_vars/dev.yml:

#NOTE: I can manually ssh in with the details without a problem
ansible_ssh_port: 22
ansible_user: docker
ansible_ssh_host: 192.168.99.100
ansible_ssh_private_key_file: ~/.docker/machine/machines/default/id_rsa

file playbook.yml:

- hosts: all
  tasks:
  - name: test the raw module
    raw: echo "Hello World"

file hosts:

dev

Command I ran:

ansible-playbook -i ./hosts ./playbook.yml

Why is the raw command looking for Python?

How can I run command with Ansible without the target machine having Python?

Body:
It's not the raw module, but fact-gathering that tries to run Python.

Add:

gather_facts: no


问:
Android: Problems with adjusting view size in an ImageButton
I'm trying something that should be simple, an imageButton and some text that says something about it. My problem is, the view of the imageButton is bigger than the image itself. I'm certain that the actual image is not like this (I've tried with several images and the result is the same). By searching online, the solution I've found is to insert the attribute "adjustViewBounds". That seemed reasonable but it didn't work. Here I leave my code and an image of how the result looks.

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center|top">

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:background="@android:color/transparent"
        android:scaleType="fitXY"
        android:scaleX="0.2"
        android:scaleY="0.2"
        android:src="@drawable/icon1"
        android:padding="0dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DEFAULT!"
        android:textSize="20sp"
        />

</LinearLayout>
</code>```

image

答:
The problem is using scaleX and scaleY to adjust the size. The button changes it's visible size, but the rest of the layout acts as if it were the original full scale.

I'd suggest using a different method of defining the size, for example:

```<code>    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:background="@android:color/transparent"
        android:scaleType="fitXY"
        android:src="@drawable/icon1"
        android:padding="0dp"/>
</code>```

Body:
I'm trying something that should be simple, an imageButton and some text that says something about it. My problem is, the view of the imageButton is bigger than the image itself. I'm certain that the actual image is not like this (I've tried with several images and the result is the same). By searching online, the solution I've found is to insert the attribute "adjustViewBounds". That seemed reasonable but it didn't work. Here I leave my code and an image of how the result looks.

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center|top">

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:background="@android:color/transparent"
        android:scaleType="fitXY"
        android:scaleX="0.2"
        android:scaleY="0.2"
        android:src="@drawable/icon1"
        android:padding="0dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DEFAULT!"
        android:textSize="20sp"
        />

</LinearLayout>

image

Body:
The problem is using scaleX and scaleY to adjust the size. The button changes it's visible size, but the rest of the layout acts as if it were the original full scale.

I'd suggest using a different method of defining the size, for example:

    <ImageButton
        android:id="@+id/imageButton"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:background="@android:color/transparent"
        android:scaleType="fitXY"
        android:src="@drawable/icon1"
        android:padding="0dp"/>


问:
How can I use this UTF 8 shape in css :before { content: }?
I am looking at some shapes here: https://www.w3schools.com/charsets/ref_utf_geometric.asp

For example, if I want to use this one:

◹  9721    25F9        UPPER RIGHT TRIANGLE, how do I do that?

Do i just copy the icon and put it in the css file, or do I use the hex/dec code?

Thanks

答:
You can simply escape the unicode value, so that you would not have to save the file in UTF-8 format. Remember to include <meta charset="utf-8"> in your HTML file's head. The meta tag will let the user's browser know that we are working with UTF-8. You could also put the actual character (◹) as the content value, however you would need to ensure that you save the file in UTF-8 format, as well as including the meta tag in your HTML's head section.

span::before {
 content:'\25F9';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>Test</span></code>```

Body:
You can simply escape the unicode value, so that you would not have to save the file in UTF-8 format. Remember to include <meta charset="utf-8"> in your HTML file's head. The meta tag will let the user's browser know that we are working with UTF-8. You could also put the actual character (◹) as the content value, however you would need to ensure that you save the file in UTF-8 format, as well as including the meta tag in your HTML's head section.

span::before {
 content:'\25F9';
}

<span>Test</span>


问:
An app that made with sdk 4.0.1 doesn't install on device with os 4.2
I made an app with ios sdk 4.0.1 but now i want to install it from xcode on ipod touch with os 4.2 but says

No provisioned iPhone OS device is
  connected.

答: Open up organizer, with your device plugged in, and select it in the list on the left. Then once selected, click "Use for Development." This should fix you right up.</p>


问:
Javascript - React - Arrow Function Usage Understanding
I'm trying to wrap my head around how this is coded

https://github.com/ReactTraining/react-router/blob/dc2149ec0c63bfc95b71e40c81431e34cfbfeda9/packages/react-router-dom/modules/NavLink.js#L8

```<code>const NavLink = ({
  to,
  exact,
  strict,
  activeClassName,
  className,
  activeStyle,
  style,
  isActive: getIsActive,
  ...rest
}) => (
  <Route
    path={typeof to === 'object' ? to.pathname : to}
    exact={exact}
    strict={strict}
    children={({ location, match }) => {
      const isActive = !!(getIsActive ? getIsActive(match, location) : match)

      return (
        <Link
          to={to}
          className={isActive ? [ activeClassName, className ].join(' ') : className}
          style={isActive ? { ...style, ...activeStyle } : style}
          {...rest}
        />
      )
    }}
  />
)
</code>```

What's going on here? Is this defining a function that returned a JSX element? The only thing that is throwing me is the JSX element being wrapped in parentheses ()

What is going on in the first part where there is isActive: getIsActive?

I was looking at http://es6-features.org/#ExpressionBodies and couldn't find a direct example.

I was trying to figure out how to use the isActive method of router and couldn't parse this code.

答:
What you are seeing in the function arguments is object destructuring. In react whenever you make a stateless component it has props passed in as an argument to the stateless function.
isActive: getIsActive is saying grab the property isActive from the props object and set it to a variable called getIsActive which is something you can do with object destructuring.
THe rest of it is just pulling the specific properties we want from the props object and turning them into their own variables. This is great for declaring what props a component is going to consume. ...rest
will create a variable called rest which will be an object with the remaining properties that weren't declared previously.

you can find more information on Destructuring here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

The destructuring assignment syntax is a JavaScript expression that
  makes it possible to extract data from arrays or objects into distinct
  variables.

the parenthesis are there since the jsx spans multiple lines vs being on one line and since we are immediately returning and not doing any assignment in the function we don't need to use blocks around the function body.

Body:
I'm trying to wrap my head around how this is coded

https://github.com/ReactTraining/react-router/blob/dc2149ec0c63bfc95b71e40c81431e34cfbfeda9/packages/react-router-dom/modules/NavLink.js#L8

const NavLink = ({
  to,
  exact,
  strict,
  activeClassName,
  className,
  activeStyle,
  style,
  isActive: getIsActive,
  ...rest
}) => (
  <Route
    path={typeof to === 'object' ? to.pathname : to}
    exact={exact}
    strict={strict}
    children={({ location, match }) => {
      const isActive = !!(getIsActive ? getIsActive(match, location) : match)

      return (
        <Link
          to={to}
          className={isActive ? [ activeClassName, className ].join(' ') : className}
          style={isActive ? { ...style, ...activeStyle } : style}
          {...rest}
        />
      )
    }}
  />
)

What's going on here? Is this defining a function that returned a JSX element? The only thing that is throwing me is the JSX element being wrapped in parentheses ()

What is going on in the first part where there is isActive: getIsActive?

I was looking at http://es6-features.org/#ExpressionBodies and couldn't find a direct example.

I was trying to figure out how to use the isActive method of router and couldn't parse this code.


问:
sort and display names on different lines in ascending order
My professor wants us to Write a JavaScript code that prompts the user to enter 3 names (one at a time). The program should
sort and display the names on different lines in ascending order.

This is what I have so far

```<code><html>
<head>
  <title>Day 2 - Example 2</title>
</head>
<body>
<center>
 <script language="javascript">
   var na1,na2,na3;
   na1=prompt("Enter your first name:","");
   na2=prompt("Enter your second name:","");
   na3=prompt("Enter your third name","");
 </script>
 </center>
</body>
</html>
</code>```

答:
You could store the names entered by the user into an array and then use sort():

function nameSorting() {
    var names = [];
    var name1 = prompt("Please enter the first name");
    names[0] = name1;
    var name2 = prompt("Please enter the second name");
    names[1] = name2;
    var name3 = prompt("Please enter the second name");
    names[2] = name3;
    names.sort();

    document.getElementById("firstName").innerHTML = names[0];
    document.getElementById("secondName").innerHTML = names[1];
    document.getElementById("lastName").innerHTML = names[2];
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>

<p>Click the button to to enter 3 names (one at a time). The program will sort and display the names on different lines in ascending order.</p>

<button onclick="nameSorting()">Enter names</button>

<p id="firstName"></p>
<p id="secondName"></p>
<p id="lastName"></p>

</body>
</html></code>```

Body:
My professor wants us to Write a JavaScript code that prompts the user to enter 3 names (one at a time). The program should
sort and display the names on different lines in ascending order.

This is what I have so far

  <title>Day 2 - Example 2</title>

Body:
You could store the names entered by the user into an array and then use sort():

function nameSorting() {
    var names = [];
    var name1 = prompt("Please enter the first name");
    names[0] = name1;
    var name2 = prompt("Please enter the second name");
    names[1] = name2;
    var name3 = prompt("Please enter the second name");
    names[2] = name3;
    names.sort();

    document.getElementById("firstName").innerHTML = names[0];
    document.getElementById("secondName").innerHTML = names[1];
    document.getElementById("lastName").innerHTML = names[2];
}

<!DOCTYPE html>
<html>
<body>

<p>Click the button to to enter 3 names (one at a time). The program will sort and display the names on different lines in ascending order.</p>

<button onclick="nameSorting()">Enter names</button>

<p id="firstName"></p>
<p id="secondName"></p>
<p id="lastName"></p>

</body>
</html>


问:
AlarmManager not working in several devices
My app uses AlarmManager and it has been working since 4 years ago. But I noticed it started failing in some devices.

I'm pretty sure code is right (I'm using WakefulBroadcastReceiver, and setExactAndAllowWhileIdle for devices with Doze) because it's working perfectly on Nexus devices, but it fails in devices of some manufacturers (Huawei, Xiaomi...).

Huawei devices, for example, have a kind of battery manager that kill apps, and when an app is killed, scheduled alarms are cancelled. So setting an app as "protected" in Huawei battery manager solves the problem.

But recently I noticed it's not working with more devices: Xiaomi, Samsung (maybe it's related to the new "Smart Manager"?)... It seems that this behavior is becoming a standard: to kill background apps.

Anyone know anything about it? Any way to ensure alarm is fired?

EDIT: This problem is caused by "battery savers" added by different manufacturers. More info here: https://dontkillmyapp.com/

答:
I were looking for an answer and after several hours I found this:

https://stackoverflow.com/a/35220476/3174791

In resume is way to know if your app was killed by 'Protected apps' and this only works on Huawei devices. let me know if there is any solution for other devices (Samsung,Sony,Xiaomi, etc).

ContentLicense: CC BY-SA 4.0


问:
What's really more performant? Haskell or OCaml
I spent the last 18 months getting the grip of functional programming, starting with learning OCaml and for some weeks now Haskell. Now I want to take the next step and implement some actual application: A simple realtime terrain editor. I've written numerous realtime terrain rendering engines, so this is a familiar topic. And the used recursive algorithms and data structures seem very fit for a functional implementation.

With this being a realtime application I'm naturally looking for the best performance I can get. Now some proponents of OCaml quite frequently complain about Haskell being slow compared to OCaml or F#. But according to the The Computer Language Benchmarks Game Haskell oftenly beats OCaml, if only by rather small fractions. There remains the problem, that this benchmark takes only very specific samples.

The right thing to do would be to, of course, implement the program in both languages and compare them, but I simply don't want to do double the work.

But maybe other people did comparable applications in OCaml and Haskell and give some statistics?

答:
By all accounts, both OCaml and Haskell have sufficiently performant compilers and runtimes for almost anything. Picking between them on the basis of pure performance seems silly to me. You've come this far -- moving away from the obviously most low-level and performant languages (C, C++, etc.) in the name of clearer, more succinct, more expressive, higher-level code. So why, when the performance differences involved are much smaller, switch to that criteria now?

I'd go with some broader criteria -- if you want pervasive parallelism, then Haskell's the better choice. If you want genuinely pervasive mutation, then OCaml is better.

If you want only very coarse parallelism at best, and you intend to stick with mostly functional structures, then pick based on something else, like syntax (I think Haskell is much nicer here, but that's subjective) or available libraries (Haskell wins on quantity/availability, but OCaml might edge it out in the graphics department nonetheless).

I don't think you'll go wrong either way


问:
Does node.js compile JavaScript?
Node.js uses V8 and it compiles the JavaScript as an optimization strategy.

So, the JavaScript running at the server side via node.js / V8 is compiled or interpreted?

答:
V8 engine compiles javascript to a sequence of machine code instructions, one function at a time (usually, functions are not compiled until the first call).

V8 parses the code and extracts an AST (abstract syntax tree),
performs scope analysis in order to understand to which context a symbol refers to, and translates it to machine code instructions.

As you mentioned, V8 is highly focused on performance: besides the full compiler that compiles each function, V8 consists of extra compiler which is responsible for optimizing blocks that identified as frequently used (Known as the Crankshaft)

So no, there's no interpretation of javascript code, but translation and execution of a machine code.

Title: Does node.js compile JavaScript?


问:
PHP shell_exec returning string with no line breaks
I am executing a shell script from PHP with shell_exec like this:

```<code>$output = shell_exec('./intnacstat.sh "'.$ip.'" 2>&1');
</code>```

intnacstat.sh result is:

```<code>interface GigabitEthernet0/8
 description ISE dot1x Port
 switchport access vlan 70
 switchport trunk encapsulation dot1q
 switchport trunk native vlan 70
 switchport trunk allowed vlan 256
 switchport mode trunk
 authentication event fail action next-method
 authentication host-mode multi-host
 authentication open
 authentication order dot1x mab
 authentication priority dot1x mab
 authentication port-control auto
 authentication periodic
 authentication timer reauthenticate server
 authentication timer inactivity server
 authentication violation restrict
 mab
</code>```

So every command is on separate line.

But when I echo $output on PHP everything is on a single line,
basically unreadable:

"show run interface G0/8 Building configuration... Current configuration : 767 bytes ! interface GigabitEthernet0/8 description ISE dot1x Port switchport access vlan 70 switchport trunk encapsulation dot1q switchport trunk native vlan 70 switchport trunk allowed vlan 256 switchport mode trunk authentication event fail action next-method authentication host-mode multi-host authentication open authentication order dot1x mab authentication priority dot1x mab authentication port-control auto authentication periodic authentication timer reauthenticate server authentication timer inactivity server authentication

Can someone tell me how to echo the $output to also add line brakes at the end of the command.
Or any other way this can be done.

答:
Try echo "```". $output."```";

Tip: Use the ``` tags when displaying text with unusual formatting (includes line breaks and when printing arrays using print_r($arr))

Body:
I am executing a shell script from PHP with shell_exec like this:

$output = shell_exec('./intnacstat.sh "'.$ip.'" 2>&1');

intnacstat.sh result is:

interface GigabitEthernet0/8
 description ISE dot1x Port
 switchport access vlan 70
 switchport trunk encapsulation dot1q
 switchport trunk native vlan 70
 switchport trunk allowed vlan 256
 switchport mode trunk
 authentication event fail action next-method
 authentication host-mode multi-host
 authentication open
 authentication order dot1x mab
 authentication priority dot1x mab
 authentication port-control auto
 authentication periodic
 authentication timer reauthenticate server
 authentication timer inactivity server
 authentication violation restrict
 mab

So every command is on separate line.

But when I echo $output on PHP everything is on a single line,
basically unreadable:

"show run interface G0/8 Building configuration... Current configuration : 767 bytes ! interface GigabitEthernet0/8 description ISE dot1x Port switchport access vlan 70 switchport trunk encapsulation dot1q switchport trunk native vlan 70 switchport trunk allowed vlan 256 switchport mode trunk authentication event fail action next-method authentication host-mode multi-host authentication open authentication order dot1x mab authentication priority dot1x mab authentication port-control auto authentication periodic authentication timer reauthenticate server authentication timer inactivity server authentication

Can someone tell me how to echo the $output to also add line brakes at the end of the command.
Or any other way this can be done.

Body:
Try echo "<pre>". $output."</pre>";

Tip: Use the <pre> tags when displaying text with unusual formatting (includes line breaks and when printing arrays using print_r($arr))


问:
Is there a way to trigger an event when other users update to a table?
Is there a way to trigger an event when other user(s) in network either update or insert a record into SQL table?

I could read the table from the database every few seconds then compare the data to see if there are differences, but that would seem resource intensive.

Perhaps, I should have mentioned I'm using C#/WinForm and SQL Database, although I've tagged it.

I've already looked at SQL Trigger, but doesn't it also require reading the trigger table, which can be resource intensive?  I was looking more of small program/service running in background that when users makes changes to the database, trigger it.  Foreground app can then check the service to see if change was made.  Am I thinking overly complicated?

答:
After reading up on SqlDependency and Trigger, they both seems to be relying on periodically polling the database.  I think this can eventually hammer the performance.  So I've decided to study code on Windows Services.  Hoping to write Windows Service that I can store information about record(s) just saved.  And than I can poll it to see which table I need to reload.  I hope I'm not over complicating things....

Thanks, +1 everyone for your replies.


问:
how to read from file and add to object data?
```<code>17  5
12  8
15  22
17  11
33  21
43  15
15  4
44  35
23  19
10  23
55  39
8   6
21  9
20  28
20  13
45  29
18  16
21  19
68  55
10  16
33  54
3   1
5   9
</code>```

I am trying to read in input.txt file that looks like input above but the problem is that the program only reads in the last line from the text file.

Here is my code:

```<code>import java.io.FileNotFoundException;
import java.io.*;
import java.io.IOException;
import java.util.*;
import java.util.Scanner;

/**
 *
 */
public class ReadIn {

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

    //List<Integer> value = new ArrayList<Integer>();
    //List<Integer> weight = new ArrayList<Integer>();
    FileReader readFile = new FileReader ("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);
    Scanner keyboard = new Scanner(System.in);
    //List<Items> items = new ArrayList<Items>();

    Items[] items= new Items[23];//this only creates references that are set to their default value null which throws a null exception
    for(int i =0 ; i <items.length; i++) {//fixes null exception

        items[i] = new Items();//fully creates the objects

        while (input.hasNext()) {//read in file input to object data
            items[i].setValue(input.nextInt());
            items[i].setWeight(input.nextInt());
            items[i].setId(i);
        }
    }
    input.close();
    input.reset();
    System.out.println("What is the max capacity for the knapsack? ");
    Integer maxCapacity = keyboard.nextInt();
    System.out.println(maxCapacity);
    int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
    printArray(items);

}
    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            x[i] = new Items();
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }

}
</code>```

Thanks for the help I am stuck!!
I have also attached the Items class that i am trying to use

```<code>    public class Items {
        private Integer value ;
        private Integer weight;
        private Integer Id;

        public Items(){
            this.value = 0;
            this.weight = 0;
            this.Id =0;
        }

        public Items(Integer v, Integer w, Integer ID){
            this.value = v;
            this.weight = w;
            this.Id = ID;
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public Integer getId() {
            return Id;
        }

        public void setId(Integer id) {//sets id
            Id = id;
        }
    }
</code>```

This is the end of the code

答:
I would remove the for-loop, use a list instead of an array and read each item and add it to the list:

```<code>public static void main(String[] args) throws FileNotFoundException {
    FileReader readFile = new FileReader("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);

    List<Item> items= new LinkedList<>();
    int i = 0;
    while (input.hasNext()) {
        Item item = new Item();
        item.setValue(input.nextInt());
        item.setWeight(input.nextInt());
        item.setId(i);
        items.add(item);
        i++;
    }
    input.close();
    input.reset();
    //...
}
</code>```

Two more comments:

class Items should be called Item

you should consider adding a toString() method to class Item this way it'll be easy to print

Body:
17  5
12  8
15  22
17  11
33  21
43  15
15  4
44  35
23  19
10  23
55  39
8   6
21  9
20  28
20  13
45  29
18  16
21  19
68  55
10  16
33  54
3   1
5   9

I am trying to read in input.txt file that looks like input above but the problem is that the program only reads in the last line from the text file.

Here is my code:

import java.io.FileNotFoundException;
import java.io.*;
import java.io.IOException;
import java.util.*;
import java.util.Scanner;

/**
 *
 */
public class ReadIn {

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

    //List<Integer> value = new ArrayList<Integer>();
    //List<Integer> weight = new ArrayList<Integer>();
    FileReader readFile = new FileReader ("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);
    Scanner keyboard = new Scanner(System.in);
    //List<Items> items = new ArrayList<Items>();

    Items[] items= new Items[23];//this only creates references that are set to their default value null which throws a null exception
    for(int i =0 ; i <items.length; i++) {//fixes null exception

        items[i] = new Items();//fully creates the objects

        while (input.hasNext()) {//read in file input to object data
            items[i].setValue(input.nextInt());
            items[i].setWeight(input.nextInt());
            items[i].setId(i);
        }
    }
    input.close();
    input.reset();
    System.out.println("What is the max capacity for the knapsack? ");
    Integer maxCapacity = keyboard.nextInt();
    System.out.println(maxCapacity);
    int[] maxWeight = new int[maxCapacity];//creates int array so we can use the index as the maxWeight as the number of fields
    printArray(items);

}
    public static void printArray(Items[] x) {

        for (int i = 0; i < x.length; i++) {
            x[i] = new Items();
            System.out.println(x[i].getValue() + " " + x[i].getWeight() + " " + x[i].getId() + " ");
        }
    }

}

Thanks for the help I am stuck!!
I have also attached the Items class that i am trying to use

    public class Items {
        private Integer value ;
        private Integer weight;
        private Integer Id;

        public Items(){
            this.value = 0;
            this.weight = 0;
            this.Id =0;
        }

        public Items(Integer v, Integer w, Integer ID){
            this.value = v;
            this.weight = w;
            this.Id = ID;
        }

        public Integer getValue() {
            return value;
        }

        public void setValue(Integer value) {
            this.value = value;
        }

        public Integer getWeight() {
            return weight;
        }

        public void setWeight(Integer weight) {
            this.weight = weight;
        }

        public Integer getId() {
            return Id;
        }

        public void setId(Integer id) {//sets id
            Id = id;
        }
    }

This is the end of the code

Body:
I would remove the for-loop, use a list instead of an array and read each item and add it to the list:

public static void main(String[] args) throws FileNotFoundException {
    FileReader readFile = new FileReader("C:\\Users\\owner\\IdeaProjects\\knapsack\\src\\input");
    BufferedReader br = new BufferedReader(readFile);
    Scanner input = new Scanner(br);

    List<Item> items= new LinkedList<>();
    int i = 0;
    while (input.hasNext()) {
        Item item = new Item();
        item.setValue(input.nextInt());
        item.setWeight(input.nextInt());
        item.setId(i);
        items.add(item);
        i++;
    }
    input.close();
    input.reset();
    //...
}

Two more comments:

class Items should be called Item

you should consider adding a toString() method to class Item this way it'll be easy to print


问:
SQL Server join and insert data
My name is Thorsten and I'm new to SQL Server. Now I am facing a problem after setting a join... I joined two tables, and it worked so far, but I don't have enough knowledge to proceed.

Here is table1:

```<code>| Item | validDate  | Price |
| ---- | ---------  | ----- |
| A    | 01.01.2017 | 100   |
| A    | 31.03.2017 | 100   |
| A    | 01.04.2017 | 120   |
| A    | 31.07.2017 | 120   |
</code>```

Now I want to create a table that includes a dataset for the gap in table1:

```<code>| Item | validDate  | Price |
| ---- | ---------  | ----- |
| A    | 01.01.2017 | 100   |
| A    | 28.02.2017 | 100   |
| A    | 31.03.2017 | 120   |
</code>```

... and so on.

My idea was to set a join from table1 to a date table, were every month end is included. But I have to insert the gap as well by creating a new dataset. With what code I'll be able to solve this issue?

As mentioned - I'm a beginner, so I hope I was able to describe my problem.

Thanks in advance for help!

答:
I'm not sure if I understand you correctly but to fill the 'gaps' in your table you need to insert last days of each month. Here's the script that will do that for you. Since I'm fairly new in SQL too, this might not be the best solution, but worked for me. Please not that it will not insert records with dates that already exist in your validDate column:

```<code>declare @dateVar date = '2017-01-01' -- script will start calculating last day of the month from this date. DON'T modify the day value
declare @yearVar int = '2017' -- script insert months until the end of the year in this variable

declare @endDates table
(
item nvarchar(1),
endOfMonthDate date
)

while datepart(year, @dateVar) = @yearVar
begin
insert into @endDates
(item, endOfMonthDate)
values (
'A',
dateadd(day, -1, dateadd(month, 1, @dateVar))
)
set @dateVar = dateadd(month, 1, @dateVar)
end

insert into dbo.table1
(Item, validDate)
(
select item, endOfMonthDate
from @endDates
where endOfMonthDate not in (
select validDate
from table1)
)
</code>```

Now, updating the records with the correct prices will be a little tricky. First we set up the Price for the last days of each month based on the price from the beginning of the month.

```<code>update dbo.table1
set table1.Price = t2.Price
from table1
left join table1 as t2
on month(table1.validDate) = MONTH(t2.validDate)
</code>```

And then, we update the rest records that don't have prices with values from previous months:

```<code>declare @loopVar int = 0
declare @nullsNumb int = (select sum(case when table1.Price is null then 1 else 0 end) from table1) --calculates number of nulls in the Price column

while @loopVar < @nullsNumb --not so great solution that inserts previous month's price to every record that doesn't have any price at this moment
begin
update dbo.table1
set table1.Price = t2.Price
from table1
left join table1 as t2
on month(table1.validDate) = MONTH(t2.validDate) + 1
where table1.Price is null
set @loopVar = @loopVar + 1
end
</code>```

Here's how the data in table1 look now when ordered by validDate:

```<code>Item    validDate   Price
A           2017-01-01  100
A           2017-01-31  100
A           2017-02-28  100
A           2017-03-31  100
A           2017-04-01  120
A           2017-04-30  120
A           2017-05-31  120
A           2017-06-30  120
A           2017-07-31  120
A           2017-08-31  120
A           2017-09-30  120
A           2017-10-31  120
A           2017-11-30  120
A           2017-12-31  120
</code>```

Let me know if I was able to help.

Title: SQL Server join and insert data

Body:
My name is Thorsten and I'm new to SQL Server. Now I am facing a problem after setting a join... I joined two tables, and it worked so far, but I don't have enough knowledge to proceed.

Here is table1:

| Item | validDate  | Price |
| ---- | ---------  | ----- |
| A    | 01.01.2017 | 100   |
| A    | 31.03.2017 | 100   |
| A    | 01.04.2017 | 120   |
| A    | 31.07.2017 | 120   |

Now I want to create a table that includes a dataset for the gap in table1:

| Item | validDate  | Price |
| ---- | ---------  | ----- |
| A    | 01.01.2017 | 100   |
| A    | 28.02.2017 | 100   |
| A    | 31.03.2017 | 120   |

... and so on.

My idea was to set a join from table1 to a date table, were every month end is included. But I have to insert the gap as well by creating a new dataset. With what code I'll be able to solve this issue?

As mentioned - I'm a beginner, so I hope I was able to describe my problem.

Thanks in advance for help!

Body:
I'm not sure if I understand you correctly but to fill the 'gaps' in your table you need to insert last days of each month. Here's the script that will do that for you. Since I'm fairly new in SQL too, this might not be the best solution, but worked for me. Please not that it will not insert records with dates that already exist in your validDate column:

declare @dateVar date = '2017-01-01' -- script will start calculating last day of the month from this date. DON'T modify the day value
declare @yearVar int = '2017' -- script insert months until the end of the year in this variable

declare @endDates table
(
item nvarchar(1),
endOfMonthDate date
)

while datepart(year, @dateVar) = @yearVar
begin
insert into @endDates
(item, endOfMonthDate)
values (
'A',
dateadd(day, -1, dateadd(month, 1, @dateVar))
)
set @dateVar = dateadd(month, 1, @dateVar)
end

insert into dbo.table1
(Item, validDate)
(
select item, endOfMonthDate
from @endDates
where endOfMonthDate not in (
select validDate
from table1)
)

Now, updating the records with the correct prices will be a little tricky. First we set up the Price for the last days of each month based on the price from the beginning of the month.

update dbo.table1
set table1.Price = t2.Price
from table1
left join table1 as t2
on month(table1.validDate) = MONTH(t2.validDate)

And then, we update the rest records that don't have prices with values from previous months:

declare @loopVar int = 0
declare @nullsNumb int = (select sum(case when table1.Price is null then 1 else 0 end) from table1) --calculates number of nulls in the Price column

while @loopVar < @nullsNumb --not so great solution that inserts previous month's price to every record that doesn't have any price at this moment
begin
update dbo.table1
set table1.Price = t2.Price
from table1
left join table1 as t2
on month(table1.validDate) = MONTH(t2.validDate) + 1
where table1.Price is null
set @loopVar = @loopVar + 1
end

Here's how the data in table1 look now when ordered by validDate:

Item    validDate   Price
A           2017-01-01  100
A           2017-01-31  100
A           2017-02-28  100
A           2017-03-31  100
A           2017-04-01  120
A           2017-04-30  120
A           2017-05-31  120
A           2017-06-30  120
A           2017-07-31  120
A           2017-08-31  120
A           2017-09-30  120
A           2017-10-31  120
A           2017-11-30  120
A           2017-12-31  120

Let me know if I was able to help.


问:
C# Method overload resolution not selecting concrete generic override
This complete C# program illustrates the issue:

```<code>public abstract class Executor<T>
{
    public abstract void Execute(T item);
}

class StringExecutor : Executor<string>
{
    public void Execute(object item)
    {
        // why does this method call back into itself instead of binding
        // to the more specific "string" overload.
        this.Execute((string)item);
    }

    public override void Execute(string item) { }
}

class Program
{
    static void Main(string[] args)
    {
        object item = "value";
        new StringExecutor()
            // stack overflow
            .Execute(item);
    }
}
</code>```

I ran into a StackOverlowException that I traced back to this call pattern where I was trying to forward calls to a more specific overload. To my surprise, the invocation was not selecting the more specific overload however, but calling back into itself. It clearly has something to do with the base type being generic, but I don't understand why it wouldn't select the Execute(string) overload.

Does anyone have any insight into this?

The above code was simplified to show the pattern, the actual structure is a bit more complicated, but the issue is the same.

答:
Looks like this is mentioned in the C# specification 5.0, 7.5.3 Overload Resolution:

Overload resolution selects the function member to invoke in the following distinct contexts within C#:

Invocation of a method named in an invocation-expression (§7.6.5.1).

Invocation of an instance constructor named in an    object-creation-expression (§7.6.10.1).

Invocation of an indexer accessor through an element-access (§7.6.6).

Invocation of a predefined or user-defined operator referenced in an    expression (§7.3.3 and §7.3.4).

Each of these contexts defines the set of candidate function members
  and the list of arguments in its own unique way, as described in
  detail in the sections listed above. For example, the set of
  candidates for a method invocation does not include methods marked
  override (§7.4), and methods in a base class are not candidates if any
  method in a derived class is applicable (§7.6.5.1).

When we look at 7.4:

A member lookup of a name N with K type parameters in a type T is processed as follows:

• First, a set of accessible members named N is determined:

If T is a type parameter, then the set is the union of the sets of

  accessible members named N in each of the types specified as a primary constraint or secondary constraint (§10.1.5) for T, along with the set of accessible members named N in object.

Otherwise, the set consists of all accessible (§3.5) members named N in T, including inherited members and the accessible membersnamed N in object. If T is a constructed type, the set of members
  is obtained    by substituting type arguments as described in §10.3.2.
  Members that    include an override modifier are excluded from the set.

If you remove override the compiler picks the Execute(string) overload when you cast the item.

Body:
This complete C# program illustrates the issue:

public abstract class Executor<T>
{
    public abstract void Execute(T item);
}

class StringExecutor : Executor<string>
{
    public void Execute(object item)
    {
        // why does this method call back into itself instead of binding
        // to the more specific "string" overload.
        this.Execute((string)item);
    }

    public override void Execute(string item) { }
}

class Program
{
    static void Main(string[] args)
    {
        object item = "value";
        new StringExecutor()
            // stack overflow
            .Execute(item);
    }
}

I ran into a StackOverlowException that I traced back to this call pattern where I was trying to forward calls to a more specific overload. To my surprise, the invocation was not selecting the more specific overload however, but calling back into itself. It clearly has something to do with the base type being generic, but I don't understand why it wouldn't select the Execute(string) overload.

Does anyone have any insight into this?

The above code was simplified to show the pattern, the actual structure is a bit more complicated, but the issue is the same.


答:
As mentioned in Jon Skeet's article on overloading, when invoking a method in a class that also overrides a method with the same name from a base class, the compiler will always take the in-class method instead of the override, regardless of the "specificness" of type, provided that the signature is "compatible".

Jon goes on to point out that this is an excellent argument for avoiding overloading across inheritance boundaries, since this is exactly the kind of unexpected behavior that can occur.

Title: C# Method overload resolution not selecting concrete generic override


问:
How do I configure elasticsearch to retain documents up to 30 days?
Is there a default data retention period in elasticsearch? If yes can you help me find the configuration?</p>

答:
This is no longer supported in Elasticsearch 5.0.0 or greater. The best practice is to create indexes periodically (daily is most common) and then delete the index when the data gets old enough.

Here's a reference to how to delete an index (https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html)

This article (though it's old enough to reference _ttl) also gives some insight: https://www.elastic.co/blog/using-elasticsearch-and-logstash-to-serve-billions-of-searchable-events-for-customers

As a reminder, it's best to protect your Elasticsearch cluster from the outside world via a proxy and restrict the methods that can be sent to your cluster. This way you can prevent your cluster from being ransomed.


问:
Codeigniter : how to update mulitiple record where id
I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.

my view :

```<code><?php echo form_open('stock/updating_stock');?>
  <div class="panel-body scroll-menu" style="margin-top:0px;height:170px;padding-top:5px;">
    <?php foreach($critical_plus_warning as $data){?>
      <input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">
      <h5 class="hidden-xs"><b><?php echo $data->product_name;?></b> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
      }else{
        echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
      }
      ?>
      </h5>
      <h5 class="hidden-lg"><b><?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?></b> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
      }else{
        echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
      }
      ?>
      </h5>
    <?php }?>
  </div>
  <div class="col-xs-12" style="margin-top:-5px;background-color:white;padding:6px;background-color:white;box-shadow:0px 0px 8px 0px #bababa;"><button type="submit" name="submit" class="btn btn-success">Save data</button></div>
  <?php echo form_close();?>
</code>```

and my controller :

```<code>function updating_stock(){

    $id = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    for($i=0;$i<count($id);$i++){
    $data = array(
       array(
        'id'        => $id,
        'stok'      => $stok,
        'diubah'    => $user,
        'tgl_diubah'=> date('Y:m:d H:i:s'),
        ),
    );
    }
    //print_r($data);
    $this->stok_adm->update_stok($data);
}
</code>```

and my models :

```<code>function update_stok($data){
    $this->db->update_batch($this->table, $data,'id_product');
    return $this->db->affected_rows();
}
</code>```

答:
You need a where clause:</p>

```<code>$this->db->where('id', $id);
</code>```

<p>...I think. </p>

Body:
I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.

my view :

<?php echo form_open('stock/updating_stock');?>

    <?php foreach($critical_plus_warning as $data){?>
      <input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">

<?php echo $data->product_name;?> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "$stock";
      }else{
        echo "$stock";
      }
      ?>

<?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
      <?php
      $stock = $data->stocks;
      if($stock < 10){
        echo "$stock";
      }else{
        echo "$stock";
      }
      ?>

    <?php }?>

<button type="submit" name="submit" class="btn btn-success">Save data</button>

  <?php echo form_close();?>

and my controller :

function updating_stock(){

    $id = $this->input->post('id_product');
    $stok = $this->input->post('update_stock');
    $user = $this->data['id'];

    for($i=0;$i<count($id);$i++){
    $data = array(
       array(
        'id'        => $id,
        'stok'      => $stok,
        'diubah'    => $user,
        'tgl_diubah'=> date('Y:m:d H:i:s'),
        ),
    );
    }
    //print_r($data);
    $this->stok_adm->update_stok($data);
}

and my models :

function update_stok($data){
    $this->db->update_batch($this->table, $data,'id_product');
    return $this->db->affected_rows();
}

Body:
You need a where clause:

$this->db->where('id', $id);

...I think.


问:
How to access the user's selection in the browser?
I'm trying to write an extension for chrome that operates on a user's selection on a webpage. How can I get access to the selected text from a chrome plugin?

Thanks,
Joshua

答:
Check this (experimental) copy stuff. I think it's just what you need.

Also, the context menu api (not experimental) gives you a onClickData which contains the selection text.


问:
How to put HashMap into different elements with same key
This is my output which contains three HashMap.

```<code>{2017-03-11=1, 2017-03-05=6}
{2017-03-11=1, 2017-03-05=5}
{2017-03-05=1}
</code>```

i want them to look like this

```<code>date:2017-03-11
c=1, d=1, e=0

date:2017-03-05
c=6, d=5, e=1
</code>```

答:
You can make a wrapper class for the data structure such as

```<code>public class DateWrapper{
    private int a;
    private int b;
    private int c;
    private Date date;

    public DateWrapper(int a, int b, int c, Date date){
        this.a = a;
        this.b = b;
        this.a = c;
        this.date = date;
    }

    // getters and setters
}
</code>```

and then just make a Map<String, DateWrapper>

this way of solving data structure of multiple things that are connected allows to manage setters, and add in more values easely

Body:
This is my output which contains three HashMap.

{2017-03-11=1, 2017-03-05=6}
{2017-03-11=1, 2017-03-05=5}
{2017-03-05=1}

i want them to look like this

date:2017-03-11
c=1, d=1, e=0

date:2017-03-05
c=6, d=5, e=1

Body:
You can make a wrapper class for the data structure such as

public class DateWrapper{
    private int a;
    private int b;
    private int c;
    private Date date;

    public DateWrapper(int a, int b, int c, Date date){
        this.a = a;
        this.b = b;
        this.a = c;
        this.date = date;
    }

    // getters and setters
}

and then just make a Map<String, DateWrapper>

this way of solving data structure of multiple things that are connected allows to manage setters, and add in more values easely


问:
Does anyone see the error in this simple Ruby function?
This function is supposed to take a string and return the characters in reverse order.

```<code>def reverse(string)

    reversedString = "";

        i = string.length - 1
        while i >= 0
          reversedString = reversedString + string[i]
          i -= 1
        end
    puts reversedString

end
</code>```

however all the tests return false:

```<code>puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)

puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)

puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)
</code>```

Does anyone see what the problem is?

答:
If I was going to do this, I'd probably take advantage of an array:

```<code>ary = 'foo bar baz'.chars
reversed_ary = []
ary.size.times do
  reversed_ary << ary.pop
end
reversed_ary.join # => "zab rab oof"
</code>```

pop removes the last character from the array and returns it, so basically it's walking backwards through ary, nibbling at the end and pushing each character onto the end of reversed_ary, effectively reversing the array.

Alternately it could be done using a string:

```<code>ary = 'foo bar baz'.chars
reversed_str = ''
ary.size.times do
  reversed_str << ary.pop
end
reversed_str # => "zab rab oof"
</code>```

or:

```<code>reversed_str += ary.pop
</code>```

I just saw that @tadman did a similar thing with the string. His would run more quickly but this is more readable, at least to my eyes.

Body:
This function is supposed to take a string and return the characters in reverse order.

def reverse(string)

    reversedString = "";

        i = string.length - 1
        while i >= 0
          reversedString = reversedString + string[i]
          i -= 1
        end
    puts reversedString

end

however all the tests return false:

puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)

puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)

puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)

Does anyone see what the problem is?

Body:
If I was going to do this, I'd probably take advantage of an array:

ary = 'foo bar baz'.chars
reversed_ary = []
ary.size.times do
  reversed_ary << ary.pop
end
reversed_ary.join # => "zab rab oof"

pop removes the last character from the array and returns it, so basically it's walking backwards through ary, nibbling at the end and pushing each character onto the end of reversed_ary, effectively reversing the array.

Alternately it could be done using a string:

ary = 'foo bar baz'.chars
reversed_str = ''
ary.size.times do
  reversed_str << ary.pop
end
reversed_str # => "zab rab oof"

or:

reversed_str += ary.pop

I just saw that @tadman did a similar thing with the string. His would run more quickly but this is more readable, at least to my eyes.


问:
Get indices from Boolean array into lists
I have an array called TorF -True or False-, which is a Boolean array.  Say it is a 10 x 10 array with various Trues and Falses.  How do I get the indices of all the True elements?

On a 1D array, I see that np.where() works great.  And on my 10x10 array, I can use np.where(TorF[0]) and return the indices perfectly for the first row.  I can manually do np.where(TorF[1]) for the second row.

I would like to do it for all 10 rows or in a bigger array up to "N" rows.  The problem is that the number of True elements is different for each row. So the list of True elements indices might look like:

```<code>[0, 7, 9]  #the first, eighth, and tenth elements were True
[1, 4, 5, 8, 9]  #2nd, 5th, 6th, 9th, and 10th elements were True
[2, 6]
[0, 5, 7]
etc. up to ten lists or "N" lists
</code>```

Since the list of indices are different lengths, I have problems.  How do I make a loop to get the list of True indices?  Or is there a better function to return this list?  Ideally I would like to have a variable called TrueList that holds these 10 subsets.

答:
The easiest way would be to use lists and a list comprehension inside another list comprehension:

```<code>>>> arr = np.random.randint(0, 2, (10, 10)).astype(bool)
>>> [[idx for idx, item in enumerate(subarr) if item] for subarr in arr.tolist()]
[[0, 5, 7, 8],
 [2, 3, 4, 5, 6, 8, 9],
 [0, 3, 4, 9],
 [1, 3, 4, 5, 6, 9],
 [0, 1, 2, 4, 5, 7],
 [0, 7, 9],
 [0, 5, 8, 9],
 [1, 5, 7],
 [3, 6],
 [0, 1, 2, 4, 5, 6, 7, 9]]
</code>```

For small arrays using python iterations can even be faster than numpy functions like np.where so when you're dealing with 10x10 arrays the list comprehensions can be comparable in performance. But of course you can also use np.where in a list-comprehension:

```<code>>>> [np.where(subarr)[0] for subarr in arr]
[array([0, 5, 7, 8], dtype=int64),
 array([2, 3, 4, 5, 6, 8, 9], dtype=int64),
 array([0, 3, 4, 9], dtype=int64),
 array([1, 3, 4, 5, 6, 9], dtype=int64),
 array([0, 1, 2, 4, 5, 7], dtype=int64),
 array([0, 7, 9], dtype=int64),
 array([0, 5, 8, 9], dtype=int64),
 array([1, 5, 7], dtype=int64),
 array([3, 6], dtype=int64),
 array([0, 1, 2, 4, 5, 6, 7, 9], dtype=int64)]
</code>```

Body:
I have an array called TorF -True or False-, which is a Boolean array.  Say it is a 10 x 10 array with various Trues and Falses.  How do I get the indices of all the True elements?

On a 1D array, I see that np.where() works great.  And on my 10x10 array, I can use np.where(TorF[0]) and return the indices perfectly for the first row.  I can manually do np.where(TorF[1]) for the second row.

I would like to do it for all 10 rows or in a bigger array up to "N" rows.  The problem is that the number of True elements is different for each row. So the list of True elements indices might look like:

[0, 7, 9]  #the first, eighth, and tenth elements were True
[1, 4, 5, 8, 9]  #2nd, 5th, 6th, 9th, and 10th elements were True
[2, 6]
[0, 5, 7]
etc. up to ten lists or "N" lists

Since the list of indices are different lengths, I have problems.  How do I make a loop to get the list of True indices?  Or is there a better function to return this list?  Ideally I would like to have a variable called TrueList that holds these 10 subsets.

Body:
The easiest way would be to use lists and a list comprehension inside another list comprehension:

>>> arr = np.random.randint(0, 2, (10, 10)).astype(bool)
>>> [[idx for idx, item in enumerate(subarr) if item] for subarr in arr.tolist()]
[[0, 5, 7, 8],
 [2, 3, 4, 5, 6, 8, 9],
 [0, 3, 4, 9],
 [1, 3, 4, 5, 6, 9],
 [0, 1, 2, 4, 5, 7],
 [0, 7, 9],
 [0, 5, 8, 9],
 [1, 5, 7],
 [3, 6],
 [0, 1, 2, 4, 5, 6, 7, 9]]

For small arrays using python iterations can even be faster than numpy functions like np.where so when you're dealing with 10x10 arrays the list comprehensions can be comparable in performance. But of course you can also use np.where in a list-comprehension:

>>> [np.where(subarr)[0] for subarr in arr]
[array([0, 5, 7, 8], dtype=int64),
 array([2, 3, 4, 5, 6, 8, 9], dtype=int64),
 array([0, 3, 4, 9], dtype=int64),
 array([1, 3, 4, 5, 6, 9], dtype=int64),
 array([0, 1, 2, 4, 5, 7], dtype=int64),
 array([0, 7, 9], dtype=int64),
 array([0, 5, 8, 9], dtype=int64),
 array([1, 5, 7], dtype=int64),
 array([3, 6], dtype=int64),
 array([0, 1, 2, 4, 5, 6, 7, 9], dtype=int64)]