问:
Signal handling error
When I use my_handler as function there is not error but I can't because I have to use another method there.

If I build code below :
 error: invalid use of member functi
on (did you forget the ‘()’ ?)

This is my first program in C++

```<code>void Client::my_handler(int s){
    if (s == SIGINT){
        printf("SIGINT\n");
    // here I have to use stop_thread method
    }
}

int main (int argc, const char **argv) {
  Client client(argc, argv);
  client.before_start();

  struct sigaction sigIntHandler;

  sigIntHandler.sa_handler = (__sighandler_t) client.my_handler; //error here
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;
  sigaction(SIGINT, &sigIntHandler, NULL);

  client.run();

  return 0;
}
</code>```

答:
@SJL has provided a great explanation of why this is not working, and offers a C-style workaround.

If you can use Boost, boost::asio::signal_set can be used to handle signals in a more C++ style. The async_wait function can receive a lambda, bound member function pointer, or any other callable type with the appropriate signature.

Title: Signal handling error

Body:
When I use my_handler as function there is not error but I can't because I have to use another method there.

If I build code below :
 error: invalid use of member functi
on (did you forget the ‘()’ ?)

This is my first program in C++

void Client::my_handler(int s){
    if (s == SIGINT){
        printf("SIGINT\n");
    // here I have to use stop_thread method
    }
}

int main (int argc, const char **argv) {
  Client client(argc, argv);
  client.before_start();

  struct sigaction sigIntHandler;

  sigIntHandler.sa_handler = (__sighandler_t) client.my_handler; //error here
  sigemptyset(&sigIntHandler.sa_mask);
  sigIntHandler.sa_flags = 0;
  sigaction(SIGINT, &sigIntHandler, NULL);

  client.run();

  return 0;
}


来源: stackexchange

问:
Why Faker does not return Datetime Object?
I am doing Laravel Testing and when I use faker->datetime() or faker->dateTime($max = 'now') for created and updated at but it always give me this error?

Error Message '2017-03-29 14:21:48' does not match expected type "object".

```<code>'created_at' => $faker->dateTime($max = 'now'),
'updated_at' => $faker->dateTime($max = 'now')
</code>```

答:
In faker dateTime() returns a timestamp.  Laravel uses Carbon under the hood for the timestamps.  You can create a Carbon instance from your Faker timestamp:

```<code>'created_at' => new Carbon($faker->dateTime($max = 'now')),
'updated_at' => new Carbon($faker->dateTime($max = 'now'))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am doing Laravel Testing and when I use faker->datetime() or faker->dateTime($max = 'now') for created and updated at but it always give me this error?

Error Message '2017-03-29 14:21:48' does not match expected type "object".

'created_at' => $faker->dateTime($max = 'now'),
'updated_at' => $faker->dateTime($max = 'now')

Body:
In faker dateTime() returns a timestamp.  Laravel uses Carbon under the hood for the timestamps.  You can create a Carbon instance from your Faker timestamp:

'created_at' => new Carbon($faker->dateTime($max = 'now')),
'updated_at' => new Carbon($faker->dateTime($max = 'now'))


问:
Optional error while converting from Swift 2 to 3 in keyboardWillShow notification
I am converting my app to Swift 3 at the moment and I have problems with this function I used to show the keyboard before.

Initializer for conditional binding must have Optional type, not 'CGFloat'

The error appears in the third line.

It's been a while since I've programmed the last time and so I am not sure how to solve this.

```<code>func keyboardWillShow(_ sender: Notification) {
        if let userInfo = sender.userInfo {
            if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
                let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
                let edgeInsets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
                UIView.animate(withDuration: duration!, animations: { () -> Void in
                    self.tableView.contentInset = edgeInsets
                    self.tableView.scrollIndicatorInsets = edgeInsets
                    self.view.layoutIfNeeded()
                })
            }
        }
    }
</code>```

答:
change

```<code>if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
</code>```

to

```<code>if let foo = userInfo[UIKeyboardFrameEndUserInfoKey] {
    let keyboardHeight = (foo as as AnyObject).cgRectValue.size.height
</code>```

--- UPDATE ---

or

```<code>if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject?).cgRectValue.size.height {
</code>```

AnyObject? works because AnyObject can contain Optional itself. So you have to casting to Optional explicitly. Either AnyObject? or Optional<AnyObject> will work.

Body:
I am converting my app to Swift 3 at the moment and I have problems with this function I used to show the keyboard before.

Initializer for conditional binding must have Optional type, not 'CGFloat'

The error appears in the third line.

It's been a while since I've programmed the last time and so I am not sure how to solve this.

func keyboardWillShow(_ sender: Notification) {
        if let userInfo = sender.userInfo {
            if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {
                let duration = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as AnyObject).doubleValue
                let edgeInsets = UIEdgeInsetsMake(0, 0, keyboardHeight, 0)
                UIView.animate(withDuration: duration!, animations: { () -> Void in
                    self.tableView.contentInset = edgeInsets
                    self.tableView.scrollIndicatorInsets = edgeInsets
                    self.view.layoutIfNeeded()
                })
            }
        }
    }

Body:
change

if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height {

to

if let foo = userInfo[UIKeyboardFrameEndUserInfoKey] {
    let keyboardHeight = (foo as as AnyObject).cgRectValue.size.height

--- UPDATE ---

or

if let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as AnyObject?).cgRectValue.size.height {

AnyObject? works because AnyObject can contain Optional itself. So you have to casting to Optional explicitly. Either AnyObject? or Optional<AnyObject> will work.


问:
How can I make certain parts of my html not selectable?
How can I make certain parts of my html not selectable?

I have some absolutely positioned divs that keep getting selected if a user tries to select the content of my page.

Is there a way to make it so certain elements (such as those divs) aren't selectable?

EDIT: The main issue is when someone copies these absolute div's and then pastes them into the rich text editor on my site, the rich text editor breaks on IE.

答:
this article might help with a cross-browser solution: (uses jQuery)
http://aleembawany.com/2009/01/20/disable-selction-on-menu-items-with-this-jquery-extension/

in theory, you can extend the jQUery core using this:

```<code>jQuery.fn.extend({
    disableSelection : function() {
            return this.each(function() {
                    this.onselectstart = function() { return false; };
                    this.unselectable = "on";
                    jQuery(this).addClass('unselectable');
            });
    }
});
</code>```

and applying it like this:

```<code>// disable selection on selected objects
$('.myClass').disableSelection();
</code>```

you must make sure you have this in your stylesheet:

```<code>.unselectable {
    user-select: none;
    -o-user-select: none;
    -moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
}
</code>```

looks as if it basically does what SLaks and Sime have mentioned.
i haven't tried it, but i'd be interested to know if it works

ContentLicense: CC BY-SA 2.5

Body:
this article might help with a cross-browser solution: (uses jQuery)
http://aleembawany.com/2009/01/20/disable-selction-on-menu-items-with-this-jquery-extension/

in theory, you can extend the jQUery core using this:

jQuery.fn.extend({
    disableSelection : function() {
            return this.each(function() {
                    this.onselectstart = function() { return false; };
                    this.unselectable = "on";
                    jQuery(this).addClass('unselectable');
            });
    }
});

and applying it like this:

// disable selection on selected objects
$('.myClass').disableSelection();

you must make sure you have this in your stylesheet:

.unselectable {
    user-select: none;
    -o-user-select: none;
    -moz-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
}

looks as if it basically does what SLaks and Sime have mentioned.
i haven't tried it, but i'd be interested to know if it works


问:
Inline SVG Element not working on Div
I have this snippet. My end game is to use a larger hexagon as a container for the generated hexagons. I am using an inline svg element but it does not seem that the mask is applying to the div with the inner class like I hoped. Am I implementing it wrong or missing something?

If I had to guess is it because my coordinates for the hexagon are larger than 1 which would break boundingBox?

$(document).ready(function() {
    var wrapper = document.getElementsByClassName('inner')[0];

    for(var i = 0; i <= 250; i++) {
      var hex = document.createElement('div');

      var colors = ['red-hex', 'blue-hex','yellow-hex'];
      var hexColor = Math.floor(Math.random() * colors.length);

      hex.className = 'hexagon ';
      hex.className += colors[hexColor];
      hex.innerHTML = '';

      var size = (Math.random()* (200-100)) + 100;
      hex.style.fontSize = size + 'px';

      var posx = (Math.random() * wrapper.offsetWidth - size).toFixed();
      var posy = (Math.random() * wrapper.offsetHeight - size).toFixed();

      hex.style.top = posy+'px';
      hex.style.left = posx+'px';

      wrapper.appendChild(hex);
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hexagon_wrapper {
  position: relative;
  width: 1000px;
  height: 1000px;
  margin: 0 auto;
}

.svg-defs {
  position: absolute;
  width: 0;
  height: 0;
 }

.inner {
  position: relative;
  width: 100%;
  height: 100%;
  -webkit-clip-path: url("#clipping");
          clip-path: url("#clipping");
}

.hexagon {
  position: absolute;
  /* mix-blend-mode: color-dodge; looks wicked */
  mix-blend-mode: saturation;
  padding: 10px;
}

.red-hex {
  color: #fe412b;
  -webkit-animation:fade-in 6s infinite;
}

.blue-hex {
  color: #39b1e3;
  -webkit-animation:fade-in 5s infinite;
}

.yellow-hex {
  color: #fcfe41;
  -webkit-animation:fade-in 4s infinite;
}

@-webkit-keyframes fade-in{
  0%, 100% {
    opacity: 0.9;
  }
  50% {
    opacity: 0.5;
  }
}</code>```

<link href="https://cdn.materialdesignicons.com/1.8.36/css/materialdesignicons.min.css" rel="stylesheet"/>

  <svg class="svg-defs">
    <defs>
      <clipPath id="clipping" clipPathUnits ="objectBoundingBox">
        <polygon points="50 1 95 25 95 75 50 99 5 75 5 25" />
      </clipPath>
    </defs>
  </svg>

```

答:
I have rewritten your polygon to fit within a viewBox of 1x1, then it works. I haven't figured out what the exact reason is for this behavior.

$(document).ready(function() {
    var wrapper = document.getElementsByClassName('inner')[0];

    for(var i = 0; i <= 250; i++) {
      var hex = document.createElement('div');

      var colors = ['red-hex', 'blue-hex','yellow-hex'];
      var hexColor = Math.floor(Math.random() * colors.length);

      hex.className = 'hexagon ';
      hex.className += colors[hexColor];
      hex.innerHTML = '';

      var size = (Math.random()* (200-100)) + 100;
      hex.style.fontSize = size + 'px';

      var posx = (Math.random() * wrapper.offsetWidth - size).toFixed();
      var posy = (Math.random() * wrapper.offsetHeight - size).toFixed();

      hex.style.top = posy+'px';
      hex.style.left = posx+'px';

      wrapper.appendChild(hex);
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hexagon_wrapper {
  position: relative;
  width: 1000px;
  height: 1000px;
  margin: 0 auto;
}

.svg-defs {
  position: absolute;
  width: 0;
  height: 0;
 }

.inner {
  position: relative;
  width: 100%;
  height: 100%;
  -webkit-clip-path: url("#clipping");
          clip-path: url("#clipping");
}

.hexagon {
  position: absolute;
  /* mix-blend-mode: color-dodge; looks wicked */
  mix-blend-mode: saturation;
  padding: 10px;
}

.red-hex {
  color: #fe412b;
  -webkit-animation:fade-in 6s infinite;
}

.blue-hex {
  color: #39b1e3;
  -webkit-animation:fade-in 5s infinite;
}

.yellow-hex {
  color: #fcfe41;
  -webkit-animation:fade-in 4s infinite;
}

@-webkit-keyframes fade-in{
  0%, 100% {
    opacity: 0.9;
  }
  50% {
    opacity: 0.5;
  }
}</code>```

<link href="https://cdn.materialdesignicons.com/1.8.36/css/materialdesignicons.min.css" rel="stylesheet"/>

  <svg class="svg-defs">
    <defs>
      <clipPath id="clipping" clipPathUnits ="objectBoundingBox">
                <polygon points=".5 .01, 0.95 .25, .95 .75, .50 .99, .05 .75, .05 .25" />
      </clipPath>
    </defs>
  </svg>

```

Title: Inline SVG Element not working on Div

Body:
I have this snippet. My end game is to use a larger hexagon as a container for the generated hexagons. I am using an inline svg element but it does not seem that the mask is applying to the div with the inner class like I hoped. Am I implementing it wrong or missing something?

If I had to guess is it because my coordinates for the hexagon are larger than 1 which would break boundingBox?

$(document).ready(function() {
    var wrapper = document.getElementsByClassName('inner')[0];

    for(var i = 0; i <= 250; i++) {
      var hex = document.createElement('div');

      var colors = ['red-hex', 'blue-hex','yellow-hex'];
      var hexColor = Math.floor(Math.random() * colors.length);

      hex.className = 'hexagon ';
      hex.className += colors[hexColor];
      hex.innerHTML = '';

      var size = (Math.random()* (200-100)) + 100;
      hex.style.fontSize = size + 'px';

      var posx = (Math.random() * wrapper.offsetWidth - size).toFixed();
      var posy = (Math.random() * wrapper.offsetHeight - size).toFixed();

      hex.style.top = posy+'px';
      hex.style.left = posx+'px';

      wrapper.appendChild(hex);
    }
});

.hexagon_wrapper {
  position: relative;
  width: 1000px;
  height: 1000px;
  margin: 0 auto;
}

.svg-defs {
  position: absolute;
  width: 0;
  height: 0;
 }

.inner {
  position: relative;
  width: 100%;
  height: 100%;
  -webkit-clip-path: url("#clipping");
          clip-path: url("#clipping");
}

.hexagon {
  position: absolute;
  /* mix-blend-mode: color-dodge; looks wicked */
  mix-blend-mode: saturation;
  padding: 10px;
}

.red-hex {
  color: #fe412b;
  -webkit-animation:fade-in 6s infinite;
}

.blue-hex {
  color: #39b1e3;
  -webkit-animation:fade-in 5s infinite;
}

.yellow-hex {
  color: #fcfe41;
  -webkit-animation:fade-in 4s infinite;
}

@-webkit-keyframes fade-in{
  0%, 100% {
    opacity: 0.9;
  }
  50% {
    opacity: 0.5;
  }
}

<link href="https://cdn.materialdesignicons.com/1.8.36/css/materialdesignicons.min.css" rel="stylesheet"/>

  <svg class="svg-defs">
    <defs>
      <clipPath id="clipping" clipPathUnits ="objectBoundingBox">
        <polygon points="50 1 95 25 95 75 50 99 5 75 5 25" />
      </clipPath>
    </defs>
  </svg>

Body:
I have rewritten your polygon to fit within a viewBox of 1x1, then it works. I haven't figured out what the exact reason is for this behavior.

$(document).ready(function() {
    var wrapper = document.getElementsByClassName('inner')[0];

    for(var i = 0; i <= 250; i++) {
      var hex = document.createElement('div');

      var colors = ['red-hex', 'blue-hex','yellow-hex'];
      var hexColor = Math.floor(Math.random() * colors.length);

      hex.className = 'hexagon ';
      hex.className += colors[hexColor];
      hex.innerHTML = '<i class="mdi mdi-hexagon" aria-hidden="true"></i>';

      var size = (Math.random()* (200-100)) + 100;
      hex.style.fontSize = size + 'px';

      var posx = (Math.random() * wrapper.offsetWidth - size).toFixed();
      var posy = (Math.random() * wrapper.offsetHeight - size).toFixed();

      hex.style.top = posy+'px';
      hex.style.left = posx+'px';

      wrapper.appendChild(hex);
    }
});

.hexagon_wrapper {
  position: relative;
  width: 1000px;
  height: 1000px;
  margin: 0 auto;
}

.svg-defs {
  position: absolute;
  width: 0;
  height: 0;
 }

.inner {
  position: relative;
  width: 100%;
  height: 100%;
  -webkit-clip-path: url("#clipping");
          clip-path: url("#clipping");
}

.hexagon {
  position: absolute;
  /* mix-blend-mode: color-dodge; looks wicked */
  mix-blend-mode: saturation;
  padding: 10px;
}

.red-hex {
  color: #fe412b;
  -webkit-animation:fade-in 6s infinite;
}

.blue-hex {
  color: #39b1e3;
  -webkit-animation:fade-in 5s infinite;
}

.yellow-hex {
  color: #fcfe41;
  -webkit-animation:fade-in 4s infinite;
}

@-webkit-keyframes fade-in{
  0%, 100% {
    opacity: 0.9;
  }
  50% {
    opacity: 0.5;
  }
}

<link href="https://cdn.materialdesignicons.com/1.8.36/css/materialdesignicons.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="hexagon_wrapper">
  <div class="inner">
  </div>
  <svg class="svg-defs">
    <defs>
      <clipPath id="clipping" clipPathUnits ="objectBoundingBox">
                <polygon points=".5 .01, 0.95 .25, .95 .75, .50 .99, .05 .75, .05 .25" />
      </clipPath>
    </defs>
  </svg>
</div>


问:
Setting section headers in R file that get rendered with spin()
Traditionally I declare section headers in Rmd files like this:

```<code># header 1
```{r, echo=FALSE}
print("foo")
```

## header level 2
```{r}
print("bar")
```
</code>```

So that when it gets rendered to HTML, it looks like this. And I can put in a table of contents.

header 1

```<code>foo
</code>```

header level 2

```<code>bar
</code>```

Using the spin() function, I would like to generate a Rmd file from a R ('Main.R') file that has the proper headers in knitr. Currently if I have this R file:

```<code>#+ section_1, echo=F
# what do I put here so that "header 1" gets inserted into the spun Rmd?
print("foo")

#+ section_2
print("bar")
</code>```

Spinning with spin('Main.R', knit=F) produces this:

```<code>```{r section_1, echo=F}
# what do I put here so that "header 1" gets inserted into the spun Rmd?
print("foo")

```{r section_2}
print("bar")
```
```

I could not find any documentation that suggests how to insert the section names?

答:
You can include Roxygen comments in .R files.  For example,

```<code>#' ## Section 1
print("foo")

#' ## Section 2
print("bar")
</code>```

If you want to, you can include a full YAML header such as

```<code>#' ---
#' title: My document in a .R file
#' output:
#'   html_document:
#'     toc: true
#' ---
#'
</code>```

but you'll probably need to use rmarkdown::render instead of knitr::spin.

Body:
Traditionally I declare section headers in Rmd files like this:

# header 1
```{r, echo=FALSE}
print("foo")
```

## header level 2
```{r}
print("bar")
```

So that when it gets rendered to HTML, it looks like this. And I can put in a table of contents.

header 1

foo

header level 2

bar

Using the spin() function, I would like to generate a Rmd file from a R ('Main.R') file that has the proper headers in knitr. Currently if I have this R file:

#+ section_1, echo=F
# what do I put here so that "header 1" gets inserted into the spun Rmd?
print("foo")

#+ section_2
print("bar")

Spinning with spin('Main.R', knit=F) produces this:

```{r section_1, echo=F}
# what do I put here so that "header 1" gets inserted into the spun Rmd?
print("foo")

```{r section_2}
print("bar")
```

I could not find any documentation that suggests how to insert the section names?

Body:
You can include Roxygen comments in .R files.  For example,

#' ## Section 1
print("foo")

#' ## Section 2
print("bar")

If you want to, you can include a full YAML header such as

#' ---
#' title: My document in a .R file
#' output:
#'   html_document:
#'     toc: true
#' ---
#'

but you'll probably need to use rmarkdown::render instead of knitr::spin.


问:
What is the modulus operator (%) in swift 3?
I have this line:

```<code>randomIndex = Int(drand48() % Double(alphabetColors.count))
</code>```

And Xcode 8 (Swift 3) tells me:

```<code>'%' is unavailable: Use truncatingRemainder instead
</code>```

Is there no operator anymore? How should I convert my code?

答:
This seems to be available for me, currently on Swift 3.1, so possible it was added back.

My guess is that it's somewhere in Foundation and needs an explicit import Foundation

Update

This is for Int types only. It seems that for doubles, truncating remainder is required.

Body:
I have this line:

randomIndex = Int(drand48() % Double(alphabetColors.count))

And Xcode 8 (Swift 3) tells me:

'%' is unavailable: Use truncatingRemainder instead

Is there no operator anymore? How should I convert my code?


问:
I would like to manipulate captured data from a regular expression return
I am writing a command that will search my html document and add an id to any heading tag based on the text node. I wanted to know if it is possible to capture the text node and then replace white space with hyphens.

e.g.

```<code><h2>This is a heading</h2>
</code>```

would become

```<code><h2 id="this-is-a-heading">This is a heading</h2>
</code>```

I am new to regular expression so forgive me if it is a silly question.

At the moment I have this, but realize it does not alter the captured data.

Search Criteria:

```<code><h2\s*>([^<]*)</h2>
</code>```

Replace text:

```<code><h2 id="$1">$1</h2>
</code>```

Thanks in advance.

答:
I have had to use a work around for now by doing what I wanted in stages.

This is what I have done so far.

To change

```<code><h2>1. Something Here</h2>
</code>```

to

```<code><h2 id="Something-here">1. Something Here</h2>
</code>```

To find all heading tags excluding h1...

```<code>        dw.setUpFindReplace({searchString: '<h([^1])>([^<]*)',
    replaceString: '<h$1 id="$2">$2', searchSource: true,
matchCase: false, ignoreWhitespace: false,
useRegularExpressions: true, searchWhat: 'document'});
                dw.replaceAll();
</code>```

to remove any numbers at the beginning of the id...

```<code>        dw.setUpFindReplace({searchString: '<h([^1]) id="\s*(\d+\s+|\d+,\d+\s+|\d+\.)',
replaceString: '<h$1 id="', searchSource: true, matchCase: false,
ignoreWhitespace: false, useRegularExpressions: true,
searchWhat: 'document'});
            dw.replaceAll();
</code>```

to hyphenate the id...

```<code>     dw.setUpFindReplace({searchString: '<h([^1]) id="(\w+)\s+(\w+)\s*',
replaceString: '<h$1 id="$2-$3',
    searchSource: true, matchCase: false,
    ignoreWhitespace: false, useRegularExpressions: true,
    searchWhat: 'document'});
                        dw.replaceAll();
</code>```

Body:
I am writing a command that will search my html document and add an id to any heading tag based on the text node. I wanted to know if it is possible to capture the text node and then replace white space with hyphens.

e.g.

This is a heading

would become

This is a heading

I am new to regular expression so forgive me if it is a silly question.

At the moment I have this, but realize it does not alter the captured data.

Search Criteria:

([^<]*)

Replace text:

$1

Thanks in advance.

Body:
I have had to use a work around for now by doing what I wanted in stages.

This is what I have done so far.

To change

<h2>1. Something Here</h2>

to

<h2 id="Something-here">1. Something Here</h2>

To find all heading tags excluding h1...

        dw.setUpFindReplace({searchString: '<h([^1])>([^<]*)',
    replaceString: '<h$1 id="$2">$2', searchSource: true,
matchCase: false, ignoreWhitespace: false,
useRegularExpressions: true, searchWhat: 'document'});
                dw.replaceAll();

to remove any numbers at the beginning of the id...

        dw.setUpFindReplace({searchString: '<h([^1]) id="\s*(\d+\s+|\d+,\d+\s+|\d+\.)',
replaceString: '<h$1 id="', searchSource: true, matchCase: false,
ignoreWhitespace: false, useRegularExpressions: true,
searchWhat: 'document'});
            dw.replaceAll();

to hyphenate the id...

     dw.setUpFindReplace({searchString: '<h([^1]) id="(\w+)\s+(\w+)\s*',
replaceString: '<h$1 id="$2-$3',
    searchSource: true, matchCase: false,
    ignoreWhitespace: false, useRegularExpressions: true,
    searchWhat: 'document'});
                        dw.replaceAll();


问:
Create docx file from a template file in java
I need to create docx files based on a templates.
The template should contain the place holders and I should be able to fill the the place holders from java .
Is it possible to do it , If so suggest me the good and efficient way to do it .</p>

答:
You can use Word template with following syntax of LINQ Reporting to achieve your requirements using Aspose.Words for Java.

<< tag_name [expression] -switch1 -switch2 ...>>

A tag body typically consists of the following elements:

A tag name

An expression surrounded by brackets

A set of switches available for the tag, each of which is preceded by the “-“ character

Assume, that you have the Sender class defined in your application as follows:

```<code>public class Sender {
    public Sender(String name, String message) {
        _name = name;
        _message = message;
    }

    public String getName() {
        return _name;
    }

    public String getMessage() {
        return _message;
    }

    private String _name;
    private String _message;
}
</code>```

To produce a report containing a message of a concrete sender on its behalf, you can use a template document with the following content.

<<[s.getName()]>> says: "<<[s.getMessage()]>>."

To build a report from the template, you can use the following source code.

```<code>Document doc = new Document(getMyDir() + "temp_HelloWorld.docx");

Sender sender = new Sender("LINQ Reporting Engine", "Hello World");
ReportingEngine engine = new ReportingEngine();
engine.buildReport(doc, sender, "s");

doc.save(getMyDir() + "out.docx");
</code>```

I work with Aspose as Developer evangelist.

Body:
You can use Word template with following syntax of LINQ Reporting to achieve your requirements using Aspose.Words for Java.

<< tag_name [expression] -switch1 -switch2 ...>>

A tag body typically consists of the following elements:

A tag name

An expression surrounded by brackets

A set of switches available for the tag, each of which is preceded by the “-“ character

Assume, that you have the Sender class defined in your application as follows:

public class Sender {
    public Sender(String name, String message) {
        _name = name;
        _message = message;
    }

    public String getName() {
        return _name;
    }

    public String getMessage() {
        return _message;
    }

    private String _name;
    private String _message;
}

To produce a report containing a message of a concrete sender on its behalf, you can use a template document with the following content.

<<[s.getName()]>> says: "<<[s.getMessage()]>>."

To build a report from the template, you can use the following source code.

Document doc = new Document(getMyDir() + "temp_HelloWorld.docx");

Sender sender = new Sender("LINQ Reporting Engine", "Hello World");
ReportingEngine engine = new ReportingEngine();
engine.buildReport(doc, sender, "s");

doc.save(getMyDir() + "out.docx");

I work with Aspose as Developer evangelist.


问:
Xcode with SDK 4.2 always starting iPad Simulator
Why does Xcode, after updating to SDK 4.2, always run my application in iPad Simulator instead of iPhone???
If I select iPhone Simulator as active executable it doesn't store my preference and runs the iPad simulator after any new Build & Run.</p>

答:
Check your .xcodeproj info. Navigate yourself in there and locate Simulator's  Settings and choose 'iPhone' or 'iPad'

Hope this helps


问:
Adding JavaScript to my Carousel
I don't know much about JavaScript, so how could I add some to get my carousel slides change every couple seconds? Do I need to change anything with my CSS or HTML to get it to work? Anything helps, thanks.

  .carousel {
      border-style:solid;
      border-width:1px;
      border-color:rgba(0, 0, 0, 0.05);
      box-shadow: 0px 1px 6px rgba(0, 0, 0, 0.1);
      widht:100%;
      height:250px;
  }

  .carousel-inner {
      position: relative;
      overflow: hidden;
      width: 100%;
      height:250px;
  }

  .carousel-open:checked + .carousel-item {
      position: absolute;
      opacity: 100;
      background-color:white;
      width:100%;
      height:250px;
  }

  .carousel-item {
      position: absolute;
      opacity: 0;
      padding-top:10px;
      text-align:center;
  }

  .carousel-control {
      background: rgba(0, 0, 0, 0);
      border-radius: 50%;
      color:#008c6c;
      cursor: pointer;
      display: none;
      font-size: 30px;
      height: 40px;
      line-height: 35px;
      position: absolute;
      top: 50%;
      -webkit-transform: translate(0, -50%);
      cursor: pointer;
      -ms-transform: translate(0, -50%);
      transform: translate(0, -50%);
      text-align: center;
      width: 40px;
      z-index: 10;
  }

  .carousel-control.prev {
      left: 2%;
  }

  .carousel-control.next {
      right: 2%;
  }

  .carousel-control:hover {
      background: rgba(0, 0, 0, 0.05);
      color: #008c6c;
  }

  #carousel-1:checked ~ .control-1,
  #carousel-2:checked ~ .control-2,
  #carousel-3:checked ~ .control-3,
  #carousel-4:checked ~ .control-4{
      display: block;
  }

  .carousel-indicators {
      margin: 0;
      padding: 0;
      position: absolute;
      bottom: 2px;
      left: 0;
      right: 0;
      text-align: center;
  }

  .carousel-indicators li {
      display: inline-block;
      margin: 0 5px;
  }

  .carousel-bullet {
      color: rgba(0, 0, 0, 0.05);
      cursor: pointer;
      font-size: 25px;
  }

  .carousel-bullet:hover {
      color: rgba(0, 0, 0, 0.1);
  }

  .HRConnectImage
  {width:375px;
  padding-top:50px;
  display:inline-block;}

  #carousel-1:checked ~ .control-1 ~ .carousel-indicators li:nth-child(1) .carousel-bullet,
  #carousel-2:checked ~ .control-2 ~ .carousel-indicators li:nth-child(2) .carousel-bullet,
  #carousel-3:checked ~ .control-3 ~ .carousel-indicators li:nth-child(3) .carousel-bullet,
  #carousel-4:checked ~ .control-4 ~ .carousel-indicators li:nth-child(4) .carousel-bullet{
      color: #008c6c;
  }

  #title {
      width: 100%;
      position: absolute;
      padding: 0px;
      margin: 0px auto;
      text-align: center;
      font-size: 27px;
      color: rgba(255, 255, 255, 1);
      font-family: 'Open Sans', sans-serif;
      z-index: 9999;
      text-shadow: 0px 1px 2px rgba(0, 0, 0, 0.33), -1px 0px 2px rgba(255, 255, 255, 0);
  }

  ul
  {margin-left:40px;
  margin-right:60px;
  text-align:left;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="http://wearenorthwest.northwest.ca/departments/humanresources/hr-connect-two/Documents/HRHome.css" rel="stylesheet"/>

  <div class="carousel">
     <div class="carousel-inner">
        <input name="carousel" class="carousel-open" id="carousel-1" aria-hidden="true" type="radio" hidden="true" Checked/>
        <div class="carousel-item">
  <h1>Slide 1</h1>
  <br/>
           <ul>
      <li>Content.</li>
    </ul>
        </div>
        <input name="carousel" class="carousel-open" id="carousel-2" aria-hidden="true" type="radio" hidden="true"/>
        <div class="carousel-item">
           <h1>Slide 2</h1>
  <br/>
           <ul>
      <li>Content.</li>
    </ul>
        </div>
        <input name="carousel" class="carousel-open" id="carousel-3" aria-hidden="true" type="radio" hidden="true"/>
        <div class="carousel-item">
           <h1>Slide 3</h1>
  <br/>
           <ul>
      <li>Content.</li>

    </ul>
        </div>
        <input name="carousel" class="carousel-open" id="carousel-4" aria-hidden="true" type="radio" hidden="true"/>
        <div class="carousel-item">
           <h1>Slide 4</h1>
  <br/>
           <ul>
      <li> Content.</li>

    </ul>
        </div>
        <label class="carousel-control prev control-1" for="carousel-4">‹</label>
        <label class="carousel-control next control-1" for="carousel-2">›</label>
        <label class="carousel-control prev control-2" for="carousel-1">‹</label>
        <label class="carousel-control next control-2" for="carousel-3">›</label>
        <label class="carousel-control prev control-3" for="carousel-2">‹</label>
        <label class="carousel-control next control-3" for="carousel-4">›</label>
        <label class="carousel-control prev control-4" for="carousel-3">‹</label>
        <label class="carousel-control next control-4" for="carousel-1">›</label>
        <ol class="carousel-indicators">
           <li>
              <label class="carousel-bullet" for="carousel-1">•</label> </li>
           <li>
              <label class="carousel-bullet" for="carousel-2">•</label> </li>
           <li>
              <label class="carousel-bullet" for="carousel-3">•</label> </li>
           <li>
              <label class="carousel-bullet" for="carousel-4">•</label> </li>
        </ol>
     </div>
  </div></code>```

答:
A simple answer, which requires jQuery, is</p>

```<code>setInterval(function(){
    $('label.carousel-control.next:visible').click()
}, 3000) // change slide every 3 seconds
</code>```

Title: Adding JavaScript to my Carousel

Body:
I don't know much about JavaScript, so how could I add some to get my carousel slides change every couple seconds? Do I need to change anything with my CSS or HTML to get it to work? Anything helps, thanks.

  .carousel {
      border-style:solid;
      border-width:1px;
      border-color:rgba(0, 0, 0, 0.05);
      box-shadow: 0px 1px 6px rgba(0, 0, 0, 0.1);
      widht:100%;
      height:250px;
  }

  .carousel-inner {
      position: relative;
      overflow: hidden;
      width: 100%;
      height:250px;
  }

  .carousel-open:checked + .carousel-item {
      position: absolute;
      opacity: 100;
      background-color:white;
      width:100%;
      height:250px;
  }

  .carousel-item {
      position: absolute;
      opacity: 0;
      padding-top:10px;
      text-align:center;
  }

  .carousel-control {
      background: rgba(0, 0, 0, 0);
      border-radius: 50%;
      color:#008c6c;
      cursor: pointer;
      display: none;
      font-size: 30px;
      height: 40px;
      line-height: 35px;
      position: absolute;
      top: 50%;
      -webkit-transform: translate(0, -50%);
      cursor: pointer;
      -ms-transform: translate(0, -50%);
      transform: translate(0, -50%);
      text-align: center;
      width: 40px;
      z-index: 10;
  }

  .carousel-control.prev {
      left: 2%;
  }

  .carousel-control.next {
      right: 2%;
  }

  .carousel-control:hover {
      background: rgba(0, 0, 0, 0.05);
      color: #008c6c;
  }

  #carousel-1:checked ~ .control-1,
  #carousel-2:checked ~ .control-2,
  #carousel-3:checked ~ .control-3,
  #carousel-4:checked ~ .control-4{
      display: block;
  }

  .carousel-indicators {
      margin: 0;
      padding: 0;
      position: absolute;
      bottom: 2px;
      left: 0;
      right: 0;
      text-align: center;
  }

  .carousel-indicators li {
      display: inline-block;
      margin: 0 5px;
  }

  .carousel-bullet {
      color: rgba(0, 0, 0, 0.05);
      cursor: pointer;
      font-size: 25px;
  }

  .carousel-bullet:hover {
      color: rgba(0, 0, 0, 0.1);
  }

  .HRConnectImage
  {width:375px;
  padding-top:50px;
  display:inline-block;}

  #carousel-1:checked ~ .control-1 ~ .carousel-indicators li:nth-child(1) .carousel-bullet,
  #carousel-2:checked ~ .control-2 ~ .carousel-indicators li:nth-child(2) .carousel-bullet,
  #carousel-3:checked ~ .control-3 ~ .carousel-indicators li:nth-child(3) .carousel-bullet,
  #carousel-4:checked ~ .control-4 ~ .carousel-indicators li:nth-child(4) .carousel-bullet{
      color: #008c6c;
  }

  #title {
      width: 100%;
      position: absolute;
      padding: 0px;
      margin: 0px auto;
      text-align: center;
      font-size: 27px;
      color: rgba(255, 255, 255, 1);
      font-family: 'Open Sans', sans-serif;
      z-index: 9999;
      text-shadow: 0px 1px 2px rgba(0, 0, 0, 0.33), -1px 0px 2px rgba(255, 255, 255, 0);
  }

  ul
  {margin-left:40px;
  margin-right:60px;
  text-align:left;}

<link href="http://wearenorthwest.northwest.ca/departments/humanresources/hr-connect-two/Documents/HRHome.css" rel="stylesheet"/>

        <input name="carousel" class="carousel-open" id="carousel-1" aria-hidden="true" type="radio" hidden="true" Checked/>

Slide 1

Content.

        <input name="carousel" class="carousel-open" id="carousel-2" aria-hidden="true" type="radio" hidden="true"/>

Slide 2

Content.

        <input name="carousel" class="carousel-open" id="carousel-3" aria-hidden="true" type="radio" hidden="true"/>

Slide 3

Content.

        <input name="carousel" class="carousel-open" id="carousel-4" aria-hidden="true" type="radio" hidden="true"/>

Slide 4

 Content.

        ‹
        ›
        ‹
        ›
        ‹
        ›
        ‹
        ›

              •

              •

              •

              •

Body:
A simple answer, which requires jQuery, is

setInterval(function(){
    $('label.carousel-control.next:visible').click()
}, 3000) // change slide every 3 seconds


问:
returning defer.promise not working as expected
I've started doing Angular for three days now and I can't wrap my head around the concept of promise.

I'm trying to create a factory to share JSON data between two controllers. The data represent a serialized SQL datatable.

The factory fetches the data using $http

```<code>var app = angular.module('myApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);

app.factory('Tableau', function ($http, $q) {
    var obj = {};
    obj.getTable = function (page) {
            var temp = {};
            var defer = $q.defer();
            $http.get('api/Table/' + page).then(function (resolve) {
                defer.resolve(resolve.data);
            });
            return defer.promise;
    }
    return obj;
});
</code>```

The first controller should display the data as an HTML table

```<code>app.controller("TableController", function ($scope, Tableau) {
    $scope.elements = Tableau.getTable(2); // get the first ten rows with row id >= n x 10 (in this case 2 x 10)
});
</code>```

And here's the HTML code with the ng directives

```<code><tr ng-repeat="t in elements.myarray track by $index">
    <td ng-repeat="(k,v) in t track by $index">
        <div ng-if="k.indexOf('#')===0">
            <span class="label label-default" ng-repeat="vv in v.split(';')">{{vv}}</span><br />
        </div>
        <div ng-if="k.indexOf('§')===0">
            <a href="{{v}}">Lien</a>
        </div>
        <div ng-if="k.indexOf('#')!=0 && k.indexOf('§')!=0">
            {{v}}
        </div>
    </td>
</tr>
</code>```

I have no problem calling $http from the controller, but when I moved the code to the factory, $scope.elements contains a promise object instead of my expected JSON object.

I did not implement the second controller, which would create a pagination for the table (using ui-bootstrap)

How can I wait for $http to complete before returning returning an object from the factory ?

If this isn't possible, how can I share data retrieved from a server in a single move ?

Thanks in advance.

答:
You need to wait for the promise to complete before using its result. That means using .then():

```<code>app.controller("TableController", function ($scope, Tableau) {
    Tableau.getTable(2)
        .then(function (result) {
            $scope.elements = result;
        });
});
</code>```

You've also fallen prey to the Explicit Promise Construction Antipattern.

Simpler implementation for your factory:

```<code>app.factory('Tableau', function ($http, $q) {
    var obj = {};

    obj.getTable = function (page) {
        return $http.get('api/Table/' + page)
            .then(function (result) {
                return result.data;
            });
    };

    return obj;
});
</code>```

Body:
I've started doing Angular for three days now and I can't wrap my head around the concept of promise.

I'm trying to create a factory to share JSON data between two controllers. The data represent a serialized SQL datatable.

The factory fetches the data using $http

var app = angular.module('myApp', ['ngAnimate', 'ngSanitize', 'ui.bootstrap']);

app.factory('Tableau', function ($http, $q) {
    var obj = {};
    obj.getTable = function (page) {
            var temp = {};
            var defer = $q.defer();
            $http.get('api/Table/' + page).then(function (resolve) {
                defer.resolve(resolve.data);
            });
            return defer.promise;
    }
    return obj;
});

The first controller should display the data as an HTML table

app.controller("TableController", function ($scope, Tableau) {
    $scope.elements = Tableau.getTable(2); // get the first ten rows with row id >= n x 10 (in this case 2 x 10)
});

And here's the HTML code with the ng directives

            {{vv}}

            Lien

            {{v}}

I have no problem calling $http from the controller, but when I moved the code to the factory, $scope.elements contains a promise object instead of my expected JSON object.

I did not implement the second controller, which would create a pagination for the table (using ui-bootstrap)

How can I wait for $http to complete before returning returning an object from the factory ?

If this isn't possible, how can I share data retrieved from a server in a single move ?

Thanks in advance.

Body:
You need to wait for the promise to complete before using its result. That means using .then():

app.controller("TableController", function ($scope, Tableau) {
    Tableau.getTable(2)
        .then(function (result) {
            $scope.elements = result;
        });
});

You've also fallen prey to the Explicit Promise Construction Antipattern.

Simpler implementation for your factory:

app.factory('Tableau', function ($http, $q) {
    var obj = {};

    obj.getTable = function (page) {
        return $http.get('api/Table/' + page)
            .then(function (result) {
                return result.data;
            });
    };

    return obj;
});


问:
Getting the third moving date
I need to get the third moving date based on address for each person. Either status change or address change will make DT change. For example, for PERSON_ID:1, the third moving date should be 07/16/2016. Thanks!
The data is as below:</p>

```<code>PERSON_ID      STATUS      DT        ADDRESS
1                12      5/6/2016      3
1                 6      5/8/2016      3
1                 7      6/5/2016      3
1                 1      6/13/2016     3
1                 12    6/20/2016      1
1                 17    7/8/2016       1
1                  1    7/11/2016      1
1                 12    7/16/2016      2
1                  3    12/6/2016      2
2                  5    3/11/2016      5
2                  1    5/15/2016      4
2                  6    7/18/2016      6
2                 12    7/21/2016      6
</code>```

答:
Using row_number() and group by for the min(dt) per address:

Note: This will not work correctly if the person moves between the same addresses.

```<code>select
    Person_id
  , dt = convert(char(10),dt,120)
  , Address
from (
  select
      person_id
    , dt = min(dt)
    , address
    , rn = row_number() over (partition by person_id order by min(dt))
  from t
  group by person_id, address
) s
where rn = 3
</code>```

rextester demo: http://rextester.com/VLTUU16478

returns:

```<code>+-----------+------------+---------+
| Person_id |     dt     | Address |
+-----------+------------+---------+
|         1 | 2016-07-16 |       2 |
|         2 | 2016-07-18 |       6 |
+-----------+------------+---------+
</code>```

To solve this correctly for a person moving between the same addresses, you have to address the gaps and islands problem.

Adding an additional subquery to the above solution so we can identify and group by the islands:

```<code>select
    Person_id
  , dt = convert(char(10),dt,120)
  , Address
from (
  select
      person_id
    , dt = min(dt)
    , address
    , rn = row_number() over (partition by person_id order by min(dt))
  from (
    select
        person_id
      , address
      , dt
      , island = row_number() over (partition by person_id order by dt)
               - row_number() over (partition by person_id, address order by dt)
     from t
      ) s
  group by person_id, address, island
) s
where rn = 3
</code>```

rextester demo: http://rextester.com/PPIH49666

returns:

```<code>+-----------+------------+---------+
| Person_id |     dt     | Address |
+-----------+------------+---------+
|         1 | 2016-07-16 |       3 |
|         2 | 2016-07-18 |       5 |
+-----------+------------+---------+
</code>```

Title: Getting the third moving date

Body:
I need to get the third moving date based on address for each person. Either status change or address change will make DT change. For example, for PERSON_ID:1, the third moving date should be 07/16/2016. Thanks!
The data is as below:

PERSON_ID      STATUS      DT        ADDRESS
1                12      5/6/2016      3
1                 6      5/8/2016      3
1                 7      6/5/2016      3
1                 1      6/13/2016     3
1                 12    6/20/2016      1
1                 17    7/8/2016       1
1                  1    7/11/2016      1
1                 12    7/16/2016      2
1                  3    12/6/2016      2
2                  5    3/11/2016      5
2                  1    5/15/2016      4
2                  6    7/18/2016      6
2                 12    7/21/2016      6

Body:
Using row_number() and group by for the min(dt) per address:

Note: This will not work correctly if the person moves between the same addresses.

select
    Person_id
  , dt = convert(char(10),dt,120)
  , Address
from (
  select
      person_id
    , dt = min(dt)
    , address
    , rn = row_number() over (partition by person_id order by min(dt))
  from t
  group by person_id, address
) s
where rn = 3

rextester demo: http://rextester.com/VLTUU16478

returns:

+-----------+------------+---------+
| Person_id |     dt     | Address |
+-----------+------------+---------+
|         1 | 2016-07-16 |       2 |
|         2 | 2016-07-18 |       6 |
+-----------+------------+---------+

To solve this correctly for a person moving between the same addresses, you have to address the gaps and islands problem.

Adding an additional subquery to the above solution so we can identify and group by the islands:

select
    Person_id
  , dt = convert(char(10),dt,120)
  , Address
from (
  select
      person_id
    , dt = min(dt)
    , address
    , rn = row_number() over (partition by person_id order by min(dt))
  from (
    select
        person_id
      , address
      , dt
      , island = row_number() over (partition by person_id order by dt)
               - row_number() over (partition by person_id, address order by dt)
     from t
      ) s
  group by person_id, address, island
) s
where rn = 3

rextester demo: http://rextester.com/PPIH49666

returns:

+-----------+------------+---------+
| Person_id |     dt     | Address |
+-----------+------------+---------+
|         1 | 2016-07-16 |       3 |
|         2 | 2016-07-18 |       5 |
+-----------+------------+---------+


问:
express middleware redirects not working
I have the next express server i want redirect .js files to the correspond .js.gz file but when i request /static/common.js don't redirects

Response Headers

HTTP/1.1 200 OK
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Wed, 29 Mar 2017 14:30:17 GMT
ETag: W/"2b4084-15b1a796ca8"
Content-Type: application/javascript
Content-Length: 2834564
Date: Wed, 29 Mar 2017 16:25:53 GMT
Connection: keep-alive

```<code>// define the folder that will be used for static assets
const staticFolder = './';
app.use(favicon(`${staticFolder}/icons/favicon.ico`));
app.use('/static', Express.static(staticFolder));
app.use('/', Express.static(`${staticFolder}/sw`));
app.use(locale(supported));

app.get('*.js', (req, res, next) => {
  const reqI = req;
  reqI.url += '.gz';
  res.set('Content-Encoding', 'gzip');
  next();
});

// universal routing and rendering
app.get('*', (req, res) => {
</code>```

I am using nginx inside a docker image with the next configuration:

```<code>server {
    listen 80;
    server_name api.inmoblex.com;
    return 301 https://$host$request_uri;
}

server {
 listen 443 ssl http2;
 server_name api.inmoblex.com;
 charset utf-8;

 ssl_certificate /www/certs/fullchain.pem;
 ssl_certificate_key /www/certs/privkey.pem;

 location / {
     proxy_pass http://web:8000;
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }
}

server {
    listen 80 default_server;
    server_name inmoblex.com www.inmoblex.com;
    return 301 https://$host$request_uri;
}

server {

   listen 443 ssl http2 default_server;
   server_name inmoblex.com www.inmoblex.com;
   charset utf-8;

   ssl_certificate /www/certs/fullchain.pem;
   ssl_certificate_key /www/certs/privkey.pem;

   location / {
       proxy_pass http://node:3000;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   }

}
</code>```

答:
Don't need to precompress or redirect.</p>

```<code>var compression = require('compression')
var express = require('express')

var app = express()
app.use(compression())
</code>```

Body:
I have the next express server i want redirect .js files to the correspond .js.gz file but when i request /static/common.js don't redirects

Response Headers

HTTP/1.1 200 OK
X-Powered-By: Express
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Wed, 29 Mar 2017 14:30:17 GMT
ETag: W/"2b4084-15b1a796ca8"
Content-Type: application/javascript
Content-Length: 2834564
Date: Wed, 29 Mar 2017 16:25:53 GMT
Connection: keep-alive

// define the folder that will be used for static assets
const staticFolder = './';
app.use(favicon(`${staticFolder}/icons/favicon.ico`));
app.use('/static', Express.static(staticFolder));
app.use('/', Express.static(`${staticFolder}/sw`));
app.use(locale(supported));

app.get('*.js', (req, res, next) => {
  const reqI = req;
  reqI.url += '.gz';
  res.set('Content-Encoding', 'gzip');
  next();
});

// universal routing and rendering
app.get('*', (req, res) => {

I am using nginx inside a docker image with the next configuration:

server {
    listen 80;
    server_name api.inmoblex.com;
    return 301 https://$host$request_uri;
}

server {
 listen 443 ssl http2;
 server_name api.inmoblex.com;
 charset utf-8;

 ssl_certificate /www/certs/fullchain.pem;
 ssl_certificate_key /www/certs/privkey.pem;

 location / {
     proxy_pass http://web:8000;
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
 }
}

server {
    listen 80 default_server;
    server_name inmoblex.com www.inmoblex.com;
    return 301 https://$host$request_uri;
}

server {

   listen 443 ssl http2 default_server;
   server_name inmoblex.com www.inmoblex.com;
   charset utf-8;

   ssl_certificate /www/certs/fullchain.pem;
   ssl_certificate_key /www/certs/privkey.pem;

   location / {
       proxy_pass http://node:3000;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
   }

}

Body:
Don't need to precompress or redirect.

var compression = require('compression')
var express = require('express')

var app = express()
app.use(compression())


问:
How to use requestReview (SKStoreReviewController) to show review popup in the current viewController after a random period of time
I've read about this new feature available in iOS 10.3 and thought it will be more flexible and out of the box. But after I read the docs I found out that you need to decide the time to show it and the viewController who calls it. Is there any way I can make it trigger after a random period of time in any viewController is showing at that moment?   </p>

答:
In your AppDelegate:

Swift:

```<code>import StoreKit

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let shortestTime: UInt32 = 50
    let longestTime: UInt32 = 500
    guard let timeInterval = TimeInterval(exactly: arc4random_uniform(longestTime - shortestTime) + shortestTime) else { return true }

    Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(AppDelegate.requestReview), userInfo: nil, repeats: false)

}

@objc func requestReview() {
    SKStoreReviewController.requestReview()
}
</code>```

Objective-C:

```<code>#import <StoreKit/StoreKit.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    int shortestTime = 50;
    int longestTime = 500;
    int timeInterval = arc4random_uniform(longestTime - shortestTime) + shortestTime;

    [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(requestReview) userInfo:nil repeats:NO];
}

- (void)requestReview {
    [SKStoreReviewController requestReview];
}
</code>```

The code above will ask Apple to prompt the user to rate the app at a random time between 50 and 500 seconds after the app finishes launching.
Remember that according to Apple's docs, there is no guarantee that the rating prompt will be presented when the requestReview is called.

Body:
In your AppDelegate:

Swift:

import StoreKit

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    let shortestTime: UInt32 = 50
    let longestTime: UInt32 = 500
    guard let timeInterval = TimeInterval(exactly: arc4random_uniform(longestTime - shortestTime) + shortestTime) else { return true }

    Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(AppDelegate.requestReview), userInfo: nil, repeats: false)

}

@objc func requestReview() {
    SKStoreReviewController.requestReview()
}

Objective-C:

#import <StoreKit/StoreKit.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    int shortestTime = 50;
    int longestTime = 500;
    int timeInterval = arc4random_uniform(longestTime - shortestTime) + shortestTime;

    [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(requestReview) userInfo:nil repeats:NO];
}

- (void)requestReview {
    [SKStoreReviewController requestReview];
}

The code above will ask Apple to prompt the user to rate the app at a random time between 50 and 500 seconds after the app finishes launching.
Remember that according to Apple's docs, there is no guarantee that the rating prompt will be presented when the requestReview is called.

ContentLicense: CC BY-SA 4.0


问:
How to repair corrupted Oracle export file (.dmp)?
I need to restore Oracle database from export file (.dmp) generated by EXP tool, but the file looks to be corrupted. Does anybody know a tool or solution to repair it?</p>

答: For some reason the most helpful answer was deleted. Someone has suggested to use data recovery service for Oracle dump files provided by Intelligent Converters and so I did. Indeed, they were able to repair my dump file. Our estimation is more than 95% of the data has been recovered. I hope this information will be useful for database people having similar problem. </p>


问:
Modified Magento List Template does have all attributes nesssary to display product info anymore
I am trying to display all products of a specific category. So i created a copy of /theme/template/catalog/list.phtml, and i added these couple of lines at the top:

```<code>$cat_id = 10; // category_id for "specific category"
$_productCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter(Mage::getModel('catalog/category')->load($cat_id));
</code>```

Which replaced:

```<code>$_productCollection=$this->getLoadedProductCollection();
</code>```

Now im getting all the products, but certain attributes and methods of the product dont seem to be available anymore($_product->isSaleable(), $this->getPriceHtml($_product) ). so the template does not show the product price or image correctly.  It seems to me that certain helper functions are not available to me anymore since i referenced the model directly for the products, but i dont know enough about the Zend/Magento framework to know what method(s) to use instead.

I didnt paste the code for list.phtml, as this is just the default code for the base template on magento 1.3. Please let me know anyone needs this code for reference.

Thanks in advance!

答:
If you want to limit displaying of the products by a particular category, you need to set this category id into layer object (product list scope). It is not good practice to call models and initalize new collection inside of the template. You can simply set category id via layout and use old template code (without your modifications):</p>

```<code><reference name="your.custom.product.list">
    <action method="setCategoryId"><categoryId>10</categoryId></action>
</reference>
</code>```

Body:
I am trying to display all products of a specific category. So i created a copy of /theme/template/catalog/list.phtml, and i added these couple of lines at the top:

$cat_id = 10; // category_id for "specific category"
$_productCollection = Mage::getResourceModel('catalog/product_collection')->addCategoryFilter(Mage::getModel('catalog/category')->load($cat_id));

Which replaced:

$_productCollection=$this->getLoadedProductCollection();

Now im getting all the products, but certain attributes and methods of the product dont seem to be available anymore($_product->isSaleable(), $this->getPriceHtml($_product) ). so the template does not show the product price or image correctly.  It seems to me that certain helper functions are not available to me anymore since i referenced the model directly for the products, but i dont know enough about the Zend/Magento framework to know what method(s) to use instead.

I didnt paste the code for list.phtml, as this is just the default code for the base template on magento 1.3. Please let me know anyone needs this code for reference.

Thanks in advance!

Body:
If you want to limit displaying of the products by a particular category, you need to set this category id into layer object (product list scope). It is not good practice to call models and initalize new collection inside of the template. You can simply set category id via layout and use old template code (without your modifications):

<reference name="your.custom.product.list">
    <action method="setCategoryId"><categoryId>10</categoryId></action>
</reference>


答:
In your controller:    </p>

```<code>   Tableau.getTable(2)
      .then((data) => {
       $scope.elements = data
    })
</code>```

Title: returning defer.promise not working as expected

Body:
In your controller:

   Tableau.getTable(2)
      .then((data) => {
       $scope.elements = data
    })


问:
R Treemap - how to add multiple labels
I'm trying to create a treemap using R package treemap similar to the one in a sample from the package.

```<code>library(treemap)
data(GNI2010)
treemap(GNI2010,
    index=c("iso3"),
    vSize="population",
    vColor="GNI",
    type="value")
</code>```

Is there any way to add extra labels from columns to display "CHN, 1,35 bln, 20% "

答:
Following lawyeR answer, but adding a detail. If you want to center both labels one above the other, use "\n" as separator in paste function</p>

```<code>GNI2010$label <- paste(GNI2010$iso3, GNI2010$population, sep = "\n")

treemap(GNI2010,
    index=c("label"),
    vSize="population",
    vColor="GNI",
    type="value")
</code>```

Title: R Treemap - how to add multiple labels

Body:
I'm trying to create a treemap using R package treemap similar to the one in a sample from the package.

library(treemap)
data(GNI2010)
treemap(GNI2010,
    index=c("iso3"),
    vSize="population",
    vColor="GNI",
    type="value")

Is there any way to add extra labels from columns to display "CHN, 1,35 bln, 20% "

Body:
Following lawyeR answer, but adding a detail. If you want to center both labels one above the other, use "\n" as separator in paste function

GNI2010$label <- paste(GNI2010$iso3, GNI2010$population, sep = "\n")

treemap(GNI2010,
    index=c("label"),
    vSize="population",
    vColor="GNI",
    type="value")


问:
How to send Long and Double through Ajax to Spring controller?
I want to send Long and Double to Spring controller use Ajax.

```<code>  var id = $(this).data('customer-id');
    var quantity = $('#quantity-' + id).val();
    $.ajax({
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json"
        },
        type: "POST",
        url: '/changeQuantityOrder',
        data: {idOrder: id, quantityChange: quantity},

        error: function(e) {
            console.log(e);
        },
        success: function (msg) {
            window.location.href = "/administrationNotSleeps";
        }
</code>```

I try to receive a code so:

```<code>@RequestMapping(value = "/changeQuantityOrder", method = {RequestMethod.POST})
public @ResponseBody Long editCustomerOrder(@RequestParam(value = "idOrder")Long id,
                                            @RequestParam(value = "quantityChange")Double quantity){
    System.out.println("Id:"+id+" Quantity "+quantity );
    return id;
}
</code>```

But I receive exception

```<code>{"timestamp":1490775639761,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required Long parameter 'idOrder' is not present","path":"/changeQuantityOrder"}"
</code>```

I looked for and have found about this exception (MissingServletRequestParameterException) https://stackoverflow.com/

But this article was written 3 years ago, maybe something changed?

Because now I send String to Spring controller and after that I use split in java.

答:
key should be in quotes
    data: {"idOrder": id, "quantityChange": quantity}
Also mention dataType - what kind of response to expect.

Body:
I want to send Long and Double to Spring controller use Ajax.

  var id = $(this).data('customer-id');
    var quantity = $('#quantity-' + id).val();
    $.ajax({
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json"
        },
        type: "POST",
        url: '/changeQuantityOrder',
        data: {idOrder: id, quantityChange: quantity},

        error: function(e) {
            console.log(e);
        },
        success: function (msg) {
            window.location.href = "/administrationNotSleeps";
        }

I try to receive a code so:

@RequestMapping(value = "/changeQuantityOrder", method = {RequestMethod.POST})
public @ResponseBody Long editCustomerOrder(@RequestParam(value = "idOrder")Long id,
                                            @RequestParam(value = "quantityChange")Double quantity){
    System.out.println("Id:"+id+" Quantity "+quantity );
    return id;
}

But I receive exception

{"timestamp":1490775639761,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required Long parameter 'idOrder' is not present","path":"/changeQuantityOrder"}"

I looked for and have found about this exception (MissingServletRequestParameterException) https://stackoverflow.com/

But this article was written 3 years ago, maybe something changed?

Because now I send String to Spring controller and after that I use split in java.


问:
SSIS package fails with error "If 64-bit driver not installed, run in 32-bit mode"
I am receiving the following error when trying to run the package from the Integration Services catalog in SSMS. I changed the 64BitRuntime option to FALSE but it still does not work. The error below is followed by an error that a connection cannot be made to my Excel connection manager. Any suggestions?

Package Error: The requested OLE DB provider Microsoft.Jet.OLEDB 4.0
  is not registered. If the 64-bit driver is not installed, run the
  package in 32-bit mode. Error code: 0x00000000

答:
Using the built in excel connection manager in SSIS, the package needs to run in 32-bit mode.  Switching this:

64BitRuntime option to FALSE

Only allows SSDT to run the package in 32bit mode, but it does not affect how it will run once you deploy it.  To run it in 32bit mode from SSMS:

If you are right clicking on the package in the Integration Services Catalog and hitting execute, go to the advanced tab of the dialogue and check 32-bit runtime.

If you are executing it via a SQL Agent job.  In the step, go to configuration > Advanced and check 32-bit runtime.


问:
Device number in stat command output
```<code>  stat test.log
  File: `test.log'
  Size: 573         Blocks: 8          IO Block: 4096   regular file
Device: 804h/2052d  Inode: 7091301     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1001/   abc)   Gid: ( 1001/   abc)
Access: 2010-11-29 17:56:22.000000000 -0800
Modify: 2010-11-29 17:56:22.000000000 -0800
Change: 2010-11-29 17:56:22.000000000 -0800
</code>```

In the stat o/p above what does the Device entry signify ?

答:
```<code># stat tool
  File: `tool'
  Size: 4096            Blocks: 8          IO Block: 4096   directory
Device: 801h/2049d      Inode: 671689      Links: 3

# ls -l /dev/sda*
brw-rw---- 1 root disk 8, 0 2010-08-16 14:43 /dev/sda
brw-rw---- 1 root disk 8, 1 2010-08-16 14:43 /dev/sda1
brw-rw---- 1 root disk 8, 2 2010-08-16 14:43 /dev/sda2
brw-rw---- 1 root disk 8, 5 2010-08-16 14:43 /dev/sda5
</code>```

In the example, 'tool' (801h) is in /dev/sda1 (major device number is 8, minor device number is 1). That's the first partition in /dev/sda.

Title: Device number in stat command output

Body:
  stat test.log
  File: `test.log'
  Size: 573         Blocks: 8          IO Block: 4096   regular file
Device: 804h/2052d  Inode: 7091301     Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1001/   abc)   Gid: ( 1001/   abc)
Access: 2010-11-29 17:56:22.000000000 -0800
Modify: 2010-11-29 17:56:22.000000000 -0800
Change: 2010-11-29 17:56:22.000000000 -0800

In the stat o/p above what does the Device entry signify ?

Body:
# stat tool
  File: `tool'
  Size: 4096            Blocks: 8          IO Block: 4096   directory
Device: 801h/2049d      Inode: 671689      Links: 3

# ls -l /dev/sda*
brw-rw---- 1 root disk 8, 0 2010-08-16 14:43 /dev/sda
brw-rw---- 1 root disk 8, 1 2010-08-16 14:43 /dev/sda1
brw-rw---- 1 root disk 8, 2 2010-08-16 14:43 /dev/sda2
brw-rw---- 1 root disk 8, 5 2010-08-16 14:43 /dev/sda5

In the example, 'tool' (801h) is in /dev/sda1 (major device number is 8, minor device number is 1). That's the first partition in /dev/sda.


问:
Writing to DB failed?
I'm trying to write 2 data to db.

```<code>  @IBAction func show(button: UIButton) {

        let userRef = self.dataBaseRef.child("users/\(FIRAuth.auth()!.currentUser!.uid)")
        userRef.observe(.value, with: { (snapshot) in
            let user = User(snapshot: snapshot)
            let currentUser = user.email
            let request = Requests(requestBy: user.email!,
                                   requestTo: self.email!)

            let contactRef = self.ref.child(currentUser! + "--" + self.email!)
            contactRef.setValue(request.toAnyObject())
            self.items.append(request)
            print(request)
        }) { (error ) in
            print(error.localizedDescription)
        }

        self.dismiss(animated: true, completion: nil);

}
</code>```

items is an array

```<code>var items: [Requests] = []
</code>```

user.email and self.email! isn't empty I printed it.

request file looks

```<code>struct Requests {

let key: String
let requestBy: String
let requestTo: String
let ref: FIRDatabaseReference?

init(requestBy: String, requestTo: String, key: String = "") {
    self.key = key
    self.requestBy = requestBy
    self.requestTo = requestTo
    self.ref = nil
}

init(snapshot: FIRDataSnapshot) {
    key = snapshot.key
    let snapshotValue = snapshot.value as! [String: AnyObject]
    requestBy = snapshotValue["requestBy"] as! String
    requestTo = snapshotValue["requestTo"] as! String
    ref = snapshot.ref
}

func toAnyObject() -> Any {
    return [
        "requestBy": requestBy,
        "requestTo": requestTo
    ]
}
</code>```

}

and I'm getting error - unexpectedly found nil while unwrapping an Optional value

答:
According to what I'm seeing in your posted code, you create a request but never assign a value to the ref property. However, it is not clear since we cannot see where it crashes or when is it really used.

Also, assuming self.ref is an optional (as you've been handled that way in your visible code) then this could be the problem:

let contactRef = self.ref.child

you should first check if you can unwrap that optional, like:

if let realRef = self.ref {
realRef.child(currentUser! + "--" + self.email!)
}

Title: Writing to DB failed?

Body:
I'm trying to write 2 data to db.

  @IBAction func show(button: UIButton) {

        let userRef = self.dataBaseRef.child("users/\(FIRAuth.auth()!.currentUser!.uid)")
        userRef.observe(.value, with: { (snapshot) in
            let user = User(snapshot: snapshot)
            let currentUser = user.email
            let request = Requests(requestBy: user.email!,
                                   requestTo: self.email!)

            let contactRef = self.ref.child(currentUser! + "--" + self.email!)
            contactRef.setValue(request.toAnyObject())
            self.items.append(request)
            print(request)
        }) { (error ) in
            print(error.localizedDescription)
        }

        self.dismiss(animated: true, completion: nil);

}

items is an array

var items: [Requests] = []

user.email and self.email! isn't empty I printed it.

request file looks

struct Requests {

let key: String
let requestBy: String
let requestTo: String
let ref: FIRDatabaseReference?

init(requestBy: String, requestTo: String, key: String = "") {
    self.key = key
    self.requestBy = requestBy
    self.requestTo = requestTo
    self.ref = nil
}

init(snapshot: FIRDataSnapshot) {
    key = snapshot.key
    let snapshotValue = snapshot.value as! [String: AnyObject]
    requestBy = snapshotValue["requestBy"] as! String
    requestTo = snapshotValue["requestTo"] as! String
    ref = snapshot.ref
}

func toAnyObject() -> Any {
    return [
        "requestBy": requestBy,
        "requestTo": requestTo
    ]
}

}

and I'm getting error - unexpectedly found nil while unwrapping an Optional value


问:
valgrind finds errors passing pointer to function, but no errors when the code is in the same scope
I am wondering why, in this example code, valgrind finds no errors or lost memory:

```<code>#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(8);
   strcpy(str, "example");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);

   return(0);
}
</code>```

However, when I replace these lines with a function:

```<code>int main() {
   ...
   /* Reallocating memory */
   newstr(str);
   ...
}

void newstr(char *str) {
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
}
</code>```

I am getting 19 errors on valgrind, complaining mostly about invalid reads. However, the program executes and outputs everything the same, without an error. Is there something going on when I pass str into the function that happens in memory that valgrind is notifying me of? What can I do to fix this? How can I learn more about this behavior and what the implications are?

This is the output of the program in either case:

```<code>String = example,  Address = 16445456
String = example.com,  Address = 16445456
</code>```

答:
As a general rule, parameters passed to C functions are passed by value. Unless you explicitly pass by reference, or instead pass a pointer to your object, Changes made in the called function will not persist when the function returns.

In your case, you may be passing a pointer, but you are trying to  then modify the pointer in the function instead of modifying what the pointer references.

Apart from the solution provided in the other answer where you return the new pointer, you have two options:

Pointer to Pointer

```<code>void newstr(char **str) {
   *str = (char *) realloc(*str, 25);
   strcat(*str, ".com");
}
</code>```

Reference

```<code>void newstr(char *&str) {
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
}
</code>```

Body:
I am wondering why, in this example code, valgrind finds no errors or lost memory:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(8);
   strcpy(str, "example");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);

   return(0);
}

However, when I replace these lines with a function:

int main() {
   ...
   /* Reallocating memory */
   newstr(str);
   ...
}

void newstr(char *str) {
   str = (char *) realloc(str, 14);
   strcat(str, ".com");
}

I am getting 19 errors on valgrind, complaining mostly about invalid reads. However, the program executes and outputs everything the same, without an error. Is there something going on when I pass str into the function that happens in memory that valgrind is notifying me of? What can I do to fix this? How can I learn more about this behavior and what the implications are?

This is the output of the program in either case:

String = example,  Address = 16445456
String = example.com,  Address = 16445456

Body:
As a general rule, parameters passed to C functions are passed by value. Unless you explicitly pass by reference, or instead pass a pointer to your object, Changes made in the called function will not persist when the function returns.

In your case, you may be passing a pointer, but you are trying to  then modify the pointer in the function instead of modifying what the pointer references.

Apart from the solution provided in the other answer where you return the new pointer, you have two options:

Pointer to Pointer

void newstr(char **str) {
   *str = (char *) realloc(*str, 25);
   strcat(*str, ".com");
}

Reference

void newstr(char *&str) {
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
}


问:
XSL selecting a XML document is not showing information
Why doesn't this work?

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">
    <html>
      <body>
        <xsl:variable name="PubDB" select="document('MSA_PublisherDatabase.XML')"/>
        <table>
          <xsl:apply-templates select="$PubDB/PublisherDatabase/Publishers/Publisher"/>
        </table>
      </body>
    </html>
  </xsl:template>
  <xsl:template match="Publisher">
    <tr>
      <td>
        <xsl:value-of select="Name"/>
      </td>
    </tr>
  </xsl:template>
</xsl:stylesheet>
</code>```

The XML file contains something like:

```<code><?xml version="1.0" encoding="utf-8"?>
<PublisherDatabase xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.publictalksoftware.co.uk/msa">
  <Publishers>
    <Publisher Gender="Male" Appointed="MinisterialServant" Serving="Publisher">
      <Name>Fred Junior</Name>
      <Notes />
      <Availability Midweek="true" Weekend="true">
        <DatesNotAvailable />
        <DefaultExclusions />
      </Availability>
      <Assignments Attendant="true" ConductorCBS="false" ReaderCBS="true" Chairman="false" Microphones="true" PlatformAttendant="true" Prayer="true" OCLM="true" Sound="true" Student="true" Demonstrations="false">
        <CustomAssignments />
      </Assignments>
    </Publisher>
  </Publishers>
</PublisherDatabase>
</code>```

In this instance I am expecting it to give me a list of names. Nothing is showing up.

I specifically am trying to select a document in to my XSL ..

答:
As mentioned in the comments, you have a namespace problem: The namespaces of your XSLT and your XML do not match.

I created a solution with a third .XML file:

third.xml is simple and only used for the XSLT to start processing:

```<code><?xml version="1.0" encoding="utf-8"?>
<root>
</root>
</code>```

Your XML file named MSA_PublisherDatabase.XML can stay as it is - as desired.

But to get your desired result, your XSLT file has to be adjusted like this to properly handle the namespace issue:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:msa="http://www.publictalksoftware.co.uk/msa"
                              exclude-result-prefixes="msa">
  <xsl:output method="xml" />

  <xsl:template match="/root">
    <html>
      <body>
        <xsl:variable name="PubDB" select="document('MSA_PublisherDatabase.XML')"/>
        <table>
          <xsl:apply-templates select="$PubDB/msa:PublisherDatabase/msa:Publishers/msa:Publisher"/>
        </table>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="msa:Publisher">
    <tr>
      <td>
        <xsl:value-of select="msa:Name"/>
      </td>
    </tr>
  </xsl:template>

</xsl:stylesheet>
</code>```

After these modifications the output should be/is:

```<code><?xml version="1.0"?>
<html>
    <body>
        <table>
            <tr>
                <td>Fred Junior</td>
            </tr>
        </table>
    </body>
</html>
</code>```

If you're using some Linux variant, you can apply this command (with the programsxsltproc and xmlindent installed):

```<code>xsltproc b.xslt b1.xml | xmlindent
</code>```

Body:
Why doesn't this work?

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="/">

        <xsl:variable name="PubDB" select="document('MSA_PublisherDatabase.XML')"/>

          <xsl:apply-templates select="$PubDB/PublisherDatabase/Publishers/Publisher"/>

  </xsl:template>
  <xsl:template match="Publisher">

        <xsl:value-of select="Name"/>

  </xsl:template>
</xsl:stylesheet>

The XML file contains something like:

<?xml version="1.0" encoding="utf-8"?>
<PublisherDatabase xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.publictalksoftware.co.uk/msa">
  <Publishers>
    <Publisher Gender="Male" Appointed="MinisterialServant" Serving="Publisher">
      <Name>Fred Junior</Name>
      <Notes />
      <Availability Midweek="true" Weekend="true">
        <DatesNotAvailable />
        <DefaultExclusions />
      </Availability>
      <Assignments Attendant="true" ConductorCBS="false" ReaderCBS="true" Chairman="false" Microphones="true" PlatformAttendant="true" Prayer="true" OCLM="true" Sound="true" Student="true" Demonstrations="false">
        <CustomAssignments />
      </Assignments>
    </Publisher>
  </Publishers>
</PublisherDatabase>

In this instance I am expecting it to give me a list of names. Nothing is showing up.

I specifically am trying to select a document in to my XSL ..

Body:
As mentioned in the comments, you have a namespace problem: The namespaces of your XSLT and your XML do not match.

I created a solution with a third .XML file:

third.xml is simple and only used for the XSLT to start processing:

<?xml version="1.0" encoding="utf-8"?>
<root>
</root>

Your XML file named MSA_PublisherDatabase.XML can stay as it is - as desired.

But to get your desired result, your XSLT file has to be adjusted like this to properly handle the namespace issue:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                              xmlns:msa="http://www.publictalksoftware.co.uk/msa"
                              exclude-result-prefixes="msa">
  <xsl:output method="xml" />

  <xsl:template match="/root">
    <html>
      <body>
        <xsl:variable name="PubDB" select="document('MSA_PublisherDatabase.XML')"/>
        <table>
          <xsl:apply-templates select="$PubDB/msa:PublisherDatabase/msa:Publishers/msa:Publisher"/>
        </table>
      </body>
    </html>
  </xsl:template>

  <xsl:template match="msa:Publisher">
    <tr>
      <td>
        <xsl:value-of select="msa:Name"/>
      </td>
    </tr>
  </xsl:template>

</xsl:stylesheet>

After these modifications the output should be/is:

<?xml version="1.0"?>
<html>
    <body>
        <table>
            <tr>
                <td>Fred Junior</td>
            </tr>
        </table>
    </body>
</html>

If you're using some Linux variant, you can apply this command (with the programsxsltproc and xmlindent installed):

xsltproc b.xslt b1.xml | xmlindent


问:
Send Email With Multiple RangeToHTML Ranges
I am using some code copied from Ron de Bruin's website (awesome, btw) and am running into a snag.

The email that's generated will paste only the header to the completedTasks range.

It will correctly paste the Summary and incompletedTasks ranges to the body of the email.

If I remove all code dealing with incompletedTasks then it will correctly paste the Summary and completedTasks HTML to the email body.

Thanks in advance for any help.

```<code>Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

Sub Monthly_Close_Daily_Report()
'
'

Dim yearMonth As String
Dim closeDay As String
Dim currTime As String
Dim summaryRange As Range
Dim completedTasks As Range
Dim incompleteTasks As Range
Dim emailRng As Range, cl As Range
Dim sTo As String

Application.ScreenUpdating = False
Sheets("Inputs").Select

'Check to make sure there are no errors, then proceed
If Not IsError(Sheets("Inputs").Range("B12")) Then
    If Sheets("Inputs").Range("B12") = "Yes" Then
        'Store the YY-MM as a variable
        Sheets("Inputs").Select
        yearMonth = Range("B4").Value

        'Store the MM/DD/YYYY as a variable
        Sheets("Inputs").Select
        closeDay = Range("B5").Value

        'Store the current time as a variable
        Sheets("Inputs").Select
        currTime = Format(Now(), "h:mmAM/PM")

        'Unfilter the Task Listing tab
        Sheets("Task Listing").Select
        Activesheet.ShowAllData

        'Refresh the table with new Sharepoint data
        ActiveWorkbook.Connections("SharePoint").Refresh

            'Create a new email with the Email Listing tab in the "To" line
            Set OutApp = CreateObject("Outlook.Application")
            Set OutMail = OutApp.CreateItem(0)

            'Determine the email addresses to send to
            Set emailRng = Worksheets("Email Listing").Range("B2:B50")
            For Each cl In emailRng
                sTo = sTo & ";" & cl.Value
            Next
            sTo = Mid(sTo, 2)

            'Set the Summary range to be copied into the email
            Set summaryRange = Sheets("Summary").Range("A1:G11")
            summaryRange.Copy

            'Filter the Task Listing tab for this month's completed tasks & copy to range
            Sheets("Task Listing").Select
            ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=1, Criteria1:=yearMonth, Operator:=xlFilterValues
            ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=6, Criteria1 _
                :="Completed"
            Set completedTasks = Application.Intersect(ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible), Range("A:G"))
            'Set completedTasks = Sheets("Task Listing").UsedRange.SpecialCells(xlCellTypeVisible)
            Worksheets("Task Listing").ShowAllData

            'Filter the Task Listing tab for this month's non-completed tasks & copy to range
            ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=1, Criteria1:=yearMonth, Operator:=xlFilterValues
            ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=6, Criteria1:="<>Completed"
            Set incompleteTasks = Application.Intersect(ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible), Range("A:G"))

            'On Error Resume Next
            With OutMail
                .To = sTo
                .CC = ""
                .BCC = ""
                .Subject = "Month End Close Status for " & yearMonth & " As Of " & currTime & " on " & closeDay
                .HTMLBody = RangetoHTML(summaryRange) & "<br><br><strong>Completed Tasks" & RangetoHTML(completedTasks) & "<br><br><strong>Incomplete Tasks" & RangetoHTML(incompleteTasks)
                .Display 'Can also use .Send which will send the email.  We want to preview before sending, though.
            End With

            Set OutMail = Nothing
            Set OutApp = Nothing

    Else
        'If tasks are missing Due Dates, flag those for the user and exit the macro
        MsgBox ("There are ""Due Dates"" missing for some tasks.  Please correct the issue and run the macro again.")
    End If

End If

    'Filter the "Task Listing" tab for the current month
    Sheets("Task Listing").Select
    Range("A2").Select
    Selection.AutoFilter
    ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=1, Criteria1:=yearMonth, Operator:=xlFilterValues

'

End Sub
</code>```

答:
It appears that you're pulling both ranges from the same sheet, it's the same sheet only with filtering.

Set input to Completed
Set input to Incomplete

completed = RangetoHTML(input) //you're reading the incompletes
incomplete = RangetoHTML(input) //you're reading the incompletes again

Instead try this

Set input to Completed
htmlBodyBuffer = RangetoHTML(input)

Set input to Incomplete
.HTMLBody = htmlBodyBuffer & RangetoHTML(input)

Body:
I am using some code copied from Ron de Bruin's website (awesome, btw) and am running into a snag.

The email that's generated will paste only the header to the completedTasks range.

It will correctly paste the Summary and incompletedTasks ranges to the body of the email.

If I remove all code dealing with incompletedTasks then it will correctly paste the Summary and completedTasks HTML to the email body.

Thanks in advance for any help.

Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.readall
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

Sub Monthly_Close_Daily_Report()
'
'

Dim yearMonth As String
Dim closeDay As String
Dim currTime As String
Dim summaryRange As Range
Dim completedTasks As Range
Dim incompleteTasks As Range
Dim emailRng As Range, cl As Range
Dim sTo As String

Application.ScreenUpdating = False
Sheets("Inputs").Select

'Check to make sure there are no errors, then proceed
If Not IsError(Sheets("Inputs").Range("B12")) Then
    If Sheets("Inputs").Range("B12") = "Yes" Then
        'Store the YY-MM as a variable
        Sheets("Inputs").Select
        yearMonth = Range("B4").Value

        'Store the MM/DD/YYYY as a variable
        Sheets("Inputs").Select
        closeDay = Range("B5").Value

        'Store the current time as a variable
        Sheets("Inputs").Select
        currTime = Format(Now(), "h:mmAM/PM")

        'Unfilter the Task Listing tab
        Sheets("Task Listing").Select
        Activesheet.ShowAllData

        'Refresh the table with new Sharepoint data
        ActiveWorkbook.Connections("SharePoint").Refresh

            'Create a new email with the Email Listing tab in the "To" line
            Set OutApp = CreateObject("Outlook.Application")
            Set OutMail = OutApp.CreateItem(0)

            'Determine the email addresses to send to
            Set emailRng = Worksheets("Email Listing").Range("B2:B50")
            For Each cl In emailRng
                sTo = sTo & ";" & cl.Value
            Next
            sTo = Mid(sTo, 2)

            'Set the Summary range to be copied into the email
            Set summaryRange = Sheets("Summary").Range("A1:G11")
            summaryRange.Copy

            'Filter the Task Listing tab for this month's completed tasks & copy to range
            Sheets("Task Listing").Select
            ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=1, Criteria1:=yearMonth, Operator:=xlFilterValues
            ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=6, Criteria1 _
                :="Completed"
            Set completedTasks = Application.Intersect(ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible), Range("A:G"))
            'Set completedTasks = Sheets("Task Listing").UsedRange.SpecialCells(xlCellTypeVisible)
            Worksheets("Task Listing").ShowAllData

            'Filter the Task Listing tab for this month's non-completed tasks & copy to range
            ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=1, Criteria1:=yearMonth, Operator:=xlFilterValues
            ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=6, Criteria1:="<>Completed"
            Set incompleteTasks = Application.Intersect(ActiveSheet.UsedRange.SpecialCells(xlCellTypeVisible), Range("A:G"))

            'On Error Resume Next
            With OutMail
                .To = sTo
                .CC = ""
                .BCC = ""
                .Subject = "Month End Close Status for " & yearMonth & " As Of " & currTime & " on " & closeDay
                .HTMLBody = RangetoHTML(summaryRange) & "

Completed Tasks" & RangetoHTML(completedTasks) & "

Incomplete Tasks" & RangetoHTML(incompleteTasks)
                .Display 'Can also use .Send which will send the email.  We want to preview before sending, though.
            End With

            Set OutMail = Nothing
            Set OutApp = Nothing

    Else
        'If tasks are missing Due Dates, flag those for the user and exit the macro
        MsgBox ("There are ""Due Dates"" missing for some tasks.  Please correct the issue and run the macro again.")
    End If

End If

    'Filter the "Task Listing" tab for the current month
    Sheets("Task Listing").Select
    Range("A2").Select
    Selection.AutoFilter
    ActiveSheet.ListObjects("Close_Tasks").Range.AutoFilter Field:=1, Criteria1:=yearMonth, Operator:=xlFilterValues

'

End Sub


问:
C++ behaviour when const
Here's a basic struct (I hope)

```<code>struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};
</code>```

And source

```<code>SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}
</code>```

The I have a class

```<code>struct SomeClass {
    static const SomeType v;

    SomeClass();
};
</code>```

When I then initialise it

```<code>const SomeType SomeClass::v(0,0,0,0);
</code>```

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

答:
```<code>const SomeClass::v(0,0,0,0);
</code>```

won't compile, since you didn't specify the type of v.

Otherwise, this works for me (and should work).

Perhaps you should post a complete, compilable example in one code listing, so we can see what you really had in mind.

Title: C++ behaviour when const

Body:
Here's a basic struct (I hope)

struct SomeType {
    float a;
    float b;
    float c;
    float d;

    SomeType(float, float, float, float);
};

And source

SomeType::SomeType(float na, float nb, float nc, float nd) : a(na), b(nb), c(nc), d(nd) {}

The I have a class

struct SomeClass {
    static const SomeType v;

    SomeClass();
};

When I then initialise it

const SomeType SomeClass::v(0,0,0,0);

My vales become inf or nan or -nan. Anyone seen this before, or know how to fix it?

Edit: Fixed type

Edit: This is quite close to my original example. I multiple classes with similar structure to SomeClass.

Body:
const SomeClass::v(0,0,0,0);

won't compile, since you didn't specify the type of v.

Otherwise, this works for me (and should work).

Perhaps you should post a complete, compilable example in one code listing, so we can see what you really had in mind.