问:
Espresso IdlingResource polling frequency
I noticed that Espresso polls a particular IdlingResource's isIdleNow() method every five second.

Is it possible to adjust this granularity?

Thanks in advance!

答:
Short answer:

No, it's baked into the IdlingPolicies.dynamicIdlingResourceWarningPolicy and not controlled by external configuration as of version 3.0.1. This policy controls the frequency of warning events that are posted to the handler. These events, in turn, cause the call to isIdleNow()

Slightly longer answer:

It is like this for a very good reason. isIdleNow() is not a place to set your application state. At the time isIdleNow() is called the state should already be known. The state should be updated with the call to ResourceCallback::onTransitionToIdle and generally(99% of a time) not inside of isIdleNow()

The documentation hints at it when it says that you should return immediately, but does not make it clear.

Updating the state in isIdleNow() makes it no better than just sleeping the thread conditionally. Actually, makes it even worse, as your tests are now 5 seconds slower on a per test basis. Which defeats the purpose of espresso as it kills the determinism of the test. And in my opinion determinism of espresso tests is what makes it so great thanks to the built-in main thread synchronization and idling resource interface.

With that being said there should not be a need to modify this timeout. Calling ResourceCallback::onTransitionToIdle will post this event to the handler and espresso will proceed immediately.

Unfortunately, there are lots of examples and even blogs that promote inefficient implementations.

These examples should be great sources of inspiration if you want a more conventional idling resource:

okhttp idling resource

DrawerActions$IdlingDrawerListener bundled with espresso-contrib. here is the source.

CountingTaskExecutorRule from Room library, here is the usage of it.


来源: stackexchange

问:
Node.js: How can i store the jsonObj in a global variable after converting CSV to JSON by using csvtojson

I want to store the jsonObj in a global variable. However, it doesn't work.
</p>

```<code>var jsonContent;

csvConverter.on("end_parsed", function(jsonObj){
//   console.log(jsonObj);
       jsonContent = jsonObj;
});

console.log(jsonContent);
</code>```

<p>
jsonObj can be printed correctly inside {...}. But why can't I pass it to a global variable? The result of "console.log(jsonContent);" is still undefined.
</p>

```<code>undefined
</code>```

答:
jsonContent is global in the sense that it is available everywhere in your JS file. The problem is that csvConverter.on is asynchronous, so it will not block the program while it runs. Therefore, you will not be able to use jsonContent until after csvConverter.on runs its callback.

If you need to use jsonObj, you have to use it after your callback to csvConcerter runs. In order to do so, you can simply wrap your logic in a function and run that function once your callback is called:

```<code>var jsonContent;

csvConverter.on("end_parsed", function(jsonObj){
  jsonContent = jsonObj;
  runLogic();
});

function runLogic() {
  // this function will run after csvConverter.on callback is called
  console.log(jsonContent);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to store the jsonObj in a global variable. However, it doesn't work.

var jsonContent;

csvConverter.on("end_parsed", function(jsonObj){
//   console.log(jsonObj);
       jsonContent = jsonObj;
});

console.log(jsonContent);

jsonObj can be printed correctly inside {...}. But why can't I pass it to a global variable? The result of "console.log(jsonContent);" is still undefined.

undefined

Body:
jsonContent is global in the sense that it is available everywhere in your JS file. The problem is that csvConverter.on is asynchronous, so it will not block the program while it runs. Therefore, you will not be able to use jsonContent until after csvConverter.on runs its callback.

If you need to use jsonObj, you have to use it after your callback to csvConcerter runs. In order to do so, you can simply wrap your logic in a function and run that function once your callback is called:

var jsonContent;

csvConverter.on("end_parsed", function(jsonObj){
  jsonContent = jsonObj;
  runLogic();
});

function runLogic() {
  // this function will run after csvConverter.on callback is called
  console.log(jsonContent);
}


问:
Understand JavaScript Synchronous vs Asynchronous
I am new to JavaScript, Node.js in particular, and I have 2 functions that I am trying to execute. One gets data from a file and passes it to a list, and the other reads from that list in order to get one of the lines from the text file. My code works flawlessly, except the second function executes before the first, which is obviously a problem considering the second function needs information from the first in order to execute successfully.

```<code>let names = [];

function loadNames() {
  var reader = new LineReader("names.txt");
  reader.on("line", function (line) {
  names.push(line);
  console.log("length " + names.length)
  });
}

function getName() {
  console.log(names.length);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      console.log("Loaded - " + name);
 }
  console.log("what is wrong with this thing?")
}
</code>```

loadNames()
getName()

Expected Output:

```<code>length 1
length 2
length 3
length 4
length 5
length 6
length 7
length 8
length 9
length 10
10
Loaded - 1
Loaded - 2
Loaded - 3
Loaded - 4
Loaded - 5
Loaded - 6
Loaded - 7
Loaded - 8
Loaded - 9
Loaded - 10
what is wrong with this thing?
</code>```

Actual Output (besides everything in parenthesis):

```<code>0 (from getName -> console.log(names.length))
what is wrong with this thing? (from getName)
length 1 (from loadNames -> console.log("length" + names.length))
length 2 (from loadNames -> console.log("length" + names.length))
length 3 (from loadNames -> console.log("length" + names.length))
length 4 (from loadNames -> console.log("length" + names.length))
length 5 (from loadNames -> console.log("length" + names.length))
length 6 (from loadNames -> console.log("length" + names.length))
length 7 (from loadNames -> console.log("length" + names.length))
length 8 (from loadNames -> console.log("length" + names.length))
length 9 (from loadNames -> console.log("length" + names.length))
length 10 (from loadNames -> console.log("length" + names.length))
</code>```

答:
There's plenty of great resources on the web to understand the asynchronous nature of JavaScript.

For your specific problem, the library I think you're using offers a solution.

```<code>reader.on('end', function () {
    getName()
}
</code>```

Body:
I am new to JavaScript, Node.js in particular, and I have 2 functions that I am trying to execute. One gets data from a file and passes it to a list, and the other reads from that list in order to get one of the lines from the text file. My code works flawlessly, except the second function executes before the first, which is obviously a problem considering the second function needs information from the first in order to execute successfully.

let names = [];

function loadNames() {
  var reader = new LineReader("names.txt");
  reader.on("line", function (line) {
  names.push(line);
  console.log("length " + names.length)
  });
}

function getName() {
  console.log(names.length);
    for (var i = 0; i < names.length; i++) {
      var name = names[i];
      console.log("Loaded - " + name);
 }
  console.log("what is wrong with this thing?")
}

loadNames()
getName()

Expected Output:

length 1
length 2
length 3
length 4
length 5
length 6
length 7
length 8
length 9
length 10
10
Loaded - 1
Loaded - 2
Loaded - 3
Loaded - 4
Loaded - 5
Loaded - 6
Loaded - 7
Loaded - 8
Loaded - 9
Loaded - 10
what is wrong with this thing?

Actual Output (besides everything in parenthesis):

0 (from getName -> console.log(names.length))
what is wrong with this thing? (from getName)
length 1 (from loadNames -> console.log("length" + names.length))
length 2 (from loadNames -> console.log("length" + names.length))
length 3 (from loadNames -> console.log("length" + names.length))
length 4 (from loadNames -> console.log("length" + names.length))
length 5 (from loadNames -> console.log("length" + names.length))
length 6 (from loadNames -> console.log("length" + names.length))
length 7 (from loadNames -> console.log("length" + names.length))
length 8 (from loadNames -> console.log("length" + names.length))
length 9 (from loadNames -> console.log("length" + names.length))
length 10 (from loadNames -> console.log("length" + names.length))

Body:
There's plenty of great resources on the web to understand the asynchronous nature of JavaScript.

For your specific problem, the library I think you're using offers a solution.

reader.on('end', function () {
    getName()
}


问:
How to replace found regex sub string with spaces with equal length in javascript?
In javascript if I have something like

```<code>string.replace(new RegExp(regex, "ig"), " ")
</code>```

this replaces all found regexes with a single space. But how would I do it if I wanted to replace all found regexes with spaces that matched in length?

so if regex was \d+, and the string was

```<code>"123hello4567"
</code>```

it changes to

```<code>"   hello    "
</code>```

Thanks

答:
The replacement argument (2nd) to .replace can be a function - this function is called in turn with every matching part as the first argument

knowing the length of the matching part, you can return the same number of spaces as the replacement value

In the code below I use . as a replacement value to easily illustrate the code

Note: this uses String#repeat, which is not available in IE11 (but then, neither are arrow functions) but you can always use a polyfill and a transpiler

let regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), m => '.'.repeat(m.length)));```
</div>
</div>
</p>

<p>Internet Exploder friendly version</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>var regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), function (m) {
    return Array(m.length+1).join('.');
}));</code>```

thanks to @nnnnnn for the shorter IE friendly version

Body:
In javascript if I have something like

string.replace(new RegExp(regex, "ig"), " ")

this replaces all found regexes with a single space. But how would I do it if I wanted to replace all found regexes with spaces that matched in length?

so if regex was \d+, and the string was

"123hello4567"

it changes to

"   hello    "

Thanks

Body:
The replacement argument (2nd) to .replace can be a function - this function is called in turn with every matching part as the first argument

knowing the length of the matching part, you can return the same number of spaces as the replacement value

In the code below I use . as a replacement value to easily illustrate the code

Note: this uses String#repeat, which is not available in IE11 (but then, neither are arrow functions) but you can always use a polyfill and a transpiler

let regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), m => '.'.repeat(m.length)));

Internet Exploder friendly version

var regex = "\\d+";
console.log("123hello4567".replace(new RegExp(regex, "ig"), function (m) {
    return Array(m.length+1).join('.');
}));

thanks to @nnnnnn for the shorter IE friendly version


问:
calculating frequency for signal in c# .net
I am developing an application for an oscilloscope in c# .NET, I am drawing different kinds of waves (sine, square etc..) with the help of zedgraph control.
I get values from oscilloscope and stored in a buffer of size 1024(byte array) and have to calculate parameters like time period, Frequency, rise time, fall time etc at run time.
for this purpose i have to extract only a single cycle of whole signal.one more problem is that values are not always rise or fall continuously mean values are stored in buffer like this[0,0,0,1,1,2,3,4,5,5,6,6,6,5,5,4,3,2,1,1,0,0,0..........]. signals are continuously receive from machine.
it is not sure that waves are always oscillating around zero.
Thanks
Regards
Nilesh </p>

答:
You could find out the time period between a crest and a trough, which will give you half the wavelength for that particular wave.

For graph 1, the first trough is 2, the first crest is 12. Find out the time taking between these points, and you have half the wavelength.

For graph two, the same principle applies, you can calculate the wavelength (and thus the period) for each section of the graph

ContentLicense: CC BY-SA 2.5


问:
Mysql database not showing the current date for NOW() function
I am using the NOW() with insert query so that I can get the currentTime when the query is triggered. But I get a time of 12 hours back in the database. How can I get the current Time ? Please help.</p>

答:
You can do something like this

SELECT * FROM tbl WHERE datetime < NOW() - INTERVAL 12 HOURS


问:
Issue opening video file with OpenCV VideoCapture
I've been reviewing the multitudes of similar questions for this issue, but I'm afraid I just cannot figure out why I cannot open a file in opencv

I have a file "small.avi", which is a reencoding of "small.mp4" that I got from the internet. I reencoded it with ffmpeg -i small.mp4 small.avi, and I did this because I couldn't open a mp4 file either and online it recommended trying an avi format first.

Here is my code (mostly copied from a tutorial, with a few lines to show some relevant info):

```<code>import cv2
import os

for _, __, files in os.walk("."):
    for file in files:
        print file
print ""

cap = cv2.VideoCapture("small.mp4")
print cap.isOpened()
print cap.open("small.avi")
i = 0
while cap.isOpened() and i < 10:
    i += 1
    ret, frame = cap.read()
    print "read a frame"
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()
</code>```

This produces the following output:

```<code>"A:\Program Files\AnacondaPY\Anaconda\python.exe" A:/Documents/Final/VideoProcessor.py
small.avi
small.mp4
VideoProcessor.py

False
False

Process finished with exit code 0
</code>```

My program does not appear to properly open either file. Following the advice of

Can not Read or Play a Video in OpenCV+Python using VideoCapture

and

Cannot open ".mp4" video files using OpenCV 2.4.3, Python 2.7 in Windows 7 machine,

I found my cv2 version to be 3.0.0, went to

A:\Downloads\opencv\build\x86\vc12\bin

and copied the file opencv_ffmpeg300.dll to

A:\Program Files\AnacondaPY\Anaconda

Despite this, the code still does not successfully open the video file. I even tried the x64 versions, and tried naming the file opencv_ffmpeg.dll, opencv_ffmpeg300.dll, and opencv_ffmpeg300_64.dll (for the x64 version). Is there anything else I can try to fix this?

Thanks for any help

答:
If you downloaded opencv from menpo(or default conda) channel(using 'conda install --channel https://conda.anaconda.org/menpo opencv3'
), it might not work as some video processing dependencies such as ffmpeg are not present.

You need to download opencv from 'conda-forge' channel which contains latest and additional packages and dependencies for video processing. Try the following:

```<code>conda install -c conda-forge ffmpeg

conda install -c conda-forge opencv
</code>```

Here -c tells the channel to use as 'conda-forge'.

Body:
I've been reviewing the multitudes of similar questions for this issue, but I'm afraid I just cannot figure out why I cannot open a file in opencv

I have a file "small.avi", which is a reencoding of "small.mp4" that I got from the internet. I reencoded it with ffmpeg -i small.mp4 small.avi, and I did this because I couldn't open a mp4 file either and online it recommended trying an avi format first.

Here is my code (mostly copied from a tutorial, with a few lines to show some relevant info):

import cv2
import os

for _, __, files in os.walk("."):
    for file in files:
        print file
print ""

cap = cv2.VideoCapture("small.mp4")
print cap.isOpened()
print cap.open("small.avi")
i = 0
while cap.isOpened() and i < 10:
    i += 1
    ret, frame = cap.read()
    print "read a frame"
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame', gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

This produces the following output:

"A:\Program Files\AnacondaPY\Anaconda\python.exe" A:/Documents/Final/VideoProcessor.py
small.avi
small.mp4
VideoProcessor.py

False
False

Process finished with exit code 0

My program does not appear to properly open either file. Following the advice of

Can not Read or Play a Video in OpenCV+Python using VideoCapture

and

Cannot open ".mp4" video files using OpenCV 2.4.3, Python 2.7 in Windows 7 machine,

I found my cv2 version to be 3.0.0, went to

A:\Downloads\opencv\build\x86\vc12\bin

and copied the file opencv_ffmpeg300.dll to

A:\Program Files\AnacondaPY\Anaconda

Despite this, the code still does not successfully open the video file. I even tried the x64 versions, and tried naming the file opencv_ffmpeg.dll, opencv_ffmpeg300.dll, and opencv_ffmpeg300_64.dll (for the x64 version). Is there anything else I can try to fix this?

Thanks for any help

Body:
If you downloaded opencv from menpo(or default conda) channel(using 'conda install --channel https://conda.anaconda.org/menpo opencv3'
), it might not work as some video processing dependencies such as ffmpeg are not present.

You need to download opencv from 'conda-forge' channel which contains latest and additional packages and dependencies for video processing. Try the following:

conda install -c conda-forge ffmpeg

conda install -c conda-forge opencv

Here -c tells the channel to use as 'conda-forge'.


问:
How to select all values in a column by column number in excel
I am trying to find an elegant way to select all values in a given column on another sheet, based on it's number. I also need to exclude the first row.

I figured that this would be simple but am surprised how much of a headache it has been.

One method has been this:

```<code>=INDEX(OtherSheet!$A$2:$H$15, 0, <colNum>)
</code>```

but this relies on hoping that $H is the last column and $15 is the last row.

Second attempt:

```<code>=OFFSET(INDIRECT("OtherSheet!R1C"&<colNum>, FALSE), 1, 0, 15)
</code>```

But I have to hardcode the number of rows here as well.

This seems like this is such a simple thing to do, am I just missing something?

Thanks!

答:
To return the last row containing data of a given column, using a formula and given that

wSheet is a named range containing the worksheet name

colNum is a named range containing the  desired column number

```<code>=LOOKUP(2,1/(LEN(INDIRECT(wSheet & "!C" & colNum,FALSE))>0),ROW(INDIRECT(wSheet & "!C" & colNum,FALSE)))
</code>```

To return a range which refers to that column from Row 2 to the last row, you can combine INDIRECT with the ADDRESS function:

```<code>=INDIRECT(ADDRESS(2,colNum,1,1,wSheet)&":"&ADDRESS(LOOKUP(2,1/(LEN(INDIRECT(wSheet & "!C" & colNum,FALSE))>0),ROW(INDIRECT(wSheet & "!C" & colNum,FALSE))),colNum,1,1))
</code>```

One issue with this method is that it will return 0's for empty or blank cells

Body:
I am trying to find an elegant way to select all values in a given column on another sheet, based on it's number. I also need to exclude the first row.

I figured that this would be simple but am surprised how much of a headache it has been.

One method has been this:

=INDEX(OtherSheet!$A$2:$H$15, 0, <colNum>)

but this relies on hoping that $H is the last column and $15 is the last row.

Second attempt:

=OFFSET(INDIRECT("OtherSheet!R1C"&<colNum>, FALSE), 1, 0, 15)

But I have to hardcode the number of rows here as well.

This seems like this is such a simple thing to do, am I just missing something?

Thanks!

Body:
To return the last row containing data of a given column, using a formula and given that

wSheet is a named range containing the worksheet name

colNum is a named range containing the  desired column number

=LOOKUP(2,1/(LEN(INDIRECT(wSheet & "!C" & colNum,FALSE))>0),ROW(INDIRECT(wSheet & "!C" & colNum,FALSE)))

To return a range which refers to that column from Row 2 to the last row, you can combine INDIRECT with the ADDRESS function:

=INDIRECT(ADDRESS(2,colNum,1,1,wSheet)&":"&ADDRESS(LOOKUP(2,1/(LEN(INDIRECT(wSheet & "!C" & colNum,FALSE))>0),ROW(INDIRECT(wSheet & "!C" & colNum,FALSE))),colNum,1,1))

One issue with this method is that it will return 0's for empty or blank cells


问:
selection.data returning different types of objects
Every loop, I perform some updates on a certain selection of objects (see code snippet below), starting with removing deleted elements using an exit() call.  I just added a slider to modify a parameter in one of the objects, and when the slider moves I call the same update method (again with the code below).  When the slider triggers the update, however, the selection is different... and in particular, the exit() method fails --- TypeError: selection.exit is not a function (and I think I'm avoiding the standard cause of that problem).

```<code>var selection = svgSim.selectAll(".bh")
    .data(binary);

// Remove old
console.log("sel = ", selection);
var olds = selection.exit();
olds.remove();
</code>```

When I log the selection to console, the contents is basically the same... but there seems to be something different about the object type, or something like that.  See the screen shot below.  The first printout of selection ("sel = [...]") is when it works fine.  The next time it raises the error, and the formatting of the print is different - although it seems to contain the same basic data.

Why is selection.data() returning different types of objects when called in different contexts?

What is the difference in the console.log output: what is pt (in the output) and what are the different types of objects being printed here.

Note: I understand if this non-MWE is insufficient to solve the problem entirely, which is why I've tried to ask a few specific (sub)questions which may help me find the problem, none-the-less.

The data looks something like,

```<code>var phaseInit = Math.random();
var binary = [
    {name: "a", phase: phaseInit, mass: m1},
    {name: "b", phase: phaseInit + 0.5, mass: m2}
];
</code>```

And when the slider moves, I'm modifying the data like:

```<code>binary[0].mass = sliderScaleM1.invert(sval);
</code>```

(very new to javascipt and d3)

答:
Since we don't have access to a MWE (see this comment), this is a general answer trying to clarify the issue based on the information provided.

In D3, the data() method accepts three things:

An array;

A function;

Nothing.

In the first and second cases, data() is a setter. However, in the third case, data() is a getter.

We can see this in a basic example:

var body = d3.select("body");
var data = ["foo", "bar", "baz"];
var sel = body.selectAll(null)
  .data(data);
sel.enter()
  .append("p")
  .html(String)

console.log(sel)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

However, if we use data() as a getter, we don't have a selection anymore:

var body = d3.select("body");
var data = ["foo", "bar", "baz"];
var sel = body.selectAll(null)
  .data(data);
sel.enter()
  .append("p")
  .html(String)
var sel2 = body.selectAll("p").data()

console.log(sel2)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://d3js.org/d3.v4.min.js"></script></code>```

Because of that, you cannot call exit() on that variable: it is not a D3 selection, but just the data array.

Looking at your console we can see that, at 19:57:07, sel is a regular D3 selection. However, at 19:57:12, sel is just an array, more specifically your data array.

So, in conclusion, somehow in your code you're using data() as a getter, and the variable sel doesn't hold a D3 selection anymore.

Body:
Every loop, I perform some updates on a certain selection of objects (see code snippet below), starting with removing deleted elements using an exit() call.  I just added a slider to modify a parameter in one of the objects, and when the slider moves I call the same update method (again with the code below).  When the slider triggers the update, however, the selection is different... and in particular, the exit() method fails --- TypeError: selection.exit is not a function (and I think I'm avoiding the standard cause of that problem).

var selection = svgSim.selectAll(".bh")
    .data(binary);

// Remove old
console.log("sel = ", selection);
var olds = selection.exit();
olds.remove();

When I log the selection to console, the contents is basically the same... but there seems to be something different about the object type, or something like that.  See the screen shot below.  The first printout of selection ("sel = [...]") is when it works fine.  The next time it raises the error, and the formatting of the print is different - although it seems to contain the same basic data.

Why is selection.data() returning different types of objects when called in different contexts?

What is the difference in the console.log output: what is pt (in the output) and what are the different types of objects being printed here.

Note: I understand if this non-MWE is insufficient to solve the problem entirely, which is why I've tried to ask a few specific (sub)questions which may help me find the problem, none-the-less.

The data looks something like,

var phaseInit = Math.random();
var binary = [
    {name: "a", phase: phaseInit, mass: m1},
    {name: "b", phase: phaseInit + 0.5, mass: m2}
];

And when the slider moves, I'm modifying the data like:

binary[0].mass = sliderScaleM1.invert(sval);

(very new to javascipt and d3)

Body:
Since we don't have access to a MWE (see this comment), this is a general answer trying to clarify the issue based on the information provided.

In D3, the data() method accepts three things:

An array;

A function;

Nothing.

In the first and second cases, data() is a setter. However, in the third case, data() is a getter.

We can see this in a basic example:

var body = d3.select("body");
var data = ["foo", "bar", "baz"];
var sel = body.selectAll(null)
  .data(data);
sel.enter()
  .append("p")
  .html(String)

console.log(sel)

<script src="https://d3js.org/d3.v4.min.js"></script>

However, if we use data() as a getter, we don't have a selection anymore:

var body = d3.select("body");
var data = ["foo", "bar", "baz"];
var sel = body.selectAll(null)
  .data(data);
sel.enter()
  .append("p")
  .html(String)
var sel2 = body.selectAll("p").data()

console.log(sel2)

<script src="https://d3js.org/d3.v4.min.js"></script>

Because of that, you cannot call exit() on that variable: it is not a D3 selection, but just the data array.

Looking at your console we can see that, at 19:57:07, sel is a regular D3 selection. However, at 19:57:12, sel is just an array, more specifically your data array.

So, in conclusion, somehow in your code you're using data() as a getter, and the variable sel doesn't hold a D3 selection anymore.


问:
CSS Navigation Bar within the Parallax Page
I did look for some tutorials about parallax. I want to add navigation bar on it but the results are different from what I'm expecting. I need your help.

This is the CSS code of the navigation Bar:

```<code>body{
        margin: 0;

    }

    .navigation{
        width: 100%;
        background: #313131;
        height: 50px;
        margin-top: 0px;

    }

    ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
        position: absolute;
        margin-top: 5px;
    }

    li {
    float: left;
    margin-top: 5px;
    padding-left: 25px;
    padding-right: 25px;
    }

    a{
        width: 150px;
        color: white;
        display: block;
        text-decoration: none;
        font-size: 20px;
        text-align: center;
        padding: 2px;
        border-radius: 4px;
        font-family: Century Gothic;
        font-weight: bold;

    }

    a:hover{
        background: #669900;
        transition: 0.6s;
    }
</code>```

CSS Code of Parallax Page

```<code>@import "bourbon";

//Edit these
$farColor: #ffe4c7;
$nearColor: darken(cyan,30%);
$layer: 7; //make sure it is +1 the ammount of layer divs in the html
$perspective: 1;

    .bg {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0px;
  z-index: 0;
  background-color: #ffe4c7;
}

.layer {
  position: fixed;
  top: 0px;
  margin: auto;
  width: 100%;
  z-index: 100;
  min-height: 400px;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-position: top center;
  background-repeat: no-repeat;
}

.parallax {
  height: 100vh;
  overflow-x: hidden;
  overflow-y: scroll;
  -webkit-perspective: 1px;
          perspective: 1px;
}

.parallax-group {
  position: relative;
  height: 100vh;
  -webkit-transform-style: preserve-3d;
          transform-style: preserve-3d;
}

.parallax-group div:nth-child(1) {
  background-color: #ffe4c7;
  margin-top: 600px;
  background-color: #d9d1b8;
  -webkit-transform: translateZ(-12px) scale(13);
          transform: translateZ(-12px) scale(13);
}
.parallax-group div:nth-child(1):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #d9d1b8 66.01%), -webkit-linear-gradient(45deg, #d9d1b8 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #d9d1b8 66.01%), linear-gradient(45deg, #d9d1b8 34%, transparent 34.01%);
  background-position: 222px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(2) {
  background-color: #ffe4c7;
  margin-top: 900px;
  background-color: #b3beaa;
  -webkit-transform: translateZ(-10px) scale(11);
          transform: translateZ(-10px) scale(11);
}
.parallax-group div:nth-child(2):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #b3beaa 66.01%), -webkit-linear-gradient(45deg, #b3beaa 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #b3beaa 66.01%), linear-gradient(45deg, #b3beaa 34%, transparent 34.01%);
  background-position: 77px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(3) {
  background-color: #ffe4c7;
  margin-top: 1200px;
  background-color: #8cab9b;
  -webkit-transform: translateZ(-8px) scale(9);
          transform: translateZ(-8px) scale(9);
}
.parallax-group div:nth-child(3):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #8cab9b 66.01%), -webkit-linear-gradient(45deg, #8cab9b 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #8cab9b 66.01%), linear-gradient(45deg, #8cab9b 34%, transparent 34.01%);
  background-position: 117px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(4) {
  background-color: #ffe4c7;
  margin-top: 1500px;
  background-color: #66988d;
  -webkit-transform: translateZ(-6px) scale(7);
          transform: translateZ(-6px) scale(7);
}
.parallax-group div:nth-child(4):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #66988d 66.01%), -webkit-linear-gradient(45deg, #66988d 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #66988d 66.01%), linear-gradient(45deg, #66988d 34%, transparent 34.01%);
  background-position: 183px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(5) {
  background-color: #ffe4c7;
  margin-top: 1800px;
  background-color: #40867e;
  -webkit-transform: translateZ(-4px) scale(5);
          transform: translateZ(-4px) scale(5);
}
.parallax-group div:nth-child(5):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #40867e 66.01%), -webkit-linear-gradient(45deg, #40867e 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #40867e 66.01%), linear-gradient(45deg, #40867e 34%, transparent 34.01%);
  background-position: 71px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(6) {
  background-color: #ffe4c7;
  margin-top: 2100px;
  background-color: #1a7370;
  -webkit-transform: translateZ(-2px) scale(3);
          transform: translateZ(-2px) scale(3);
}
.parallax-group div:nth-child(6):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #1a7370 66.01%), -webkit-linear-gradient(45deg, #1a7370 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #1a7370 66.01%), linear-gradient(45deg, #1a7370 34%, transparent 34.01%);
  background-position: 13px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.content {
  position: relative;
  background-color: transparent;
  font-family: "Arial";
  letter-spacing: 10px;
  text-transform: uppercase;
  line-height: 40px;
  z-index: 10;
  width: 100%;
  font-size: 15px;
  text-align: center;
  color: white;
  margin-top: 1000px;
  -webkit-transform: translateZ(-2px) scale(3);
          transform: translateZ(-2px) scale(3);
}

.fill {
  height: 80%;
}
</code>```

HTML Code

```<code></style>
</head>
<body>

<div class="bg"></div>
<div class="parallax">

  <div class="parallax-group">

    <div class="layer"></div>
    <div class="layer"></div>
    <div class="layer"></div>
    <div class="layer"></div>
    <div class="layer"></div>
    <div class="layer fill"></div>
  </div>
  <div class="content">
    <h1>Parallax Scrolling</h1>
    <p>Using only CSS</p>
  </div>
</div>
<div class="navigation">

    <ul>

        <li><a href="Home.html"><span>Home</span></a></li>

        <li><a href="beachHouses.html"><span>Beach Houses</span></a></li>

        <li><a href="Gallery.html"><span>Gallery</span></a></li>

        <li><a href="Contact.html"><span>Contact</span></a></li>

    </ul>

</div>

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

I want a floating navigation bar within the parallax page

Here is the result that I get:
https://jsfiddle.net/christiands97/s5Ltf6pj/

答:
Put these in the css of your navigation class.

```<code>top: 10px;
position: absolute;
</code>```

change the top value according to your requirement. Also make the 'position' fixed if you want the navigation bar to be fixed at the top.

Body:
I did look for some tutorials about parallax. I want to add navigation bar on it but the results are different from what I'm expecting. I need your help.

This is the CSS code of the navigation Bar:

body{
        margin: 0;

    }

    .navigation{
        width: 100%;
        background: #313131;
        height: 50px;
        margin-top: 0px;

    }

    ul {
        list-style-type: none;
        padding: 0;
        margin: 0;
        position: absolute;
        margin-top: 5px;
    }

    li {
    float: left;
    margin-top: 5px;
    padding-left: 25px;
    padding-right: 25px;
    }

    a{
        width: 150px;
        color: white;
        display: block;
        text-decoration: none;
        font-size: 20px;
        text-align: center;
        padding: 2px;
        border-radius: 4px;
        font-family: Century Gothic;
        font-weight: bold;

    }

    a:hover{
        background: #669900;
        transition: 0.6s;
    }

CSS Code of Parallax Page

@import "bourbon";

//Edit these
$farColor: #ffe4c7;
$nearColor: darken(cyan,30%);
$layer: 7; //make sure it is +1 the ammount of layer divs in the html
$perspective: 1;

    .bg {
  position: absolute;
  height: 100%;
  width: 100%;
  top: 0px;
  z-index: 0;
  background-color: #ffe4c7;
}

.layer {
  position: fixed;
  top: 0px;
  margin: auto;
  width: 100%;
  z-index: 100;
  min-height: 400px;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-position: top center;
  background-repeat: no-repeat;
}

.parallax {
  height: 100vh;
  overflow-x: hidden;
  overflow-y: scroll;
  -webkit-perspective: 1px;
          perspective: 1px;
}

.parallax-group {
  position: relative;
  height: 100vh;
  -webkit-transform-style: preserve-3d;
          transform-style: preserve-3d;
}

.parallax-group div:nth-child(1) {
  background-color: #ffe4c7;
  margin-top: 600px;
  background-color: #d9d1b8;
  -webkit-transform: translateZ(-12px) scale(13);
          transform: translateZ(-12px) scale(13);
}
.parallax-group div:nth-child(1):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #d9d1b8 66.01%), -webkit-linear-gradient(45deg, #d9d1b8 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #d9d1b8 66.01%), linear-gradient(45deg, #d9d1b8 34%, transparent 34.01%);
  background-position: 222px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(2) {
  background-color: #ffe4c7;
  margin-top: 900px;
  background-color: #b3beaa;
  -webkit-transform: translateZ(-10px) scale(11);
          transform: translateZ(-10px) scale(11);
}
.parallax-group div:nth-child(2):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #b3beaa 66.01%), -webkit-linear-gradient(45deg, #b3beaa 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #b3beaa 66.01%), linear-gradient(45deg, #b3beaa 34%, transparent 34.01%);
  background-position: 77px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(3) {
  background-color: #ffe4c7;
  margin-top: 1200px;
  background-color: #8cab9b;
  -webkit-transform: translateZ(-8px) scale(9);
          transform: translateZ(-8px) scale(9);
}
.parallax-group div:nth-child(3):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #8cab9b 66.01%), -webkit-linear-gradient(45deg, #8cab9b 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #8cab9b 66.01%), linear-gradient(45deg, #8cab9b 34%, transparent 34.01%);
  background-position: 117px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(4) {
  background-color: #ffe4c7;
  margin-top: 1500px;
  background-color: #66988d;
  -webkit-transform: translateZ(-6px) scale(7);
          transform: translateZ(-6px) scale(7);
}
.parallax-group div:nth-child(4):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #66988d 66.01%), -webkit-linear-gradient(45deg, #66988d 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #66988d 66.01%), linear-gradient(45deg, #66988d 34%, transparent 34.01%);
  background-position: 183px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(5) {
  background-color: #ffe4c7;
  margin-top: 1800px;
  background-color: #40867e;
  -webkit-transform: translateZ(-4px) scale(5);
          transform: translateZ(-4px) scale(5);
}
.parallax-group div:nth-child(5):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #40867e 66.01%), -webkit-linear-gradient(45deg, #40867e 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #40867e 66.01%), linear-gradient(45deg, #40867e 34%, transparent 34.01%);
  background-position: 71px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.parallax-group div:nth-child(6) {
  background-color: #ffe4c7;
  margin-top: 2100px;
  background-color: #1a7370;
  -webkit-transform: translateZ(-2px) scale(3);
          transform: translateZ(-2px) scale(3);
}
.parallax-group div:nth-child(6):before {
  content: "";
  width: 100%;
  height: 200px;
  position: absolute;
  bottom: 100%;
  left: 0;
  background-image: -webkit-linear-gradient(315deg, transparent 66%, #1a7370 66.01%), -webkit-linear-gradient(45deg, #1a7370 34%, transparent 34.01%);
  background-image: linear-gradient(135deg, transparent 66%, #1a7370 66.01%), linear-gradient(45deg, #1a7370 34%, transparent 34.01%);
  background-position: 13px 0px;
  background-size: 200px 100%;
  background-repeat: repeat-x;
}

.content {
  position: relative;
  background-color: transparent;
  font-family: "Arial";
  letter-spacing: 10px;
  text-transform: uppercase;
  line-height: 40px;
  z-index: 10;
  width: 100%;
  font-size: 15px;
  text-align: center;
  color: white;
  margin-top: 1000px;
  -webkit-transform: translateZ(-2px) scale(3);
          transform: translateZ(-2px) scale(3);
}

.fill {
  height: 80%;
}

HTML Code

</style>

Parallax Scrolling

Using only CSS

Home

Beach Houses

Gallery

Contact

I want a floating navigation bar within the parallax page

Here is the result that I get:
https://jsfiddle.net/christiands97/s5Ltf6pj/

Body:
Put these in the css of your navigation class.

top: 10px;
position: absolute;

change the top value according to your requirement. Also make the 'position' fixed if you want the navigation bar to be fixed at the top.


问:
working with C# arrays (memory, efficiency, speed)
When working with an array (of bytes but could be anything) how do these two approaches compare in terms of efficiency, speed, etc. Why would one prefer one over the other?

First approach

```<code>byte[] myArray=new byte[100];

useArray(myArray);
useArray(myArray);
useArray(myArray);

//where

void useArray(byte[] MyArray)
{
   //do something with the elements of MyArray
}
</code>```

Second Approach

```<code>byte[] myArray=new byte[100];

myArray= useArray2(myArray);
myArray= useArray2(myArray);
myArray= useArray2(myArray);
//where

byte[] useArray2(byte[] MyArray)
{
    byte[] tempArray= new byte[100];
   //do EXACTLY the same as useArray but store the results in tempArray
   return tempArray;
}
</code>```

Take into account that the option 2 is leaving memory to be garbage collected at some point in time, everytime it calls useArray2.
Also the functions are going to be called repeatedly.

So which is more efficient, or preferable?

答:
Let's see. Your first example allocates a single, 100-byte array.

Your second example allocates four 100-byte arrays, all of which will need to be deallocated. And you may or may not be copying data between those arrays.

Isn't it clear that the first is more efficient?

Body:
When working with an array (of bytes but could be anything) how do these two approaches compare in terms of efficiency, speed, etc. Why would one prefer one over the other?

First approach

byte[] myArray=new byte[100];

useArray(myArray);
useArray(myArray);
useArray(myArray);

//where

void useArray(byte[] MyArray)
{
   //do something with the elements of MyArray
}

Second Approach

byte[] myArray=new byte[100];

myArray= useArray2(myArray);
myArray= useArray2(myArray);
myArray= useArray2(myArray);
//where

byte[] useArray2(byte[] MyArray)
{
    byte[] tempArray= new byte[100];
   //do EXACTLY the same as useArray but store the results in tempArray
   return tempArray;
}

Take into account that the option 2 is leaving memory to be garbage collected at some point in time, everytime it calls useArray2.
Also the functions are going to be called repeatedly.

So which is more efficient, or preferable?


问:
Macro to export Excel Doc as PDF for all Users
I need to create a macro that will save an excel document as a PDF file to any user's desktop (i.e. multiple people will be using this document/macro).

Here is VBA code I have so far:

```<code>Sub CreatePDF()
'
' CreatePDF Macro
'

'
    ChDir "C:\Users\Public\Desktop"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\Public\Desktop\QuickView Update Dec_2017.pdf", Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub
</code>```

I think the issue is with the directory it's saving to (in the instances where this code says "Public" in the file path, I had changed that from my username which was initially populated).

Does anyone know a way to specify a generic path to save this document as a PDF to any users' desktop?

答:
I have not tested this but based on what you gave try :

```<code>Dim url As String
url = Application.DefaultFilePath & "\" & ActiveWorkbook.Name & ".xls"
</code>```

in your export part of your code replace filename:= blah blah to Filename:=url

Body:
I need to create a macro that will save an excel document as a PDF file to any user's desktop (i.e. multiple people will be using this document/macro).

Here is VBA code I have so far:

Sub CreatePDF()
'
' CreatePDF Macro
'

'
    ChDir "C:\Users\Public\Desktop"
    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\Public\Desktop\QuickView Update Dec_2017.pdf", Quality:= _
        xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

I think the issue is with the directory it's saving to (in the instances where this code says "Public" in the file path, I had changed that from my username which was initially populated).

Does anyone know a way to specify a generic path to save this document as a PDF to any users' desktop?

Body:
I have not tested this but based on what you gave try :

Dim url As String
url = Application.DefaultFilePath & "\" & ActiveWorkbook.Name & ".xls"

in your export part of your code replace filename:= blah blah to Filename:=url


问:
Can HTML markup tags interleave?
I suspect this is invalid html but I'm chiefly interested to know whether browsers will handle it gracefully.  I want to <mark> some text that may have html tags interspersed.  Specifically, if a mark tag opens after another formatting tag, say span or font, but the span/font closes before the mark closes, will (modern) browsers handle it gracefully?</p>

```<code><span><mark>text</span> more text</mark>
</code>```

答:
text more text is invalid HTML, which can be confirmed by the W3 Validation Service.

Browsers cannot be relied upon to handle invalid markup reliably. In the above,  will mark the first text. Then  will kick in and close the first , and the parser will get confused as to how to handle the open . In most cases, your ending  tag will be interpreted as invalid, because the parser will think that the tag is not open.

Here's an example with
 and :

Google 1
Google 2```

Note that the two lines are split, indicating that the
 tag triggered, though both lines take the hyperlink.

As for your mention of the  tag, please note that this is obsolete, and you should be controlling the fonts via CSS instead.

Hope this helps. :)

Title: Can HTML markup tags interleave?

Body:
I suspect this is invalid html but I'm chiefly interested to know whether browsers will handle it gracefully.  I want to  some text that may have html tags interspersed.  Specifically, if a mark tag opens after another formatting tag, say span or font, but the span/font closes before the mark closes, will (modern) browsers handle it gracefully?

text more text

Body:
<span><mark>text</span> more text</mark> is invalid HTML, which can be confirmed by the W3 Validation Service.

Browsers cannot be relied upon to handle invalid markup reliably. In the above, <mark> will mark the first text. Then </span> will kick in and close the first <span>, and the parser will get confused as to how to handle the open <mark>. In most cases, your ending </mark> tag will be interpreted as invalid, because the parser will think that the tag is not open.

Here's an example with <p> and <a>:

<p><a href="http://www.google.com">Google 1</p>Google 2</a>

Note that the two lines are split, indicating that the <p> tag triggered, though both lines take the hyperlink.

As for your mention of the <font> tag, please note that this is obsolete, and you should be controlling the fonts via CSS instead.

Hope this helps. :)


问:
data.table shift() doesn't seem to "lead" correctly
I'm a beginner to data.table.  Can anyone explain to me why I cant get the expected result with shift()? (I get the same result with "lead" or "lag")

```<code>set.seed(123)
x <- data.table(a = sample(1:10,10,replace = F))
x <- x[order(a)][, a1 := shift(a,1,"lead")]
x
     a a1
 1:  1 NA
 2:  2  1
 3:  3  2
 4:  4  3
 5:  5  4
 6:  6  5
 7:  7  6
 8:  8  7
 9:  9  8
10: 10  9
</code>```

Here is the result I am expecting:

```<code>data.table(a = 1:10, a1 = c(2:10,NA))
     a a1
 1:  1  2
 2:  2  3
 3:  3  4
 4:  4  5
 5:  5  6
 6:  6  7
 7:  7  8
 8:  8  9
 9:  9 10
10: 10 NA
</code>```

答:
The function definition for shift is

```<code>shift(x, n=1L, fill=NA, type=c("lag", "lead"), give.names=FALSE)
</code>```

However, as you haven't specified the arguments you're using, the function assumes your third one is being used for the fill argument (the third one in the definition).

So what you're actually doing is

```<code>shift(x = a, n = 1, fill = "lead", type = "lag", give.names = FALSE)
## where type & give.names are using their default values
</code>```

You probably want to explicitly state the arguments:

```<code>set.seed(123)
library(data.table)
x <- data.table(a = sample(1:10,10,replace = F))

x[order(a)][, a1 := shift(a, n = 1, type = "lead")][]
#      a a1
# 1:  1  2
# 2:  2  3
# 3:  3  4
# 4:  4  5
# 5:  5  6
# 6:  6  7
# 7:  7  8
# 8:  8  9
# 9:  9 10
# 10: 10 NA
</code>```

Body:
I'm a beginner to data.table.  Can anyone explain to me why I cant get the expected result with shift()? (I get the same result with "lead" or "lag")

set.seed(123)
x <- data.table(a = sample(1:10,10,replace = F))
x <- x[order(a)][, a1 := shift(a,1,"lead")]
x
     a a1
 1:  1 NA
 2:  2  1
 3:  3  2
 4:  4  3
 5:  5  4
 6:  6  5
 7:  7  6
 8:  8  7
 9:  9  8
10: 10  9

Here is the result I am expecting:

data.table(a = 1:10, a1 = c(2:10,NA))
     a a1
 1:  1  2
 2:  2  3
 3:  3  4
 4:  4  5
 5:  5  6
 6:  6  7
 7:  7  8
 8:  8  9
 9:  9 10
10: 10 NA

Body:
The function definition for shift is

shift(x, n=1L, fill=NA, type=c("lag", "lead"), give.names=FALSE)

However, as you haven't specified the arguments you're using, the function assumes your third one is being used for the fill argument (the third one in the definition).

So what you're actually doing is

shift(x = a, n = 1, fill = "lead", type = "lag", give.names = FALSE)
## where type & give.names are using their default values

You probably want to explicitly state the arguments:

set.seed(123)
library(data.table)
x <- data.table(a = sample(1:10,10,replace = F))

x[order(a)][, a1 := shift(a, n = 1, type = "lead")][]
#      a a1
# 1:  1  2
# 2:  2  3
# 3:  3  4
# 4:  4  5
# 5:  5  6
# 6:  6  7
# 7:  7  8
# 8:  8  9
# 9:  9 10
# 10: 10 NA


问:
Calculating individuals turning specific age within a few months from current date in SQL Server
I'm trying to write a query where I can calculate individuals that will be turning 65 based on their birth date while using the current date(GETDATE). However, the query also requires that I be able to pull individuals who will be turning 65 within 3 months of the current date(GETDATE). So far, I've only been able to pull individuals by entering a parameter of 19 into my century field (eebdcy) and entering 52 in my year field (eebdyr). I would like to remove these 2 fields and allow the user to just run the query without having to fiddle with my date fields. Is this possible?

Thank you in advance.

My Code:

```<code>SELECT
distinct eessn AS SSN, eenaml AS LastName, eenamf AS FirstName, eenamm AS MiddleInitial,
         ( RIGHT('00'+ CONVERT(varchar, EEBDCY), 2) + RIGHT('00'+ CONVERT(varchar, EEBDYR), 2) + '-' + RIGHT('00'+ CONVERT(varchar, EEBDMT), 2) + '-' + RIGHT('00' + CONVERT(varchar, EEBDDY), 2) ) AS [DOB],
         phprid AS ProductID, phacct AS AccountNumber, amplac AS  AccountName, amua12 AS MSPInd, phgrp AS GroupID,
         ( RIGHT('00'+ CONVERT(varchar, amfxc2), 2) + RIGHT('00'+ CONVERT(varchar, amfxy2), 2) + '-' + RIGHT('00'+ CONVERT(varchar, amfxm2), 2) + '-' + RIGHT('00' + CONVERT(varchar, amfxd2), 2) ) as MSPEFFDT,
         substring(amuaky,1,3) as REP,
         CONVERT (date, GETDATE()) AS [TODAY],
        CAST(DATEDIFF(DD,( RIGHT('00'+ CONVERT(varchar, EEBDCY), 2) + RIGHT('00'+ CONVERT(varchar, EEBDYR), 2) + '-' + RIGHT('00'+ CONVERT(varchar, EEBDMT), 2) + '-' + RIGHT('00' + CONVERT(varchar, EEBDDY), 2) ), GETDATE())/365.25 AS INT) AS AGE
    FROM pdthist, empmstr, actmstr
   WHERE phgrp in ('4664 ESP','4664 XM')
     and phpcat = 3 and phtdcy = 0
     and eessn = phssn and eegrp = phgrp
     and phacct = amacct and phgrp = amgrp and amtdcy = 0
     and eebdcy = 19 and eebdyr = 52
    ORDER BY phacct, eessn
</code>```

答:
I believe this would work:

```<code>select
*
from your_table
cross apply (
    select DATEFROMPARTS((EEBDCY + EEBDYR), EEBDMT, EEBDDY), dateadd(month,3,getdate())
    ) ca (Birthdate, CompareDate)
where 65 <= YEAR(CompareDate) - (EEBDCY + EEBDYR)
            - ( CASE
                   WHEN MONTH(EEBDMT) > MONTH(CompareDate)
                     OR ( MONTH(EEBDMT) = MONTH(CompareDate)
                        AND DAY(EEBDDY) > DAY(CompareDate)
                        )
                   THEN 1
                   ELSE 0
                 END )
</code>```

SQL Fiddle

```<code>CREATE TABLE your_table
    ([EEBDCY] int, [EEBDYR] int, [EEBDMT] int, [EEBDDY] int)
;

INSERT INTO your_table
    ([EEBDCY], [EEBDYR], [EEBDMT], [EEBDDY])
VALUES
    (1900, 50, 3, 13),
    (1900, 50, 12, 31),
    (1900, 51, 3, 13),
    (1900, 51, 12, 31),
    (1900, 52, 3, 13),
    (1900, 52, 12, 31),
    (1900, 53, 3, 13),
    (1900, 53, 12, 31),
    (1900, 54, 3, 13),
    (1900, 54, 12, 31),
    (1900, 49, 3, 13),
    (1900, 49, 12, 31),
    (1900, 64, 3, 13),
    (1900, 64, 12, 31)
;
</code>```

Query 1:

```<code>select
      *
      , YEAR(CompareDate) - (EEBDCY + EEBDYR)
            - ( CASE
                   WHEN MONTH(EEBDMT) > MONTH(CompareDate)
                     OR ( MONTH(EEBDMT) = MONTH(CompareDate)
                        AND DAY(EEBDDY) > DAY(CompareDate)
                        )
                   THEN 1
                   ELSE 0
                 END ) as Age
from your_table
cross apply (
    select DATEFROMPARTS((EEBDCY + EEBDYR), EEBDMT, EEBDDY), dateadd(month,3,getdate())
    ) ca (Birthdate, CompareDate)
where 65 <= YEAR(CompareDate) - (EEBDCY + EEBDYR)
            - ( CASE
                   WHEN MONTH(EEBDMT) > MONTH(CompareDate)
                     OR ( MONTH(EEBDMT) = MONTH(CompareDate)
                        AND DAY(EEBDDY) > DAY(CompareDate)
                        )
                   THEN 1
                   ELSE 0
                 END )
order by birthdate
</code>```

Results:

```<code>| EEBDCY | EEBDYR | EEBDMT | EEBDDY |  Birthdate |              CompareDate | Age |
|--------|--------|--------|--------|------------|--------------------------|-----|
|   1900 |     49 |      3 |     13 | 1949-03-13 | 2018-03-06T03:14:52.793Z |  69 |
|   1900 |     49 |     12 |     31 | 1949-12-31 | 2018-03-06T03:14:52.793Z |  69 |
|   1900 |     50 |      3 |     13 | 1950-03-13 | 2018-03-06T03:14:52.793Z |  68 |
|   1900 |     50 |     12 |     31 | 1950-12-31 | 2018-03-06T03:14:52.793Z |  68 |
|   1900 |     51 |      3 |     13 | 1951-03-13 | 2018-03-06T03:14:52.793Z |  67 |
|   1900 |     51 |     12 |     31 | 1951-12-31 | 2018-03-06T03:14:52.793Z |  67 |
|   1900 |     52 |      3 |     13 | 1952-03-13 | 2018-03-06T03:14:52.793Z |  66 |
|   1900 |     52 |     12 |     31 | 1952-12-31 | 2018-03-06T03:14:52.793Z |  66 |
|   1900 |     53 |      3 |     13 | 1953-03-13 | 2018-03-06T03:14:52.793Z |  65 |
|   1900 |     53 |     12 |     31 | 1953-12-31 | 2018-03-06T03:14:52.793Z |  65 |
</code>```

Body:
I'm trying to write a query where I can calculate individuals that will be turning 65 based on their birth date while using the current date(GETDATE). However, the query also requires that I be able to pull individuals who will be turning 65 within 3 months of the current date(GETDATE). So far, I've only been able to pull individuals by entering a parameter of 19 into my century field (eebdcy) and entering 52 in my year field (eebdyr). I would like to remove these 2 fields and allow the user to just run the query without having to fiddle with my date fields. Is this possible?

Thank you in advance.

My Code:

SELECT
distinct eessn AS SSN, eenaml AS LastName, eenamf AS FirstName, eenamm AS MiddleInitial,
         ( RIGHT('00'+ CONVERT(varchar, EEBDCY), 2) + RIGHT('00'+ CONVERT(varchar, EEBDYR), 2) + '-' + RIGHT('00'+ CONVERT(varchar, EEBDMT), 2) + '-' + RIGHT('00' + CONVERT(varchar, EEBDDY), 2) ) AS [DOB],
         phprid AS ProductID, phacct AS AccountNumber, amplac AS  AccountName, amua12 AS MSPInd, phgrp AS GroupID,
         ( RIGHT('00'+ CONVERT(varchar, amfxc2), 2) + RIGHT('00'+ CONVERT(varchar, amfxy2), 2) + '-' + RIGHT('00'+ CONVERT(varchar, amfxm2), 2) + '-' + RIGHT('00' + CONVERT(varchar, amfxd2), 2) ) as MSPEFFDT,
         substring(amuaky,1,3) as REP,
         CONVERT (date, GETDATE()) AS [TODAY],
        CAST(DATEDIFF(DD,( RIGHT('00'+ CONVERT(varchar, EEBDCY), 2) + RIGHT('00'+ CONVERT(varchar, EEBDYR), 2) + '-' + RIGHT('00'+ CONVERT(varchar, EEBDMT), 2) + '-' + RIGHT('00' + CONVERT(varchar, EEBDDY), 2) ), GETDATE())/365.25 AS INT) AS AGE
    FROM pdthist, empmstr, actmstr
   WHERE phgrp in ('4664 ESP','4664 XM')
     and phpcat = 3 and phtdcy = 0
     and eessn = phssn and eegrp = phgrp
     and phacct = amacct and phgrp = amgrp and amtdcy = 0
     and eebdcy = 19 and eebdyr = 52
    ORDER BY phacct, eessn

Body:
I believe this would work:

select
*
from your_table
cross apply (
    select DATEFROMPARTS((EEBDCY + EEBDYR), EEBDMT, EEBDDY), dateadd(month,3,getdate())
    ) ca (Birthdate, CompareDate)
where 65 <= YEAR(CompareDate) - (EEBDCY + EEBDYR)
            - ( CASE
                   WHEN MONTH(EEBDMT) > MONTH(CompareDate)
                     OR ( MONTH(EEBDMT) = MONTH(CompareDate)
                        AND DAY(EEBDDY) > DAY(CompareDate)
                        )
                   THEN 1
                   ELSE 0
                 END )

SQL Fiddle

CREATE TABLE your_table
    ([EEBDCY] int, [EEBDYR] int, [EEBDMT] int, [EEBDDY] int)
;

INSERT INTO your_table
    ([EEBDCY], [EEBDYR], [EEBDMT], [EEBDDY])
VALUES
    (1900, 50, 3, 13),
    (1900, 50, 12, 31),
    (1900, 51, 3, 13),
    (1900, 51, 12, 31),
    (1900, 52, 3, 13),
    (1900, 52, 12, 31),
    (1900, 53, 3, 13),
    (1900, 53, 12, 31),
    (1900, 54, 3, 13),
    (1900, 54, 12, 31),
    (1900, 49, 3, 13),
    (1900, 49, 12, 31),
    (1900, 64, 3, 13),
    (1900, 64, 12, 31)
;

Query 1:

select
      *
      , YEAR(CompareDate) - (EEBDCY + EEBDYR)
            - ( CASE
                   WHEN MONTH(EEBDMT) > MONTH(CompareDate)
                     OR ( MONTH(EEBDMT) = MONTH(CompareDate)
                        AND DAY(EEBDDY) > DAY(CompareDate)
                        )
                   THEN 1
                   ELSE 0
                 END ) as Age
from your_table
cross apply (
    select DATEFROMPARTS((EEBDCY + EEBDYR), EEBDMT, EEBDDY), dateadd(month,3,getdate())
    ) ca (Birthdate, CompareDate)
where 65 <= YEAR(CompareDate) - (EEBDCY + EEBDYR)
            - ( CASE
                   WHEN MONTH(EEBDMT) > MONTH(CompareDate)
                     OR ( MONTH(EEBDMT) = MONTH(CompareDate)
                        AND DAY(EEBDDY) > DAY(CompareDate)
                        )
                   THEN 1
                   ELSE 0
                 END )
order by birthdate

Results:

| EEBDCY | EEBDYR | EEBDMT | EEBDDY |  Birthdate |              CompareDate | Age |
|--------|--------|--------|--------|------------|--------------------------|-----|
|   1900 |     49 |      3 |     13 | 1949-03-13 | 2018-03-06T03:14:52.793Z |  69 |
|   1900 |     49 |     12 |     31 | 1949-12-31 | 2018-03-06T03:14:52.793Z |  69 |
|   1900 |     50 |      3 |     13 | 1950-03-13 | 2018-03-06T03:14:52.793Z |  68 |
|   1900 |     50 |     12 |     31 | 1950-12-31 | 2018-03-06T03:14:52.793Z |  68 |
|   1900 |     51 |      3 |     13 | 1951-03-13 | 2018-03-06T03:14:52.793Z |  67 |
|   1900 |     51 |     12 |     31 | 1951-12-31 | 2018-03-06T03:14:52.793Z |  67 |
|   1900 |     52 |      3 |     13 | 1952-03-13 | 2018-03-06T03:14:52.793Z |  66 |
|   1900 |     52 |     12 |     31 | 1952-12-31 | 2018-03-06T03:14:52.793Z |  66 |
|   1900 |     53 |      3 |     13 | 1953-03-13 | 2018-03-06T03:14:52.793Z |  65 |
|   1900 |     53 |     12 |     31 | 1953-12-31 | 2018-03-06T03:14:52.793Z |  65 |


问:
Giving an array of indexes, how to push items from one array to another depending on the indexes that are specified?
I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :

```<code>var myArray = [['Apples',22],['Orange',55],['Berry',23]];
</code>```

Another array with the order it should be in :

```<code>var myOrder = [0,2,1];
</code>```

My resulting array would look like this :

```<code>var finalArray = [['Apples',22],['Berry',23],['Orange',55]]
</code>```

My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!

答:
One of way solving this will be

```<code>var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray;
for (x in myOrder) {
    finalArray[x] = myArray[myOrder[x]];
}
</code>```

This is a beginning level solution. Also you use libraries available for java script such as underscore.js(http://underscorejs.org/) for such operations on Array and Object.

Also you can use ECMA 6, for doing this which will reduce your line of coding.
Example-

```<code>var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let finalArray = myOrder.map(i =>  myArray[i])
</code>```

This is the new way of coding in javascript.
In my point of view, it will be easy if you learn latest version of Java script(ECMAscript 6)

Body:
I am trying to push items from one Array to another depending on the order that is supplied. Essentially i have a 2d array with a name and a price :

var myArray = [['Apples',22],['Orange',55],['Berry',23]];

Another array with the order it should be in :

var myOrder = [0,2,1];

My resulting array would look like this :

var finalArray = [['Apples',22],['Berry',23],['Orange',55]]

My initial thought process was to loop through myArray and loop through myOrder , store the object temporary at a specified index in myOrder then push to final array. I think i am over thinking it a bit, i made several attempts but with no luck whatsoever. Any help would be greatly appreciated!

Body:
One of way solving this will be

var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
var finalArray;
for (x in myOrder) {
    finalArray[x] = myArray[myOrder[x]];
}

This is a beginning level solution. Also you use libraries available for java script such as underscore.js(http://underscorejs.org/) for such operations on Array and Object.

Also you can use ECMA 6, for doing this which will reduce your line of coding.
Example-

var myArray = [['Apples',22],['Orange',55],['Berry',23]];
var myOrder = [0,2,1];
let finalArray = myOrder.map(i =>  myArray[i])

This is the new way of coding in javascript.
In my point of view, it will be easy if you learn latest version of Java script(ECMAscript 6)


问:
Repeat Python function call on exception?
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

```<code>try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2
</code>```

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

答:
Try following snippet:

```<code>while True:
    try:
        func()
        break
    except:
        print "Error. Gonna try again"
</code>```

But it is better to limit the number of retries.

Body:
Hey everybody I'm working on a data scraping project and I'm looking for a clean way to repeat a function call if an exception is raised.

Pseudo-code:

try:
    myfunc(x)
except myError:
    ###try to call myfunc(x) again Y number of times,
        until success(no exceptions raised) otherwise raise myError2

I realize this isn't best practice at all but I'm working through a number of different code/network layers that aren't reliable and I can't realistically debug them.

Right now I'm accomplishing this with a huge set of try\except blocks and it's making my eyes bleed.

Elegant ideas anyone?

Body:
Try following snippet:

while True:
    try:
        func()
        break
    except:
        print "Error. Gonna try again"

But it is better to limit the number of retries.


问:
How to generate files in a docker container for having the same owner as the host's user
I use docker containers to get some development tasks done in my git repositories.

The containers I use are built specifically for each project, that way each contributor only need docker CLI to get things done.

The bad side is the container run as root, thus generated files are owned by root once the container stops, and that's bad..

I can't change the owner in the container before exiting because there isn't the required user in the container /etc/passwd file.

I would create a user in the container before compiling the docker image but then the container won't be universal (for all my dev team).

What is the best practice(s) about that ?

答:
You can add your user to the image, launch the container as root, and use an entrypoint to adjust the uid/gid inside the container to match that of the volume mounts from your devs. Then switch to your container user to run your app.

To implement this, I've used an entrypoint shell script that includes the following lines:

```<code>  OLD_UID=`getent passwd "${opt_u}" | cut -f3 -d:`
  NEW_UID=`ls -nd "$1" | cut -f3 -d' '`
  if [ "$OLD_UID" != "$NEW_UID" ]; then
    usermod -u "$NEW_UID" "$opt_u"
    if [ -n "$opt_r" ]; then
      find / -mount -uid "$OLD_UID" -exec chown "$opt_u" {} \;
    fi
  fi
  OLD_GID=`getent group "${opt_g}" | cut -f3 -d:`
  NEW_GID=`ls -nd "$1" | cut -f4 -d' '`
  if [ "$OLD_GID" != "$NEW_GID" ]; then
    groupmod -g "$NEW_GID" "$opt_g"
    if [ -n "$opt_r" ]; then
      find / -mount -gid "$OLD_GID" -exec chgrp "$opt_g" {} \;
    fi
  fi
</code>```

In that script, $1 is the volume mount path, opt_u is the username inside the container, opt_g is the group name, and opt_r is a flag to recursively adjust the filesystem inside the container.

At the very end of my entrypoint, I kick off:

```<code>exec gosu "${RUN_AS}" "$@"
</code>```

Which switches to the user $RUN_AS and exec's the command passed to the entrypoint as that user, and as pid 1. Gosu is used to avoid su running as pid 1.

I've posted a similar example of this before with Jenkins as the app inside the container to match the GID of the docker socket. You can find the repo with all the steps here: https://github.com/bmitch3020/jenkins-docker

This has the significant upside of making the image portable to any developer system, and they can run it with the same command. Whatever the permissions are on the filesystem they map into the container from outside become the uid/gid of the user running commands inside the container. There's no need to lookup the local uid/gid on the developer system for your docker run command, or build your image on each developer workstation with unique uid/gid entries. The only downside of this implementation is that docker exec will enter the container as root, since you need to run your entrypoint as root for access to modify users/groups and filesystem ownership.

Body:
You can add your user to the image, launch the container as root, and use an entrypoint to adjust the uid/gid inside the container to match that of the volume mounts from your devs. Then switch to your container user to run your app.

To implement this, I've used an entrypoint shell script that includes the following lines:

  OLD_UID=`getent passwd "${opt_u}" | cut -f3 -d:`
  NEW_UID=`ls -nd "$1" | cut -f3 -d' '`
  if [ "$OLD_UID" != "$NEW_UID" ]; then
    usermod -u "$NEW_UID" "$opt_u"
    if [ -n "$opt_r" ]; then
      find / -mount -uid "$OLD_UID" -exec chown "$opt_u" {} \;
    fi
  fi
  OLD_GID=`getent group "${opt_g}" | cut -f3 -d:`
  NEW_GID=`ls -nd "$1" | cut -f4 -d' '`
  if [ "$OLD_GID" != "$NEW_GID" ]; then
    groupmod -g "$NEW_GID" "$opt_g"
    if [ -n "$opt_r" ]; then
      find / -mount -gid "$OLD_GID" -exec chgrp "$opt_g" {} \;
    fi
  fi

In that script, $1 is the volume mount path, opt_u is the username inside the container, opt_g is the group name, and opt_r is a flag to recursively adjust the filesystem inside the container.

At the very end of my entrypoint, I kick off:

exec gosu "${RUN_AS}" "$@"

Which switches to the user $RUN_AS and exec's the command passed to the entrypoint as that user, and as pid 1. Gosu is used to avoid su running as pid 1.

I've posted a similar example of this before with Jenkins as the app inside the container to match the GID of the docker socket. You can find the repo with all the steps here: https://github.com/bmitch3020/jenkins-docker

This has the significant upside of making the image portable to any developer system, and they can run it with the same command. Whatever the permissions are on the filesystem they map into the container from outside become the uid/gid of the user running commands inside the container. There's no need to lookup the local uid/gid on the developer system for your docker run command, or build your image on each developer workstation with unique uid/gid entries. The only downside of this implementation is that docker exec will enter the container as root, since you need to run your entrypoint as root for access to modify users/groups and filesystem ownership.


问:
Firebase functions: storage cannot be stubbed when writing unit tests
I have the following functions code inside index.js:

```<code>var admin = require('firebase-admin');
admin.initializeApp();
admin.storage();
</code>```

And the following test code:

```<code>var assert = require('assert');
var sinon = require('sinon');
describe('Event Sourcing', function() {
  var myFunctions, adminInitStub, adminStorageStub,admin;

  before(() => {
    admin =  require('firebase-admin');
    adminStorageStub = sinon.stub(admin, 'storage');
    adminInitStub = sinon.stub(admin, 'initializeApp');

    myFunctions = require('../index');
  });

  after(() => {
    // Restoring our stubs to the original methods.
    adminInitStub.restore();
    adminStorageStub.restore();
  });

  describe('CREATED', function() {
      it('should return -1 when the value is not present', function() {
            assert.equal(-1, [1,5,3].indexOf(4));
          });
    });
});
</code>```

For some strange reason, I keep getting the following error Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services. but I've clearly stubbed it. Why does stubbing work for initializeApp() but not storage().

Thanks!

答:
admin.storage() is actually a getter and therefore needs to be stubbed this way

```<code>adminStorageStub = sinon.stub(admin, 'storage').get(() => {
  return () => {
    return {bucket: (() => {})};
  }
});
</code>```

More info on sinon stubs can be found here http://sinonjs.org/releases/v2.0.0/stubs/

Body:
I have the following functions code inside index.js:

var admin = require('firebase-admin');
admin.initializeApp();
admin.storage();

And the following test code:

var assert = require('assert');
var sinon = require('sinon');
describe('Event Sourcing', function() {
  var myFunctions, adminInitStub, adminStorageStub,admin;

  before(() => {
    admin =  require('firebase-admin');
    adminStorageStub = sinon.stub(admin, 'storage');
    adminInitStub = sinon.stub(admin, 'initializeApp');

    myFunctions = require('../index');
  });

  after(() => {
    // Restoring our stubs to the original methods.
    adminInitStub.restore();
    adminStorageStub.restore();
  });

  describe('CREATED', function() {
      it('should return -1 when the value is not present', function() {
            assert.equal(-1, [1,5,3].indexOf(4));
          });
    });
});

For some strange reason, I keep getting the following error Error: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services. but I've clearly stubbed it. Why does stubbing work for initializeApp() but not storage().

Thanks!

Body:
admin.storage() is actually a getter and therefore needs to be stubbed this way

adminStorageStub = sinon.stub(admin, 'storage').get(() => {
  return () => {
    return {bucket: (() => {})};
  }
});

More info on sinon stubs can be found here http://sinonjs.org/releases/v2.0.0/stubs/


问:
How to get the next page on spring pagination
I have a resource in my service with pagination and I would like to know how could I process the next request to get the second page.

Here is the java resource:

```<code>@GetMapping(value = "/partner/codes")
public Page<String> getCodes(@PageableDefault(size = 5) Pageable pageable) {
    final List<String> userIds = service.getIds();
    int start = pageable.getOffset();
    int end = (start + pageable.getPageSize()) > userIds.size() ? userIds.size() : (start + pageable.getPageSize());

    return new PageImpl<String>(userIds.subList(start, end), pageable, userIds.size());
}
</code>```

And the response the response with 5 results:

```<code>{
  "content":[
    "4a136aa6-00d4-44f0-bb48-d192fd8bc010",
    "bebebaf2-b881-4733-8a65-1ecf80b5192e",
    "1a0f9d07-1393-48a8-8883-37d87681e84b",
    "d2580fdc-db6c-4fa3-89d4-2b52898a20bf",
    "2c90e683-4ed4-45a4-b70b-614a3339670b"
   ],
   "last":false,
   "totalPages":3,
   "totalElements":57,
   "size":20,
   "number":0,
   "sort":null,
   "numberOfElements":20,
   "first":true
}
</code>```

答:
I'm sorry, as there was nothing explicit in the documentation, I hadn't noticed that just passing the parameters in the query string.

```<code>?page=2&size=20
</code>```

And the client should create the rule using the response message.

Body:
I have a resource in my service with pagination and I would like to know how could I process the next request to get the second page.

Here is the java resource:

@GetMapping(value = "/partner/codes")
public Page<String> getCodes(@PageableDefault(size = 5) Pageable pageable) {
    final List<String> userIds = service.getIds();
    int start = pageable.getOffset();
    int end = (start + pageable.getPageSize()) > userIds.size() ? userIds.size() : (start + pageable.getPageSize());

    return new PageImpl<String>(userIds.subList(start, end), pageable, userIds.size());
}

And the response the response with 5 results:

{
  "content":[
    "4a136aa6-00d4-44f0-bb48-d192fd8bc010",
    "bebebaf2-b881-4733-8a65-1ecf80b5192e",
    "1a0f9d07-1393-48a8-8883-37d87681e84b",
    "d2580fdc-db6c-4fa3-89d4-2b52898a20bf",
    "2c90e683-4ed4-45a4-b70b-614a3339670b"
   ],
   "last":false,
   "totalPages":3,
   "totalElements":57,
   "size":20,
   "number":0,
   "sort":null,
   "numberOfElements":20,
   "first":true
}

Body:
I'm sorry, as there was nothing explicit in the documentation, I hadn't noticed that just passing the parameters in the query string.

?page=2&size=20

And the client should create the rule using the response message.


问:
synchronization in simple socket programming in C
I want to create a simple multithreaded chat application in C using api. For the beginning, i wrote a simple  server communicating with client but there is a problem in the order messages sent.

example output:

in server

*new_sock socket number: 4

Server:hello client

Client:hello server

Server:how are you?

Client:

Server:

in client

Server:hello client

Client:hello server

Server:how are you?

Client:

```<code>    //server code
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/socket.h>
    #include <sys/types.h>
    #include <netinet/in.h>
    #include <pthread.h>

void* connection_handler(void* socket_descriptor)
{

    int socket = *(int *)socket_descriptor;

    int n;

    char server_buffer[256];
    memset(server_buffer, 0, sizeof(server_buffer));

    printf("Server:");
    gets(server_buffer);

    send(socket, server_buffer, strlen(server_buffer), 0);
    memset(server_buffer, 0, sizeof(server_buffer));

    while ((n = recv(socket, server_buffer, 255, 0)) > 0)
    {
        server_buffer[n] = '\0';
        printf("Client:%s\n", server_buffer);
        memset(server_buffer, 0, sizeof(server_buffer));
        printf("Server:");
        gets(server_buffer);
        send(socket, server_buffer, strlen(server_buffer), 0);
        memset(server_buffer, 0, sizeof(server_buffer));

        n = 0;
    }

    close(socket);

    free(socket_descriptor);

    return 0;
}

int main(int argc, char *argv[])
{
    int server_sock, client_sock, portno, client_len, n;
    int *new_sock;

    struct sockaddr_in server_addr, client_addr;

    if(argc < 2)
    {
        printf("ERROR: no port provided.\n");
        exit(1);
    }

    server_sock = socket(AF_INET, SOCK_STREAM, 0);

    if(server_sock < 0)
    {
        printf("ERROR: opening socket.");
        exit(1);
    }

    portno = atoi(argv[1]);

    memset((char *)&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(portno);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    if( bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0 )
    {
        printf("ERROR: binding socket.");
        exit(1);
    }

    listen(server_sock, 5);

    pthread_t handler_thread;

    while( client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_len) )
    {

        new_sock = malloc(sizeof(int));
        *new_sock = client_sock;

        printf("*new_sock socket number: %d\n", *new_sock);

        if( pthread_create(&handler_thread, (void *)NULL, connection_handler, (void *)new_sock) < 0)
        {
            printf("ERROR: creating thread\n");
            exit(1);
        }

    }

    pthread_join(handler_thread, NULL);

    printf("server shut down.\n");

    return 0;
}

//client code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

int main(int argc, char* argv[])
{
    int sock_descriptor, portno, n;

    struct sockaddr_in server_addr;

    char buffer[256];

    if (argc != 2)
    {
        printf("usage: %s port\n", argv[0]);
        exit(1);
    }

    portno = atoi(argv[1]);

    sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);

    if (sock_descriptor < 0)
    {
        printf("ERROR: creating socket!\n");
        exit(1);
    }

    memset((char *)&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(portno);

    if (connect(sock_descriptor, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        printf("ERROR: connecting server!\n");
        exit(1);
    }

    memset(buffer, 0, sizeof(buffer));

    while((n = recv(sock_descriptor, buffer, 255, 0)) > 0)
    {
        buffer[n] = '\0';
        printf("Server:%s\n", buffer);
        memset(buffer, 0, sizeof(buffer));
        printf("Client:");
        gets(buffer);
        send(sock_descriptor, buffer, sizeof(buffer), 0);
        memset(buffer, 0, sizeof(buffer));

    }

    if (n <= 0)
    {
        printf("ERROR: reading from socket");
        exit(1);
    }

    return 0;
}
</code>```

答:
Join the threads right after it has been created , accept is a blocking call (I assume you have not modified the default behavior) . Threads are complex to analyze however , the call to join wont even come since blocking accept call in while loop.</p>

```<code>while(1)
 {
    //do something here
    ...
    if( pthread_create(&handler_thread, (void *)NULL, connection_handler, (void *)new_sock) < 0)
    {
        printf("ERROR: creating thread\n");
        exit(1);
    }

    pthread_join(handler_thread, NULL); //Use it right after creating thread
}
</code>```

Body:
I want to create a simple multithreaded chat application in C using api. For the beginning, i wrote a simple  server communicating with client but there is a problem in the order messages sent.

example output:

in server

*new_sock socket number: 4

Server:hello client

Client:hello server

Server:how are you?

Client:

Server:

in client

Server:hello client

Client:hello server

Server:how are you?

Client:

    //server code
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/socket.h>
    #include <sys/types.h>
    #include <netinet/in.h>
    #include <pthread.h>

void* connection_handler(void* socket_descriptor)
{

    int socket = *(int *)socket_descriptor;

    int n;

    char server_buffer[256];
    memset(server_buffer, 0, sizeof(server_buffer));

    printf("Server:");
    gets(server_buffer);

    send(socket, server_buffer, strlen(server_buffer), 0);
    memset(server_buffer, 0, sizeof(server_buffer));

    while ((n = recv(socket, server_buffer, 255, 0)) > 0)
    {
        server_buffer[n] = '\0';
        printf("Client:%s\n", server_buffer);
        memset(server_buffer, 0, sizeof(server_buffer));
        printf("Server:");
        gets(server_buffer);
        send(socket, server_buffer, strlen(server_buffer), 0);
        memset(server_buffer, 0, sizeof(server_buffer));

        n = 0;
    }

    close(socket);

    free(socket_descriptor);

    return 0;
}

int main(int argc, char *argv[])
{
    int server_sock, client_sock, portno, client_len, n;
    int *new_sock;

    struct sockaddr_in server_addr, client_addr;

    if(argc < 2)
    {
        printf("ERROR: no port provided.\n");
        exit(1);
    }

    server_sock = socket(AF_INET, SOCK_STREAM, 0);

    if(server_sock < 0)
    {
        printf("ERROR: opening socket.");
        exit(1);
    }

    portno = atoi(argv[1]);

    memset((char *)&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(portno);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    if( bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0 )
    {
        printf("ERROR: binding socket.");
        exit(1);
    }

    listen(server_sock, 5);

    pthread_t handler_thread;

    while( client_sock = accept(server_sock, (struct sockaddr *)&client_addr, &client_len) )
    {

        new_sock = malloc(sizeof(int));
        *new_sock = client_sock;

        printf("*new_sock socket number: %d\n", *new_sock);

        if( pthread_create(&handler_thread, (void *)NULL, connection_handler, (void *)new_sock) < 0)
        {
            printf("ERROR: creating thread\n");
            exit(1);
        }

    }

    pthread_join(handler_thread, NULL);

    printf("server shut down.\n");

    return 0;
}

//client code
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

int main(int argc, char* argv[])
{
    int sock_descriptor, portno, n;

    struct sockaddr_in server_addr;

    char buffer[256];

    if (argc != 2)
    {
        printf("usage: %s port\n", argv[0]);
        exit(1);
    }

    portno = atoi(argv[1]);

    sock_descriptor = socket(AF_INET, SOCK_STREAM, 0);

    if (sock_descriptor < 0)
    {
        printf("ERROR: creating socket!\n");
        exit(1);
    }

    memset((char *)&server_addr, 0, sizeof(server_addr));

    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(portno);

    if (connect(sock_descriptor, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0)
    {
        printf("ERROR: connecting server!\n");
        exit(1);
    }

    memset(buffer, 0, sizeof(buffer));

    while((n = recv(sock_descriptor, buffer, 255, 0)) > 0)
    {
        buffer[n] = '\0';
        printf("Server:%s\n", buffer);
        memset(buffer, 0, sizeof(buffer));
        printf("Client:");
        gets(buffer);
        send(sock_descriptor, buffer, sizeof(buffer), 0);
        memset(buffer, 0, sizeof(buffer));

    }

    if (n <= 0)
    {
        printf("ERROR: reading from socket");
        exit(1);
    }

    return 0;
}

Body:
Join the threads right after it has been created , accept is a blocking call (I assume you have not modified the default behavior) . Threads are complex to analyze however , the call to join wont even come since blocking accept call in while loop.

while(1)
 {
    //do something here
    ...
    if( pthread_create(&handler_thread, (void *)NULL, connection_handler, (void *)new_sock) < 0)
    {
        printf("ERROR: creating thread\n");
        exit(1);
    }

    pthread_join(handler_thread, NULL); //Use it right after creating thread
}


答:
Use a loop</p>

```<code>i = 0
while True:
  try: myfunc(x); break;
  except myError:
    i = i + 1;
    # print "Trying again"
    if i > 5: raise myError2;
</code>```

Title: Repeat Python function call on exception?

Body:
Use a loop

i = 0
while True:
  try: myfunc(x); break;
  except myError:
    i = i + 1;
    # print "Trying again"
    if i > 5: raise myError2;


问:
Checking a password
I think I have the right idea of solving this function, but I'm not sure why
I don't get the desired results shown in the docstring. Can anyone please help me fix this?</p>

```<code>def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
    if char.isdigit():
        if  char.islower():
            if char.isupper():
                return True
else:
    return False
</code>```

答: The reason this doesn't work is that for any given character, it first checks if it's a digit, then if it's lower, then if it's upper. Obviously, one character cannot be all three of these at once. You instead want to check each character to see if it's a digit, lowercase, or uppercase, and then flip a boolean value like has_upper. Then, after the for loop, you'll check to see if all of the boolean values are true.

Title: Checking a password

Body:
I think I have the right idea of solving this function, but I'm not sure why
I don't get the desired results shown in the docstring. Can anyone please help me fix this?

def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
    if char.isdigit():
        if  char.islower():
            if char.isupper():
                return True
else:
    return False


问:
Chef windows how to click a button in a GUI
There is a bat file which does some configurations and launch a GUI .In that GUI some buttons need to be clicked to install some other software components .Chef supports these scenarios? How to automate them using Chef? It's a 3rd party installer and has lot of code so deciding it is difficult .Launching a GUI and clicking on a button is easier..vendor has not provided any commands or API..</p>

答: This is not something Chef does. If the installer doesn't have a headless mode you'll have to look at dedicated Windows automation tools like AutoIt.</p>


问:
Enable 'upload' and 'new folder' in elFinder under IIS windows environment
I installed elFinder to my IIS 7.0 with php 7.0, followed by install guide.

But I cannot find write permission required action such as - "Upload files", "New folder" in context menu.

By response from connector's response, "writes":0, so I it caused by root folder is locked.

But I don't how can unlock and enable these features.

I tried to compare another environment with apache + php at windows.  It works.

Files that I installed is same to original repo condition.

When I checked upload folder (default value: elfinder/files) is also normal - it's permission is full control to IIS_User.

Which point that my should check?

答:
I managed to resolve it.

The problem was that it require IUser permission not IIS_User.
When I add IUser to elfiner's upload folder, it works well.


问:
Split table row into two fields and count each
So far I have wrote the following query:

```<code>SELECT forum_topics.*, users.id as userid, users.username, users.avatar, forum_categories.name as cat_name
FROM forum_topics
INNER JOIN users
ON users.id = forum_topics.author_id
INNER JOIN forum_categories
ON forum_categories.id = forum_topics.category_id
WHERE forum_topics.id = 64
</code>```

But I also want to add another table votes that has the following structure:

```<code>___________________________________________________________
| id | object_type | object_id | receiver | giver | type    |
___________________________________________________________
| 128| topic       |     64    |    21    |  22   | like    |
| 129| topic_reply |     55    |    21    |  22   | dislike |
___________________________________________________________
</code>```

Basically the relation between the two tables is forum_topics.id from Table 1 and  object_id from Table 2 (the bottom one). This is for a forum and I want to display likes/dislikes for each topic and reply. type could be like and dislike. receiver is the user that made the post, giver is the user that voted. I want to INNER JOIN the votes table in the first query and count all likes and dislikes into two separate fields. Something like:

Select votes.count(*) as likes WHERE type = 'like and votes.count(*) as dislikes WHERE type = 'dislike'
The query got so complicated and I am so confused.

Edit: So I figured it out for forum_topics. Here is how I did it:

```<code>    SELECT forum_topics.*, users.id as userid, users.username, users.avatar, forum_categories.name as cat_name,
   count(CASE WHEN votes.type = 'like'    AND votes.object_type = 'topic'  then 1 else null end) as votes_likes,
   count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic'  then 1 else null end) as votes_dislikes
FROM forum_topics
INNER JOIN users
ON users.id = forum_topics.author_id
INNER JOIN forum_categories
ON forum_categories.id = forum_topics.category_id
INNER JOIN votes
ON votes.object_id = forum_topics.id
WHERE forum_topics.id = ?
</code>```

Now for forum_posts It is not working..

```<code>SELECT forum_posts.*, users.id as userid, users.username, users.avatar,
      count(CASE WHEN votes.type = 'like'    AND votes.object_type = 'topic_post' then 1 else null end) as votes_likes,
      count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic_post' then 1 else null end) as votes_dislikes
  FROM forum_posts
  INNER JOIN users
  ON users.id = forum_posts.author_id
  LEFT JOIN votes
  ON votes.object_id = forum_posts.id
  WHERE forum_posts.topic_id = 64
  ORDER BY forum_posts.id
</code>```

Any ideas how to fix it? In HeidiSQL it returns one row with everything NULL.

答:
You need a GROUP BY

```<code>SELECT forum_posts.id
       , forum_posts.author_id
       , forum_posts.editor_id
       , forum_posts.topic_id
       , forum_posts.content
       , forum_posts.date_created
       , forum_posts.updated
       , users.id as userid
       , users.username
       , users.avatar
       , count(CASE WHEN votes.type = 'like' AND votes.object_type = 'topic_post' THEN 1 ELSE NULL END) AS votes_likes
       , count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic_post' THEN 1 ELSE NULL END) AS votes_dislikes
FROM forum_posts
INNER JOIN users ON users.id = forum_posts.author_id
LEFT JOIN votes ON votes.object_id = forum_posts.id
WHERE forum_posts.topic_id = 64
GROUP BY forum_posts.id
       , forum_posts.author_id
       , forum_posts.editor_id
       , forum_posts.topic_id
       , forum_posts.content
       , forum_posts.date_created
       , forum_posts.updated
       , users.id
       , users.username
       , users.avatar
</code>```

Body:
So far I have wrote the following query:

SELECT forum_topics.*, users.id as userid, users.username, users.avatar, forum_categories.name as cat_name
FROM forum_topics
INNER JOIN users
ON users.id = forum_topics.author_id
INNER JOIN forum_categories
ON forum_categories.id = forum_topics.category_id
WHERE forum_topics.id = 64

But I also want to add another table votes that has the following structure:

___________________________________________________________
| id | object_type | object_id | receiver | giver | type    |
___________________________________________________________
| 128| topic       |     64    |    21    |  22   | like    |
| 129| topic_reply |     55    |    21    |  22   | dislike |
___________________________________________________________

Basically the relation between the two tables is forum_topics.id from Table 1 and  object_id from Table 2 (the bottom one). This is for a forum and I want to display likes/dislikes for each topic and reply. type could be like and dislike. receiver is the user that made the post, giver is the user that voted. I want to INNER JOIN the votes table in the first query and count all likes and dislikes into two separate fields. Something like:

Select votes.count(*) as likes WHERE type = 'like and votes.count(*) as dislikes WHERE type = 'dislike'
The query got so complicated and I am so confused.

Edit: So I figured it out for forum_topics. Here is how I did it:

    SELECT forum_topics.*, users.id as userid, users.username, users.avatar, forum_categories.name as cat_name,
   count(CASE WHEN votes.type = 'like'    AND votes.object_type = 'topic'  then 1 else null end) as votes_likes,
   count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic'  then 1 else null end) as votes_dislikes
FROM forum_topics
INNER JOIN users
ON users.id = forum_topics.author_id
INNER JOIN forum_categories
ON forum_categories.id = forum_topics.category_id
INNER JOIN votes
ON votes.object_id = forum_topics.id
WHERE forum_topics.id = ?

Now for forum_posts It is not working..

SELECT forum_posts.*, users.id as userid, users.username, users.avatar,
      count(CASE WHEN votes.type = 'like'    AND votes.object_type = 'topic_post' then 1 else null end) as votes_likes,
      count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic_post' then 1 else null end) as votes_dislikes
  FROM forum_posts
  INNER JOIN users
  ON users.id = forum_posts.author_id
  LEFT JOIN votes
  ON votes.object_id = forum_posts.id
  WHERE forum_posts.topic_id = 64
  ORDER BY forum_posts.id

Any ideas how to fix it? In HeidiSQL it returns one row with everything NULL.

Body:
You need a GROUP BY

SELECT forum_posts.id
       , forum_posts.author_id
       , forum_posts.editor_id
       , forum_posts.topic_id
       , forum_posts.content
       , forum_posts.date_created
       , forum_posts.updated
       , users.id as userid
       , users.username
       , users.avatar
       , count(CASE WHEN votes.type = 'like' AND votes.object_type = 'topic_post' THEN 1 ELSE NULL END) AS votes_likes
       , count(CASE WHEN votes.type = 'dislike' AND votes.object_type = 'topic_post' THEN 1 ELSE NULL END) AS votes_dislikes
FROM forum_posts
INNER JOIN users ON users.id = forum_posts.author_id
LEFT JOIN votes ON votes.object_id = forum_posts.id
WHERE forum_posts.topic_id = 64
GROUP BY forum_posts.id
       , forum_posts.author_id
       , forum_posts.editor_id
       , forum_posts.topic_id
       , forum_posts.content
       , forum_posts.date_created
       , forum_posts.updated
       , users.id
       , users.username
       , users.avatar


问:
How to learn professional JavaScript in two days?
I really need to learn professional javascript in two days because I am gonna have to hit the
ground running (real world project). I have little which can be approximated to no knowledge of JavaScript or website development. Any help would be appreciated greatly.</p>

答:
http://eloquentjavascript.net/

See also https://stackoverflow.com/questions/4744906/would-you-recommend-starting-from-html5-css3-for-beginners for resources on learning web technologies.


问:
Keras ValueError: Input 0 is incompatible with layer conv2d_1: expected ndim=4, found ndim=5
I have checked all the solutions, but still, I am facing the same error. My training images shape is (26721, 32, 32, 1), which I believe it is 4 dimension, but I don't know why error shows it is 5 dimension.

```<code> model = Sequential()

 model.add(Convolution2D(16, 5, 5, border_mode='same', input_shape= input_shape ))
</code>```

So this is how I am defining model.fit_generator

```<code>model.fit_generator(train_dataset, train_labels, nb_epoch=epochs, verbose=1,validation_data=(valid_dataset, valid_labels), nb_val_samples=valid_dataset.shape[0],callbacks=model_callbacks)
</code>```

答:
The problem is input_shape.

It should actually contain 3 dimensions only. And internally keras will add the batch dimension making it 4.

Since you probably used input_shape with 4 dimensions (batch included), keras is adding the 5th.

You should use input_shape=(32,32,1).

ContentLicense: CC BY-SA 4.0

Body:
I have checked all the solutions, but still, I am facing the same error. My training images shape is (26721, 32, 32, 1), which I believe it is 4 dimension, but I don't know why error shows it is 5 dimension.

 model = Sequential()

 model.add(Convolution2D(16, 5, 5, border_mode='same', input_shape= input_shape ))

So this is how I am defining model.fit_generator

model.fit_generator(train_dataset, train_labels, nb_epoch=epochs, verbose=1,validation_data=(valid_dataset, valid_labels), nb_val_samples=valid_dataset.shape[0],callbacks=model_callbacks)