问:
Text is Hidden When Window Resizes
I'm building a website for class, based on a provided template, and I'm struggling to make it so that my text will move as the window gets resized (right now, resizing the window obscures the text and associated buttons).

Ideally, I'd like for the page to be anchored in such a way that the focus remains on the text/buttons - and by extension, the bottom right corner of the image - as the window is resized.

Here is my HTML:

```<code><!DOCTYPE html>
<html lang="en">
    <head>

        <meta name="viewport" content="width=device-width, inital-scale=1.0">
<!-- This tells mobile devices not to zoom out the page, start with scale=1 -->
        <link rel="stylesheet", type="text/css", href="Vendors/css/normalize.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/grid.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/ionicons.min.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/style.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/queries.css">
        <link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel='stylesheet' type='text/css'>

        <title>Whitetail Acres Tree Farm</title>
    </head>
    <body>
        <header>
            <nav>
                <div class="row">
                    <img src="Resources/img/logo-white.png" alt="Omnifood logo" class="logo">
                    <ul class="main-nav">
                        <li><a href="#features">Food Delivery</a></li>
                        <li><a href="#meals">How it Works</a></li>
                        <li><a href="#steps">Our Cities</a></li>
                        <li><a href="#cities">Sign up</a></li>
                    </ul>
                    <a class="mobile-nav-icon js--nav-icon"><i class="ion-navicon-round"></i></a>
                </div>
            </nav>
            <div class="hero-text-box">
                <h1>Schedule <br> Your Visit!</h1>
                <a class="btn btn-full js--scroll-to-plans" href="#">I'm hungry</a>
                <a class="btn btn-ghost js--scroll-to-start" href="#">Show me more</a>
            </div>
        </header>
</code>```

And here is my CSS:

```<code>/* Universal Reset*/
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html
{
    background-color: #ffffff;
    color: #555;
    font-family: 'Lato', 'Arial', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

.clearfix {zoom: 1}
.clearfix:after {
    content: '.';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

header{
    background-image: url(img/hero.jpg);
    background-size: cover;
    background-position:bottom, right;
    height: 100vh;
    background-attachment:inherit;
}

.hero-text-box{
    position: absolute;
    width:1080px;
    top:80%;
    left:55%;
    text-align: right;
    transform: translate(-50%, -50%);
}

.row{
    max-width: 1140px;
    margin:0 auto;
}

section{
    padding: 80px 0;
}

.box{

    padding: 1%;
</code>```

答:
When setting an exact width to an absolutely positioned element, you should expect that it will stay at that width, regardless of browser size.

.hero-text-box{
    position: absolute;
    top:80%;
    left: 49%;
    text-align: right;
    transform: translate(-50%, -50%);
    max-width: 1080px;
    width: 100%;
}```

Also, the left value should be less than 50% because of the transform rule that moves it off screen.

Title: Text is Hidden When Window Resizes

Body:
I'm building a website for class, based on a provided template, and I'm struggling to make it so that my text will move as the window gets resized (right now, resizing the window obscures the text and associated buttons).

Ideally, I'd like for the page to be anchored in such a way that the focus remains on the text/buttons - and by extension, the bottom right corner of the image - as the window is resized.

Here is my HTML:

<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, inital-scale=1.0">

        <link rel="stylesheet", type="text/css", href="Vendors/css/normalize.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/grid.css">
        <link rel="stylesheet", type="text/css", href="Vendors/css/ionicons.min.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/style.css">
        <link rel="stylesheet", type="text/css", href="Resources/css/queries.css">
        <link href='http://fonts.googleapis.com/css?family=Lato:100,300,400,300italic' rel='stylesheet' type='text/css'>

        <title>Whitetail Acres Tree Farm</title>

Food Delivery

How it Works

Our Cities

Sign up

Schedule
 Your Visit!

                I'm hungry
                Show me more

And here is my CSS:

/* Universal Reset*/
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

html
{
    background-color: #ffffff;
    color: #555;
    font-family: 'Lato', 'Arial', sans-serif;
    font-size: 20px;
    font-weight: 300;
    text-rendering: optimizeLegibility;
}

.clearfix {zoom: 1}
.clearfix:after {
    content: '.';
    clear: both;
    display: block;
    height: 0;
    visibility: hidden;
}

header{
    background-image: url(img/hero.jpg);
    background-size: cover;
    background-position:bottom, right;
    height: 100vh;
    background-attachment:inherit;
}

.hero-text-box{
    position: absolute;
    width:1080px;
    top:80%;
    left:55%;
    text-align: right;
    transform: translate(-50%, -50%);
}

.row{
    max-width: 1140px;
    margin:0 auto;
}

section{
    padding: 80px 0;
}

.box{

    padding: 1%;

Body:
When setting an exact width to an absolutely positioned element, you should expect that it will stay at that width, regardless of browser size.

.hero-text-box{
    position: absolute;
    top:80%;
    left: 49%;
    text-align: right;
    transform: translate(-50%, -50%);
    max-width: 1080px;
    width: 100%;
}

Also, the left value should be less than 50% because of the transform rule that moves it off screen.


来源: stackexchange

问:
How to add objects to a pointer
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

```<code>int *ptr;
ptr = new int;
</code>```

How after using that, can you add more objects to that pointer? (make it an array). Thanks!

答:
```<code>1. Build an array.
2. copy *ptr into it.
3. swap ptrs.
4. delete the temp.
</code>```

There you go, you now have "resized" your ptr.

ContentLicense: CC BY-SA 4.0

Title: How to add objects to a pointer

Body:
I'm trying to figure out how does a vector adds more objects after it has already "Created" some:

int *ptr;
ptr = new int;

How after using that, can you add more objects to that pointer? (make it an array). Thanks!

Body:
1. Build an array.
2. copy *ptr into it.
3. swap ptrs.
4. delete the temp.

There you go, you now have "resized" your ptr.

ContentLicense: CC BY-SA 2.5


问:
Angular2: How to enable save button if any model value changed on edit page
I am new for angular 2. I have a page where we can edit details of customer profile. How to enable save button if any property of has been changed. I know it is possible in angular1 by using $watch.</p>

答: and for hide button on a state you can use *ngIf in line directive.</p>

ContentLicense: CC BY-SA 3.0


问:
How to check a not-defined variable in JavaScript
I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error

```<code>alert( x );
</code>```

How can I catch this error?

答:
Another potential "solution" is to use the window object. It avoids the reference error problem when in a browser.

```<code>if (window.x) {
    alert('x exists and is truthy');
} else {
    alert('x does not exist, or exists and is falsy');
}
</code>```

Body:
I wanted to check whether the variable is defined or not. For example, the following throws a not-defined error

alert( x );

How can I catch this error?

Body:
Another potential "solution" is to use the window object. It avoids the reference error problem when in a browser.

if (window.x) {
    alert('x exists and is truthy');
} else {
    alert('x does not exist, or exists and is falsy');
}


问:
Bootstrap, can you disable display flex?
I have the following css thats breaking my layouts:

```<code>@media (min-width: 768px)
.row {
    display: flex;
}
</code>```

Can I disable the display flex rule? Can anyone explain why this happens?

Update:

Currently using boostrap-sass, "bootstrap-sass": "~3.3.5"
Cant find the line in my sass files, probably not much help but it appears here in my compiled css:

```<code>strong {
  font-weight: 600; }

.wrapper {
 padding: 50px 20px; }

 // row class here

**@media (min-width: 768px) {
  .row {
  display: flex; } }**

@media (min-width: 768px) {
  .column {
width: 50%; }
.column:first-child {
margin-right: 20px; } }

.modal__button {
 margin-right: 5px; }

@media (max-width: 500px) {
 .modal-dialog {
width: 100%;
margin: 10px auto; } }

.week-navigation {
  float: right; }

 .week-navigation__next-button {
  float: right; }
</code>```

答:
Bootstrap 4:</p>

```<code>div.row {
    display: block;
    width: 100%;
    ...
}

div.row div.col {
    width: 100%;
    max-width: 100%;
    ...
}
</code>```

Body:
I have the following css thats breaking my layouts:

@media (min-width: 768px)
.row {
    display: flex;
}

Can I disable the display flex rule? Can anyone explain why this happens?

Update:

Currently using boostrap-sass, "bootstrap-sass": "~3.3.5"
Cant find the line in my sass files, probably not much help but it appears here in my compiled css:

strong {
  font-weight: 600; }

.wrapper {
 padding: 50px 20px; }

 // row class here

**@media (min-width: 768px) {
  .row {
  display: flex; } }**

@media (min-width: 768px) {
  .column {
width: 50%; }
.column:first-child {
margin-right: 20px; } }

.modal__button {
 margin-right: 5px; }

@media (max-width: 500px) {
 .modal-dialog {
width: 100%;
margin: 10px auto; } }

.week-navigation {
  float: right; }

 .week-navigation__next-button {
  float: right; }

Body:
Bootstrap 4:

div.row {
    display: block;
    width: 100%;
    ...
}

div.row div.col {
    width: 100%;
    max-width: 100%;
    ...
}


问:
Conditionally delete line suffix and add prefix
I have 4 lines:

```<code>812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 2
812.12 135.14 646.20 2
</code>```

I want to remove the last character of each line. Moreover, if the last character changes from previous line, S will be added in the front. For example, given the input above, the third line's last character is 2 which is different from 1 that terminates the second line. Therefore, S will be added in the front as shown below.

Desired output:

```<code>812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20
</code>```

I have this piece of code to start:

```<code>while(lines[0].charAt(lines[0].length()-1)==lines[1].charAt(lines[1].length()-1)){
    continue;
}
</code>```

Body:
I have 4 lines:

812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 2
812.12 135.14 646.20 2

I want to remove the last character of each line. Moreover, if the last character changes from previous line, S will be added in the front. For example, given the input above, the third line's last character is 2 which is different from 1 that terminates the second line. Therefore, S will be added in the front as shown below.

Desired output:

812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20

I have this piece of code to start:

while(lines[0].charAt(lines[0].length()-1)==lines[1].charAt(lines[1].length()-1)){
    continue;
}

Body:
Try:

String[] lines = new String[]{
        "812.12 135.14 646.17 1",
        "812.12 135.14 646.18 1",
        "812.12 135.14 646.19 2",
        "812.12 135.14 646.20 2"};

System.out.println(lines[0].substring(0, lines[0].length() - 1));
for(int i=1; i < lines.length; i++){
    if(lines[i-1].charAt(lines[i-1].length() - 1) != lines[i].charAt(lines[i].length() - 1)){
        System.out.println("S " + lines[i].substring(0, lines[i].length() - 1));
    } else {
        System.out.println(lines[i].substring(0, lines[i].length() - 1));
    }
}

Output:

812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20


问:
IIS/ASP.NET responds with cache-control: private for all requests
Why does all responses from ASP.NET contain Cache-Control: private? Even a 404 response? Is there something in IIS that sets this default value, and is there a way to configure it? Or is there something in ASP.NET that sets this?

For dynamic content (that is, all MVC results) I would not like it to be cached by the browser, since it is dynamic and can change at any time. Static content is hosted on a CDN, so is not served by IIS.

Edit:

To clarify, I understand very well what Cache-Control: private is, the difference between private, public, no-store, etc and how/when to use them. The question I have is why Cache-Control: private is added by default by IIS/ASP.NET and how to prevent it from being added by default. I understand that it can be useful to cache dynamic pages, but in my application I don't want to cache dynamic pages/responses. For example, I don't want XHR JSON responses to be cached, since they contain dynamic content. Unfortunately the server adds Cache-Control: private to all responses automatically, so I have to manually override it everywhere.

How to reproduce: Open visual studio and create a new ASP.NET Framework (yes, framework, no not Core. We are not able to migrate our system to core yet) solution with an MVC project. Now start the project in IIS Express (just press the play button), and use F12 devtools in the browser to look at the http response. You will see that it contains Cache-Control: private. My question is, what adds this header, and how can I prevent it from being added by default?

答:
Addressing the question:

You will see that it contains Cache-Control: private. My question is,
  what adds this header, and how can I prevent it from being added by
  default?

The Short answer is: as others have noted, this is a default setting by IIS(7+).

To answer more fully: If you are looking to control or modify the default setting Cache-Control: private for caching HTTP requests, server side.

This will depend on your the which specific version of IIS you are running, and how specific you want to be with your modification. Generally speaking however you can do this using your HTTP Response Headers interface  (in IIS Manager =>   Features view - IIS)

If you want to simply disable caching for a Web site or Application:

go to  IIS Manager

Select Site/Application desired

in Features View select HTTP Response Headers:

In actions pane click: Set Common Headers

check Expire Web Content

Set to: Immediately

OK

alternatively, from your command line:

```<code>appcmd.exe set config  "Default Web Site" -section:system.webServer/staticContent /clientCache.cacheControlMode:"DisableCache"
</code>```

For Detailed Information and specifics please check:

https://learn.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/clientcache

Hope this is what your were looking for, cheers.

Body:
Addressing the question:

You will see that it contains Cache-Control: private. My question is,
  what adds this header, and how can I prevent it from being added by
  default?

The Short answer is: as others have noted, this is a default setting by IIS(7+).

To answer more fully: If you are looking to control or modify the default setting Cache-Control: private for caching HTTP requests, server side.

This will depend on your the which specific version of IIS you are running, and how specific you want to be with your modification. Generally speaking however you can do this using your HTTP Response Headers interface  (in IIS Manager =>   Features view - IIS)

If you want to simply disable caching for a Web site or Application:

go to  IIS Manager

Select Site/Application desired

in Features View select HTTP Response Headers:

In actions pane click: Set Common Headers

check Expire Web Content

Set to: Immediately

OK

alternatively, from your command line:

appcmd.exe set config  "Default Web Site" -section:system.webServer/staticContent /clientCache.cacheControlMode:"DisableCache"

For Detailed Information and specifics please check:

https://learn.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/clientcache

Hope this is what your were looking for, cheers.


问:
Modify Global Variable Inside Closure (Swift 4)
I am trying to modify the global variable currentWeather (of type CurrentWeather) using this function, which is meant to update said variable with the information retrieved from the URL and return a bool signifying its success. However, the function is returning false, as currentWeather is still nil. I recognize that the dataTask is asynchronous, and that the task is running in the background parallel to the application, but I don't understand what this means for what I'm trying to accomplish. I also am unable to update currentWeather after the do block, as weather is no longer recognized after exiting the block. I did try using "self.currentWeather", but was told it was an unresolved identifier (perhaps because the function is also global, and there is no "self"?).

The URL is not currently valid because I took out my API key, but it is working as expected otherwise, and my CurrentWeather struct is Decodable. Printing currentWeatherUnwrapped is also consistently successful.

I did look around Stack Overflow and through Apple's official documentation and was unable to find something that answered my question, but perhaps I wasn't thorough enough. I'm sorry if this is a duplicate question. Direction to any further relevant reading is also appreciated! I apologize for the lack of conformity to best coding practices - I'm not very experienced at this point. Thank you all so much!

```<code>func getCurrentWeather () -> Bool {
let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

guard let url = URL(string: jsonUrlString) else { return false }

URLSession.shared.dataTask(with: url) { (data, response, err) in
    // check error/response

    guard let data = data else { return }

    do {
        let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
        currentWeather = weather
        if let currentWeatherUnwrapped = currentWeather {
            print(currentWeatherUnwrapped)
        }
    } catch let jsonErr {
        print("Error serializing JSON: ", jsonErr)
    }

    // cannot update currentWeather here, as weather is local to do block

    }.resume()

return currentWeather != nil
}
</code>```

答:
You fundamentally misunderstand how async functions work. You function returns before the URLSession's dataTask has even begun to execute. A network request may take multiple seconds to complete. You ask it to fetch some data for you, give it a block of code to execute ONCE THE DATA HAS DOWNLOADED, and then go on with your business.

You can be certain that the line after the dataTask's resume() call will run before the new data has loaded.

You need to put code that you want to run when the data is available inside the data task's completion block. (Your statement print(currentWeatherUnwrapped) will run once the data has been read successfully.)

Body:
I am trying to modify the global variable currentWeather (of type CurrentWeather) using this function, which is meant to update said variable with the information retrieved from the URL and return a bool signifying its success. However, the function is returning false, as currentWeather is still nil. I recognize that the dataTask is asynchronous, and that the task is running in the background parallel to the application, but I don't understand what this means for what I'm trying to accomplish. I also am unable to update currentWeather after the do block, as weather is no longer recognized after exiting the block. I did try using "self.currentWeather", but was told it was an unresolved identifier (perhaps because the function is also global, and there is no "self"?).

The URL is not currently valid because I took out my API key, but it is working as expected otherwise, and my CurrentWeather struct is Decodable. Printing currentWeatherUnwrapped is also consistently successful.

I did look around Stack Overflow and through Apple's official documentation and was unable to find something that answered my question, but perhaps I wasn't thorough enough. I'm sorry if this is a duplicate question. Direction to any further relevant reading is also appreciated! I apologize for the lack of conformity to best coding practices - I'm not very experienced at this point. Thank you all so much!

func getCurrentWeather () -> Bool {
let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

guard let url = URL(string: jsonUrlString) else { return false }

URLSession.shared.dataTask(with: url) { (data, response, err) in
    // check error/response

    guard let data = data else { return }

    do {
        let weather = try JSONDecoder().decode(CurrentWeather.self, from: data)
        currentWeather = weather
        if let currentWeatherUnwrapped = currentWeather {
            print(currentWeatherUnwrapped)
        }
    } catch let jsonErr {
        print("Error serializing JSON: ", jsonErr)
    }

    // cannot update currentWeather here, as weather is local to do block

    }.resume()

return currentWeather != nil
}


问:
Trouble running multiple simulators with XCode
I'm running XCode 8 and I've followed a few of the resources to run multiple simulators but, unfortunately, whenever I compile the code within XCode, it restarts all of the simulators to the same exact version and crashes all except for the primary that's displaying the application.

My approach was the open -n Simulator.app where I open up multiple simulators manually and then target the various devices within XCode.

Any better solutions out there?

答: Xcode 9 supports this out of the box, I would recommend that you upgrade unless you have a specific reason not to do this.</p>


答:
When you do an asynchronous call like this, your function will return long before your dataTask will have any value to return. What you need to do is use a completion handler in your function. You can pass it in as a parameter like this:

```<code>func getCurrentWeather(completion: @escaping(CurrentWeather?, Error?) -> Void) {
    //Data task and such here
    let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

    guard let url = URL(string: jsonUrlString) else { return false }

    URLSession.shared.dataTask(with: url) { (data, response, err) in
    // check error/response

        guard let data = data else {
            completion(nil, err)
            return
        }

        //You don't need a do try catch if you use try?
        let weather = try? JSONDecoder().decode(CurrentWeather.self, from: data)
        completion(weather, err)
    }.resume()

}
</code>```

Then calling that function looks like this:

```<code>getCurrentWeather(completion: { (weather, error) in
    guard error == nil, let weather = weather else {
        if weather == nil { print("No Weather") }
        if error != nil { print(error!.localizedDescription) }
        return
    }
    //Do something with your weather result
    print(weather)
})
</code>```

Title: Modify Global Variable Inside Closure (Swift 4)

Body:
When you do an asynchronous call like this, your function will return long before your dataTask will have any value to return. What you need to do is use a completion handler in your function. You can pass it in as a parameter like this:

func getCurrentWeather(completion: @escaping(CurrentWeather?, Error?) -> Void) {
    //Data task and such here
    let jsonUrlString = "https://api.wunderground.com/api/KEY/conditions/q/\(state)/\(city).json"

    guard let url = URL(string: jsonUrlString) else { return false }

    URLSession.shared.dataTask(with: url) { (data, response, err) in
    // check error/response

        guard let data = data else {
            completion(nil, err)
            return
        }

        //You don't need a do try catch if you use try?
        let weather = try? JSONDecoder().decode(CurrentWeather.self, from: data)
        completion(weather, err)
    }.resume()

}

Then calling that function looks like this:

getCurrentWeather(completion: { (weather, error) in
    guard error == nil, let weather = weather else {
        if weather == nil { print("No Weather") }
        if error != nil { print(error!.localizedDescription) }
        return
    }
    //Do something with your weather result
    print(weather)
})


问:
BlockUI in a Table - Not Working
I am "trying" to use BlockUI in a table to have one row blocked out when a user already selected something.  I am able to block out all other elements on the page except anything in the table or the table itself.  Has anyone else run into this issue or have any suggestions on how to solve?</p>

答:
According to this forum post:

Blocking table cells may work in some browsers but in won't work
  reliably in an x-browser environment.  The blocked element needs to be
  an element that can have a relative position, and that is not true of
  TRs and TDs.  Further, the "block" overlay (a div) is appended to the
  blocked element, and appending a div to a table is not valid.  If you
  need to block a table, wrap it in a div and block that div instead.
  If you need to block a table cell, wrap the cell contents in a div and
  block that div instead.  If you need to block a row, block each TD's
  content div.

Basically, you could embed your td's content inside another div, which can be blocked and then call block() on all of those divs instead:

HTML:

```<code><table>
    <tr>
        <td><div class="row">Row 1 Col 1</div></td>
        <td><div class="row">Row 1 Col 2</div></td>
    </tr>
    <tr><td>Row 2 Col 1</td><td>Row 2 Col 2</td></tr>
    <tr><td>Row 3 Col 1</td><td>Row 3 Col 2</td></tr>
</table>
</code>```

JavaScript:

```<code>$("tr:eq(0) td > div.row").block({
    message: null
});
</code>```

I've applied a class row to each td's content so that I can call block() on those elements instead.  The selector selects the first trs tds divs with class "row."

Here's a working example: http://jsfiddle.net/yWwR5/ (The large amount of code up front is just the BlockUI plugin).

You could follow this strategy (as outlined in the forum post) for any element that's part of the table.

Edit: If you can't edit the HTML for some reason, you could wrap the contents of each td in the div with JavaScript:

```<code>$("tr td").contents().wrap("<div class='row' />");
</code>```

Title: BlockUI in a Table - Not Working

Body:
According to this forum post:

Blocking table cells may work in some browsers but in won't work
  reliably in an x-browser environment.  The blocked element needs to be
  an element that can have a relative position, and that is not true of
  TRs and TDs.  Further, the "block" overlay (a div) is appended to the
  blocked element, and appending a div to a table is not valid.  If you
  need to block a table, wrap it in a div and block that div instead.
  If you need to block a table cell, wrap the cell contents in a div and
  block that div instead.  If you need to block a row, block each TD's
  content div.

Basically, you could embed your td's content inside another div, which can be blocked and then call block() on all of those divs instead:

HTML:

<table>
    <tr>
        <td><div class="row">Row 1 Col 1</div></td>
        <td><div class="row">Row 1 Col 2</div></td>
    </tr>
    <tr><td>Row 2 Col 1</td><td>Row 2 Col 2</td></tr>
    <tr><td>Row 3 Col 1</td><td>Row 3 Col 2</td></tr>
</table>

JavaScript:

$("tr:eq(0) td > div.row").block({
    message: null
});

I've applied a class row to each td's content so that I can call block() on those elements instead.  The selector selects the first trs tds divs with class "row."

Here's a working example: http://jsfiddle.net/yWwR5/ (The large amount of code up front is just the BlockUI plugin).

You could follow this strategy (as outlined in the forum post) for any element that's part of the table.

Edit: If you can't edit the HTML for some reason, you could wrap the contents of each td in the div with JavaScript:

$("tr td").contents().wrap("<div class='row' />");


问:
How to implement JSON web token on front end side?
I am working on a nodejs express application. I used Passport's JSON web token for authentication. I have successfully created a JSON web token and it's working fine in Postman and also verifies when token passes into authorization. But I stuck on front-end side.

```<code>app.get('/profile',passport.authenticate('jwt',{session:false}),function(req,res){
        // res.json({user:user.req});
        // console.log(req.query.token);
        res.json('bingo u cant see this without token')
    });
</code>```

How do I send the token in the headers like I did in Postman to this (/profile) route, i.e how to implement token on front end side so that it first checks token?

答:
It depends on the kind what you are using to make your request at the frontend
if you are using ajax, do something like this

```<code>  $.ajax({
    type: 'POST',
    url: url,
    headers: {
        "authToken":"your token" //you could save it in localstorage when recieved
    }
    //OR
    //beforeSend: function(xhr) {
    //  xhr.setRequestHeader("My-First-Header", "first value");
    //  xhr.setRequestHeader("My-Second-Header", "second value");
    //}
 })
</code>```

and if it's axios try doing it like this

```<code>post(url, {
    headers: { authToken: token }
})
</code>```

Body:
I am working on a nodejs express application. I used Passport's JSON web token for authentication. I have successfully created a JSON web token and it's working fine in Postman and also verifies when token passes into authorization. But I stuck on front-end side.

app.get('/profile',passport.authenticate('jwt',{session:false}),function(req,res){
        // res.json({user:user.req});
        // console.log(req.query.token);
        res.json('bingo u cant see this without token')
    });

How do I send the token in the headers like I did in Postman to this (/profile) route, i.e how to implement token on front end side so that it first checks token?

Body:
It depends on the kind what you are using to make your request at the frontend
if you are using ajax, do something like this

  $.ajax({
    type: 'POST',
    url: url,
    headers: {
        "authToken":"your token" //you could save it in localstorage when recieved
    }
    //OR
    //beforeSend: function(xhr) {
    //  xhr.setRequestHeader("My-First-Header", "first value");
    //  xhr.setRequestHeader("My-Second-Header", "second value");
    //}
 })

and if it's axios try doing it like this

post(url, {
    headers: { authToken: token }
})


问:
Show another div when image is hovered over
so I'm trying to do a "cast" section for one of my assignments and I want the actor's character to appear when the actor is hovered over. How would I achieve this? When hiding the display of the deadpool div, it leaves a big gap in the page. I want this to not show until Ryan Reynolds is hovered over.

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>

  <div class="castcontainer">
    <div class="cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" id="cast">
      <p><b>Ryan Reynalds</b></p>
    </div>
  </div>

  <div class="castcontainer">
    <div class="cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" id="cast">
      <p><b>Wade Wilson</b></p>
    </div>
  </div>

</article></code>```

答:
Might this be what you're looking to do?
Added:

```<code>article:hover .cast {
  display: none;
}

article:hover .cast2 {
  display: block;
}
</code>```

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

article:hover .cast {
  display: none;
}

article:hover .cast2 {
  display: block;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article>

  <div id="one" class="castcontainer">
    <div class="cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" id="cast">
      <p><b>Ryan Reynalds</b></p>
    </div>
  </div>

  <div id="two"class="castcontainer">
    <div class="cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" id="cast">
      <p><b>Wade Wilson</b></p>
    </div>
  </div>

</article></code>```

Body:
so I'm trying to do a "cast" section for one of my assignments and I want the actor's character to appear when the actor is hovered over. How would I achieve this? When hiding the display of the deadpool div, it leaves a big gap in the page. I want this to not show until Ryan Reynolds is hovered over.

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}

Ryan Reynalds

Wade Wilson

Body:
Might this be what you're looking to do?
Added:

article:hover .cast {
  display: none;
}

article:hover .cast2 {
  display: block;
}

article {
  display: flex;
  flex-wrap: wrap;
  margin: auto;
  padding-top: 12px;
  padding-bottom: 12px;
  background-color: #8b2323;
  width: 48vw;
  min-height: 200px;
  min-width: 391px;
  font-family: verdana, sans-serif;
  justify-content: center;
}

article:hover .cast {
  display: none;
}

article:hover .cast2 {
  display: block;
}

.castcontainer {
  flex-wrap: wrap;
  min-width: 215px;
  width: 20%;
  height: 30%;
  overflow: hidden;
  padding: 5px;
}

#cast {
  border-radius: 50%;
  width: 100%;
}

.cast2 {
  display: none;
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

.cast:hover+.cast2 {
  display: block;
}

.cast {
  text-align: center;
  background-color: #8b1a1a;
  border-radius: 10px;
  padding: 10px;
}

p {
  background: white;
}

<article>

  <div id="one" class="castcontainer">
    <div class="cast">
      <img src="https://pbs.twimg.com/profile_images/741703039355064320/ClVbjlG-.jpg" id="cast">
      <p><b>Ryan Reynalds</b></p>
    </div>
  </div>

  <div id="two"class="castcontainer">
    <div class="cast2">
      <img src="http://cdn03.cdn.justjared.com/wp-content/uploads/headlines/2017/08/joi-harris-rip.jpg" id="cast">
      <p><b>Wade Wilson</b></p>
    </div>
  </div>

</article>


问:
How to generate a string in CodeIgniter?
I have to generate a string using the email id and current date.

This is for the purpose of providing an encrypted key to the user at the time of forgot password.

How can I generate this?

答:
You can generate string in Codigniter by using "encryption_key" in config file. You can easily generate encrypted string by following these steps.

Go to config.php file in config folder. Find $config['encryption_key'] and set your encryption key. " !@#oiqjwd2131asda3ir0000wqe+_) "

Now go to your controller and call encryption class and generate your two variables $email, $date.

Concatenate those variables and pass them through encrypt() function OR you can pass them one by one (according to your need) and echo them.

Call the controller method and you will see your encrypted string.

You can also decrypt your string by using decrypt() function

Config.php

```<code>$config['encryption_key'] =  "!@#oiqjwd2131asda3ir0000wqe+_)";
</code>```

Tested code

```<code>    class trying extends CI_controller
    {
        public function index()
        {
            1. $this->load->library('encryption');
            2. $email  = "address@domain.com";
            3. $date   = date("Y/m/d");
            4. $string = $email.$date;
            5. echo $encrypted_string = $this->encryption->encrypt($string);
            6. echo "<br>".$decrypt = $this->encryption->decrypt($encrypted_string);
        }
    }
</code>```

Now when you call the controller then by default index() method will call and then on line number 5 your your concatenated values will convert into encrypted form and on line number 6 your encrypted string will convert into original form.

Result

Result will be something like this

```<code>efc080b13a0fc4d1d220c5dcecd87479eca3a2872fa349f0bbf7827a6652ba870bf1b877f83d3f81e33aa8ae8634d97696864224cbfba14c0a3ca2edb50205c4axQjvBYx93dTrN0ZBiJLQcAu+WzFmdIyMYqwxwkRyIlYvCOIRO4Qgec9Nz8Ds1Kn (encrypted form)

address@domain.com2017/11/13 (decrypted form)
</code>```

I hope all this will help you a lot.

Body:
You can generate string in Codigniter by using "encryption_key" in config file. You can easily generate encrypted string by following these steps.

Go to config.php file in config folder. Find $config['encryption_key'] and set your encryption key. " !@#oiqjwd2131asda3ir0000wqe+_) "

Now go to your controller and call encryption class and generate your two variables $email, $date.

Concatenate those variables and pass them through encrypt() function OR you can pass them one by one (according to your need) and echo them.

Call the controller method and you will see your encrypted string.

You can also decrypt your string by using decrypt() function

Config.php

$config['encryption_key'] =  "!@#oiqjwd2131asda3ir0000wqe+_)";

Tested code

    class trying extends CI_controller
    {
        public function index()
        {
            1. $this->load->library('encryption');
            2. $email  = "address@domain.com";
            3. $date   = date("Y/m/d");
            4. $string = $email.$date;
            5. echo $encrypted_string = $this->encryption->encrypt($string);
            6. echo "<br>".$decrypt = $this->encryption->decrypt($encrypted_string);
        }
    }

Now when you call the controller then by default index() method will call and then on line number 5 your your concatenated values will convert into encrypted form and on line number 6 your encrypted string will convert into original form.

Result

Result will be something like this

efc080b13a0fc4d1d220c5dcecd87479eca3a2872fa349f0bbf7827a6652ba870bf1b877f83d3f81e33aa8ae8634d97696864224cbfba14c0a3ca2edb50205c4axQjvBYx93dTrN0ZBiJLQcAu+WzFmdIyMYqwxwkRyIlYvCOIRO4Qgec9Nz8Ds1Kn (encrypted form)

address@domain.com2017/11/13 (decrypted form)

I hope all this will help you a lot.


问:
C++ Logging and performance tuning library
I need to performance analyse some real-time code on Windows.

I can't use any of the regular profilers (Vtune,Codeanalyst) because I can't slow the executable down. So I'm using my own timing class based on QueryPerformanceCounter().

Are then any existing (free) C++ libs to log the results - BUT I need them to be buffered to the end of a run, I can't afford the time to write to a file or event log while I'm collecting data.

Easy enough to roll my own, but if there is a way of making log4cplus / qDebug or similar log to a buffer and dump later it would save some effort.

答:
I wrote a class that does this, too, because I couldn't find anything that did what I wanted but was still easy to incorporate in to existing code with copy-paste coding techniques.

(edit) Note that as mentioned in the comments, the act of timing itself changes the nature of what you're timing.  But then I'm sure you understand this all too well.  This class has still been very useful to me in finding hotspots & bottlenecks, in addition to giving me at least a rough high-side estimate of how long certain code takes to run.  The code I present here was never intended to be production-worthy.  Use it as such.

Here's a sample output of my class:

```<code>Timer Precision = 385 ns

=== Item               Trials    Ttl Time  Avg Time  Mean Time StdDev    ===
    DB Connect         1         0.11 s    0.11 s    0.11 s    0.0000 ps
    Entry Parse        3813      0.33 s    86 us     82 us     18 us
    File Load          1         50 ms     50 ms     50 ms     0.0000 ps
    Option Parse       1         5 ms      5 ms      5 ms      0.0000 ps
    Record Update      3812      0.53 s    140 us    127 us    49 us
============================================================================
</code>```

Each "Item" is one section of code I wanted to time.  The Timer object uses RAII (via auto_ptr) to allow automatic start & stop.  Here's some sample client-side code demonstrating how to use it:

Sample Code:

```<code>int main(int ac, char* av[])
{
    std::auto_ptr<dbg::Timer> section_timer(new dbg::Timer("Option Parse"));
    // MAGIC: Parse the command line...

    section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("File Load"));
    // MAGIC: Load a big file...

    section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("DB Connect"));
    // MAGIC: Establish a DB connection...

    for( /* for each item in the file*/  )
    {
      section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("Entry Parse"));
      // MAGIC: Parse the incoming item
      section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("Record Update"));
      // MAGIC: Update the database
    }

    // Dump the output shown above

    cout << dbg::Timer::DumpTrials() << endl;
}
</code>```

The implementation of this class is in an include library.  You don't need to compile anything.  I use Boost.Format to do the string formatting, but this could be replaced simply enough.

Here is the implementation (my actual implementation splits this in to two files, core.h and core_dbg.hpp; the latter is #includeed directly from the former).

Implementation:

```<code>namespace dbg
{
    class Timer
    {
    public:
        inline Timer(const std::string & name);
        inline Timer(const Timer& rhs);
        inline virtual ~Timer();
        inline std::string format_now() const;
        double current_elapsed() const;

        Timer& operator=(const std::string& name);

        static std::string DumpTrials(bool ClipboardAlso=false);
        static void Reset();
        static std::string format_elapsed(double d) ;

    private:
        typedef std::string key_type;
        typedef double time_type;
        typedef std::multimap<key_type, time_type> times;

        static __int64 TimerFreq();

        LARGE_INTEGER startTime_, stopTime_;
        mutable LARGE_INTEGER intermediateTime_;
        std::string label_;

        static times& TimeMap();

        struct extract_key : public std::unary_function<times::value_type, key_type>
        {
            std::string operator()(times::value_type const & r) const
            {
                return r.first;
            }
        };

        struct extract_val : public std::unary_function<times::value_type, time_type>
        {
            time_type operator()(times::value_type const & r) const
            {
                return r.second;
            }
        };
        struct match_key : public std::unary_function<times::value_type, bool>
        {
            match_key(key_type const & key_) : key(key_) {};
            bool operator()(times::value_type const & rhs) const
            {
                return key == rhs.first;
            }
            match_key& operator=(const match_key& rhs)
            {
                key = rhs.key;
                return * this;
            }
        protected:
            key_type key;
        };

        struct accum_key : public std::binary_function<time_type, times::value_type, time_type>
        {
            accum_key(key_type const & key_) : key(key_), n(0) {};
            time_type operator()(time_type const & v, times::value_type const & rhs) const
            {
                if( key == rhs.first )
                {
                    ++n;
                    return rhs.second + v;
                }
                return v;
            }
        private:
            times::key_type key;
            mutable size_t n;
        };
    };

    inline Timer::Timer(const std::string & name)
    {
        label_ = name;
        QueryPerformanceCounter(&startTime_);
    }

    inline double Timer::current_elapsed() const
    {
        QueryPerformanceCounter(&intermediateTime_);
        __int64 clocks = intermediateTime_.QuadPart-startTime_.QuadPart;
        double elapsed = (double)clocks/(double)TimerFreq();
        return elapsed;
    }

    inline Timer::~Timer()
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
    };

    inline Timer& Timer::operator=(const std::string& name)
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
        label_ = name;
        QueryPerformanceCounter(&startTime_);
        return * this;
    }

    inline Timer::Timer(const Timer& rhs)
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
        label_ = rhs.label_;
        QueryPerformanceCounter(&startTime_);
    }

    inline std::string Timer::format_now() const
    {
        return format_elapsed(current_elapsed());
    }

    inline std::string Timer::DumpTrials(bool ClipboardAlso)
    {
        using boost::io::group;

        if( TimeMap().empty() )
        {
            return "No trials\r\n";
        }

        std::string ret = (boost::format("\r\n\r\nTimer Precision = %s\r\n\r\n")
            % format_elapsed(1.0/(double)TimerFreq())).str();

        // get a list of keys
        typedef std::set<std::string> keyset;
        keyset keys;
        std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());

        size_t maxrows = 0;

        typedef std::vector<std::string> strings;
        strings lines;

        static const size_t t = 9;

        std::string head =
            (boost::format("=== %-s %-s %-s %-s %-s %-s ===")
            //% (t*2)
            //% (t*2)
            % group(std::setw(t*2), std::setprecision(t*2), "Item" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t), "Trials")
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "Ttl Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t), "Avg Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "Mean Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "StdDev")
            ).str();

        ret += (boost::format("\r\n%s\r\n") % head).str();
        if( ClipboardAlso )
            lines.push_back("Item\tTrials\tTtl Time\tAvg Time\tMean Time\tStdDev\r\n");
        // dump the values for each key
        for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )
        {
            time_type ttl = 0;
            ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));
            size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));
            if( num > maxrows )
                maxrows = num;
            time_type avg = ttl / num;

            // compute mean
            std::vector<time_type> sortedTimes;
            dibcore::stl::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));
            std::sort(sortedTimes.begin(), sortedTimes.end());
            size_t mid = (size_t)floor((double)num/2.0);
            double mean = ( num > 1 && (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];

            // compute variance
            double sum = 0.0;
            if( num > 1 )
            {
                for( std::vector<time_type>::iterator cur = sortedTimes.begin(); sortedTimes.end() != cur; ++cur )
                    sum += pow(*cur-mean,2.0);
            }

            // compute std dev
            double stddev = num > 1 ? sqrt(sum/((double)num-1.0)) : 0.0;

            ret += (boost::format("    %-s %-s %-s %-s %-s %-s\r\n")
                % group(std::setw(t*2), std::setprecision(t*2) , (*key))
                % group(std::setw(t), std::setprecision(t) , (boost::format("%d") %num).str() )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(ttl).c_str() )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(avg) )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(mean) )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(stddev)) ).str();

            if( ClipboardAlso )
                lines.push_back((
                boost::format("%s\t%s\t%s\t%s\t%s\t%s\r\n")
                % (*key )
                % (boost::format("%d") %num)
                % format_elapsed(ttl)
                % format_elapsed(avg)
                % format_elapsed(mean)
                % format_elapsed(stddev)
                ).str());

        }
        ret += (boost::format("%s\r\n")
            % std::string(head.length(),'=') ).str();

        if( ClipboardAlso )
        {
            // dump header row of data block
            lines.push_back("");
            {
                std::string s;
                for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
                {
                    if( key != keys.begin() )
                        s.append("\t");
                    s.append(*key);
                }
                s.append("\r\n");
                lines.push_back(s);
            }

            // blow out the flat map of time values to a seperate vector of times for each key
            typedef std::map<std::string, std::vector<time_type> > nodematrix;
            nodematrix nodes;
            for( times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )
                nodes[time->first].push_back(time->second);

            // dump each data point
            for( size_t row = 0; row < maxrows; ++row )
            {
                std::string rowDump;
                for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
                {
                    if( key != keys.begin() )
                        rowDump.append("\t");
                    if( nodes[*key].size() > row )
                        rowDump.append((
                        boost::format("%f")
                        % nodes[*key][row]
                    ).str());
                }
                rowDump.append("\r\n");
                lines.push_back(rowDump);
            }

            // dump to the clipboard
            std::string dump;
            for( strings::iterator s = lines.begin(); s != lines.end(); ++s )
            {
                dump.append(*s);
            }

            OpenClipboard(0);
            EmptyClipboard();
            HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);
            if( hg )
            {
                char* buf = (char*)GlobalLock(hg);
                if( buf )
                {
                    std::copy(dump.begin(), dump.end(), buf);
                    buf[dump.length()] = 0;
                }
                GlobalUnlock(hg);
                SetClipboardData(CF_TEXT, hg);
            }
            CloseClipboard();
        }

        return ret;
    }

    inline std::string Timer::format_elapsed(double d)
    {
        if( d < 0.00000001 )
        {
            // show in ps with 4 digits
            return (boost::format("%0.4f ps") % (d * 1000000000000.0)).str();
        }
        if( d < 0.00001 )
        {
            // show in ns
            return (boost::format("%0.0f ns")% (d * 1000000000.0)).str();
        }
        if( d < 0.001 )
        {
            // show in us
            return (boost::format("%0.0f us") % (d * 1000000.0)).str();
        }
        if( d < 0.1 )
        {
            // show in ms
            return (boost::format("%0.0f ms") % (d * 1000.0)).str();
        }
        if( d <= 60.0 )
        {
            // show in seconds
            return (boost::format("%0.2f s") % d).str();
        }
        if( d < 3600.0 )
        {
            // show in min:sec
            return (boost::format("%01.0f:%02.2f") % floor(d/60.0) % fmod(d,60.0)).str();
        }
        // show in h:min:sec
        return (boost::format("%01.0f:%02.0f:%02.2f") % floor(d/3600.0) % floor(fmod(d,3600.0)/60.0) % fmod(d,60.0)).str();
    }

    inline void Timer::Reset()
    {
        TimeMap().clear();
    }

    inline __int64 Timer::TimerFreq()
    {
        static __int64 freq = 0;
        static bool init = false;
        if( !init )
        {
            LARGE_INTEGER li;
            QueryPerformanceFrequency(&li);
            freq = li.QuadPart;
            init = true;
        }
        return freq;
    }

    inline Timer::times& Timer::TimeMap()
    {
        static times times_;
        return times_;
    }
};  // namespace dbg
</code>```

Body:
I wrote a class that does this, too, because I couldn't find anything that did what I wanted but was still easy to incorporate in to existing code with copy-paste coding techniques.

(edit) Note that as mentioned in the comments, the act of timing itself changes the nature of what you're timing.  But then I'm sure you understand this all too well.  This class has still been very useful to me in finding hotspots & bottlenecks, in addition to giving me at least a rough high-side estimate of how long certain code takes to run.  The code I present here was never intended to be production-worthy.  Use it as such.

Here's a sample output of my class:

Timer Precision = 385 ns

=== Item               Trials    Ttl Time  Avg Time  Mean Time StdDev    ===
    DB Connect         1         0.11 s    0.11 s    0.11 s    0.0000 ps
    Entry Parse        3813      0.33 s    86 us     82 us     18 us
    File Load          1         50 ms     50 ms     50 ms     0.0000 ps
    Option Parse       1         5 ms      5 ms      5 ms      0.0000 ps
    Record Update      3812      0.53 s    140 us    127 us    49 us
============================================================================

Each "Item" is one section of code I wanted to time.  The Timer object uses RAII (via auto_ptr) to allow automatic start & stop.  Here's some sample client-side code demonstrating how to use it:

Sample Code:

int main(int ac, char* av[])
{
    std::auto_ptr<dbg::Timer> section_timer(new dbg::Timer("Option Parse"));
    // MAGIC: Parse the command line...

    section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("File Load"));
    // MAGIC: Load a big file...

    section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("DB Connect"));
    // MAGIC: Establish a DB connection...

    for( /* for each item in the file*/  )
    {
      section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("Entry Parse"));
      // MAGIC: Parse the incoming item
      section_timer = auto_ptr<dbg::Timer>(new dbg::Timer("Record Update"));
      // MAGIC: Update the database
    }

    // Dump the output shown above

    cout << dbg::Timer::DumpTrials() << endl;
}

The implementation of this class is in an include library.  You don't need to compile anything.  I use Boost.Format to do the string formatting, but this could be replaced simply enough.

Here is the implementation (my actual implementation splits this in to two files, core.h and core_dbg.hpp; the latter is #includeed directly from the former).

Implementation:

namespace dbg
{
    class Timer
    {
    public:
        inline Timer(const std::string & name);
        inline Timer(const Timer& rhs);
        inline virtual ~Timer();
        inline std::string format_now() const;
        double current_elapsed() const;

        Timer& operator=(const std::string& name);

        static std::string DumpTrials(bool ClipboardAlso=false);
        static void Reset();
        static std::string format_elapsed(double d) ;

    private:
        typedef std::string key_type;
        typedef double time_type;
        typedef std::multimap<key_type, time_type> times;

        static __int64 TimerFreq();

        LARGE_INTEGER startTime_, stopTime_;
        mutable LARGE_INTEGER intermediateTime_;
        std::string label_;

        static times& TimeMap();

        struct extract_key : public std::unary_function<times::value_type, key_type>
        {
            std::string operator()(times::value_type const & r) const
            {
                return r.first;
            }
        };

        struct extract_val : public std::unary_function<times::value_type, time_type>
        {
            time_type operator()(times::value_type const & r) const
            {
                return r.second;
            }
        };
        struct match_key : public std::unary_function<times::value_type, bool>
        {
            match_key(key_type const & key_) : key(key_) {};
            bool operator()(times::value_type const & rhs) const
            {
                return key == rhs.first;
            }
            match_key& operator=(const match_key& rhs)
            {
                key = rhs.key;
                return * this;
            }
        protected:
            key_type key;
        };

        struct accum_key : public std::binary_function<time_type, times::value_type, time_type>
        {
            accum_key(key_type const & key_) : key(key_), n(0) {};
            time_type operator()(time_type const & v, times::value_type const & rhs) const
            {
                if( key == rhs.first )
                {
                    ++n;
                    return rhs.second + v;
                }
                return v;
            }
        private:
            times::key_type key;
            mutable size_t n;
        };
    };

    inline Timer::Timer(const std::string & name)
    {
        label_ = name;
        QueryPerformanceCounter(&startTime_);
    }

    inline double Timer::current_elapsed() const
    {
        QueryPerformanceCounter(&intermediateTime_);
        __int64 clocks = intermediateTime_.QuadPart-startTime_.QuadPart;
        double elapsed = (double)clocks/(double)TimerFreq();
        return elapsed;
    }

    inline Timer::~Timer()
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
    };

    inline Timer& Timer::operator=(const std::string& name)
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
        label_ = name;
        QueryPerformanceCounter(&startTime_);
        return * this;
    }

    inline Timer::Timer(const Timer& rhs)
    {
        double elapsed = current_elapsed();
        stopTime_.QuadPart = intermediateTime_.QuadPart;
        TimeMap().insert(std::make_pair(label_,elapsed));
        label_ = rhs.label_;
        QueryPerformanceCounter(&startTime_);
    }

    inline std::string Timer::format_now() const
    {
        return format_elapsed(current_elapsed());
    }

    inline std::string Timer::DumpTrials(bool ClipboardAlso)
    {
        using boost::io::group;

        if( TimeMap().empty() )
        {
            return "No trials\r\n";
        }

        std::string ret = (boost::format("\r\n\r\nTimer Precision = %s\r\n\r\n")
            % format_elapsed(1.0/(double)TimerFreq())).str();

        // get a list of keys
        typedef std::set<std::string> keyset;
        keyset keys;
        std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());

        size_t maxrows = 0;

        typedef std::vector<std::string> strings;
        strings lines;

        static const size_t t = 9;

        std::string head =
            (boost::format("=== %-s %-s %-s %-s %-s %-s ===")
            //% (t*2)
            //% (t*2)
            % group(std::setw(t*2), std::setprecision(t*2), "Item" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t), "Trials")
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "Ttl Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t), "Avg Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "Mean Time" )
            //% t
            //% t
            % group(std::setw(t), std::setprecision(t),  "StdDev")
            ).str();

        ret += (boost::format("\r\n%s\r\n") % head).str();
        if( ClipboardAlso )
            lines.push_back("Item\tTrials\tTtl Time\tAvg Time\tMean Time\tStdDev\r\n");
        // dump the values for each key
        for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )
        {
            time_type ttl = 0;
            ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));
            size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));
            if( num > maxrows )
                maxrows = num;
            time_type avg = ttl / num;

            // compute mean
            std::vector<time_type> sortedTimes;
            dibcore::stl::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));
            std::sort(sortedTimes.begin(), sortedTimes.end());
            size_t mid = (size_t)floor((double)num/2.0);
            double mean = ( num > 1 && (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];

            // compute variance
            double sum = 0.0;
            if( num > 1 )
            {
                for( std::vector<time_type>::iterator cur = sortedTimes.begin(); sortedTimes.end() != cur; ++cur )
                    sum += pow(*cur-mean,2.0);
            }

            // compute std dev
            double stddev = num > 1 ? sqrt(sum/((double)num-1.0)) : 0.0;

            ret += (boost::format("    %-s %-s %-s %-s %-s %-s\r\n")
                % group(std::setw(t*2), std::setprecision(t*2) , (*key))
                % group(std::setw(t), std::setprecision(t) , (boost::format("%d") %num).str() )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(ttl).c_str() )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(avg) )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(mean) )
                % group(std::setw(t), std::setprecision(t) , format_elapsed(stddev)) ).str();

            if( ClipboardAlso )
                lines.push_back((
                boost::format("%s\t%s\t%s\t%s\t%s\t%s\r\n")
                % (*key )
                % (boost::format("%d") %num)
                % format_elapsed(ttl)
                % format_elapsed(avg)
                % format_elapsed(mean)
                % format_elapsed(stddev)
                ).str());

        }
        ret += (boost::format("%s\r\n")
            % std::string(head.length(),'=') ).str();

        if( ClipboardAlso )
        {
            // dump header row of data block
            lines.push_back("");
            {
                std::string s;
                for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
                {
                    if( key != keys.begin() )
                        s.append("\t");
                    s.append(*key);
                }
                s.append("\r\n");
                lines.push_back(s);
            }

            // blow out the flat map of time values to a seperate vector of times for each key
            typedef std::map<std::string, std::vector<time_type> > nodematrix;
            nodematrix nodes;
            for( times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )
                nodes[time->first].push_back(time->second);

            // dump each data point
            for( size_t row = 0; row < maxrows; ++row )
            {
                std::string rowDump;
                for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )
                {
                    if( key != keys.begin() )
                        rowDump.append("\t");
                    if( nodes[*key].size() > row )
                        rowDump.append((
                        boost::format("%f")
                        % nodes[*key][row]
                    ).str());
                }
                rowDump.append("\r\n");
                lines.push_back(rowDump);
            }

            // dump to the clipboard
            std::string dump;
            for( strings::iterator s = lines.begin(); s != lines.end(); ++s )
            {
                dump.append(*s);
            }

            OpenClipboard(0);
            EmptyClipboard();
            HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);
            if( hg )
            {
                char* buf = (char*)GlobalLock(hg);
                if( buf )
                {
                    std::copy(dump.begin(), dump.end(), buf);
                    buf[dump.length()] = 0;
                }
                GlobalUnlock(hg);
                SetClipboardData(CF_TEXT, hg);
            }
            CloseClipboard();
        }

        return ret;
    }

    inline std::string Timer::format_elapsed(double d)
    {
        if( d < 0.00000001 )
        {
            // show in ps with 4 digits
            return (boost::format("%0.4f ps") % (d * 1000000000000.0)).str();
        }
        if( d < 0.00001 )
        {
            // show in ns
            return (boost::format("%0.0f ns")% (d * 1000000000.0)).str();
        }
        if( d < 0.001 )
        {
            // show in us
            return (boost::format("%0.0f us") % (d * 1000000.0)).str();
        }
        if( d < 0.1 )
        {
            // show in ms
            return (boost::format("%0.0f ms") % (d * 1000.0)).str();
        }
        if( d <= 60.0 )
        {
            // show in seconds
            return (boost::format("%0.2f s") % d).str();
        }
        if( d < 3600.0 )
        {
            // show in min:sec
            return (boost::format("%01.0f:%02.2f") % floor(d/60.0) % fmod(d,60.0)).str();
        }
        // show in h:min:sec
        return (boost::format("%01.0f:%02.0f:%02.2f") % floor(d/3600.0) % floor(fmod(d,3600.0)/60.0) % fmod(d,60.0)).str();
    }

    inline void Timer::Reset()
    {
        TimeMap().clear();
    }

    inline __int64 Timer::TimerFreq()
    {
        static __int64 freq = 0;
        static bool init = false;
        if( !init )
        {
            LARGE_INTEGER li;
            QueryPerformanceFrequency(&li);
            freq = li.QuadPart;
            init = true;
        }
        return freq;
    }

    inline Timer::times& Timer::TimeMap()
    {
        static times times_;
        return times_;
    }
};  // namespace dbg


问:
MobileFirst 8 : Unexpected error encountered while storing data
We are using UserAuthenticationSecurityCheck to authenticate user.

If verification is successful, the MFP server will store the user attributes.

```<code>public class AuthSecurityCheck extends UserAuthenticationSecurityCheck {

    static Logger logger = Logger.getLogger(AuthSecurityCheck.class.getName());

    private String userId, displayName;
    private JSONObject attrObject;

    private String errorMessage;

    @Override
    protected AuthenticatedUser createUser() {
        Map<String, Object> userAttrsMap = new HashMap<String, Object>();
        userAttrsMap.put("attributes",attrObject);
        return new AuthenticatedUser(userId, displayName, this.getName(), userAttrsMap);
    }
...
}
</code>```

But if we store larger data(when userAttrsMap is large enough), we will get the 500 error.

errorMsg: Unexpected error encountered while storing data

The error is shown below：

Full source is on Github: https://github.com/DannyYang/PMR_CreateUserStoredLargeData

MFP version:

cordova-plugin-mfp 8.0.2017102115

MFP DevelopKit : 8.0.0.00-20171024-064640

答:
The issue happens owing to the size of the data you are holding within the AuthenticatedUser object and thereby the Securitycheck's state.

MFP runtime saves the state of the securitycheck along with all the attributes to the attribute store . This involves serializing the security check state and persisting it to the DB. With a large object ( the custom map you have) this persistence operation fails and ends in a transaction rollback. This happens because the data you are trying to persist is too big and exceeds the allocated size.

SecurityCheck’s design consideration is to use it for a security check ( validation) and creating an identity object. Within your security check implementation, you have the following:

```<code>//Here the large data is assigned to the variable.
attrObject = JSONObject.parse(largeJSONString);

//This data is set into the AuthenticatedUser object.
Map<String, Object> userAttrsMap = new HashMap<String, Object>();
userAttrsMap.put("attributes",attrObject);
return new AuthenticatedUser(userId, displayName, this.getName(), userAttrsMap);
</code>```

In this scenario this large data becomes part of the Securitycheck itself and will be serialized and attempted for persistence into the attribute store. When this data does not fit in the column, the transaction is rolled back and the error condition is propagated to the end user. Hence the error message you see - ” Unexpected error occured while storing data”.   Enabling detailed trace will indicate the actual cause of the issue in the server trace logs.

Either way, this approach is  not recommended at all in production systems because:

a) Every request from the client reaching the server goes through security introspection which will involve the server to load, check and update the securitycheck’s state. On systems taking heavy load ( production ) this can and will have performance costs. The process involves serializing the data and deserializing it later. In a distributed topology ( cluster or farms ) the request may end up in any of the nodes and these nodes will have to load and later save the security check's state to the store. All this will impact performance of your system.

b) At the end of successful authentication, the AuthenticatedUser object is propagated to the client application indicating completion of the login flow . Even if the SecurityCheck state were to be stored successfully in the attribute store ( with large data) transmitting large payloads over the network just to indicate successful login will be counter productive. For the enduser it may appear as if nothing has happened since they entered the credentials, while data indicating success is still getting downloaded.

c) Under heavy loads , the server will be strained from both a) and b) above.

You should consider cutting down the data that is propagated to the client within the authenticateduser object. Keep the data minimal within the AuthenticatedUser object.  Instead, you should offload obtaining large data to resource adapters , that can be accessed post successful login .

Body:
We are using UserAuthenticationSecurityCheck to authenticate user.

If verification is successful, the MFP server will store the user attributes.

public class AuthSecurityCheck extends UserAuthenticationSecurityCheck {

    static Logger logger = Logger.getLogger(AuthSecurityCheck.class.getName());

    private String userId, displayName;
    private JSONObject attrObject;

    private String errorMessage;

    @Override
    protected AuthenticatedUser createUser() {
        Map<String, Object> userAttrsMap = new HashMap<String, Object>();
        userAttrsMap.put("attributes",attrObject);
        return new AuthenticatedUser(userId, displayName, this.getName(), userAttrsMap);
    }
...
}

But if we store larger data(when userAttrsMap is large enough), we will get the 500 error.

errorMsg: Unexpected error encountered while storing data

The error is shown below：

Full source is on Github: https://github.com/DannyYang/PMR_CreateUserStoredLargeData

MFP version:

cordova-plugin-mfp 8.0.2017102115

MFP DevelopKit : 8.0.0.00-20171024-064640

Body:
The issue happens owing to the size of the data you are holding within the AuthenticatedUser object and thereby the Securitycheck's state.

MFP runtime saves the state of the securitycheck along with all the attributes to the attribute store . This involves serializing the security check state and persisting it to the DB. With a large object ( the custom map you have) this persistence operation fails and ends in a transaction rollback. This happens because the data you are trying to persist is too big and exceeds the allocated size.

SecurityCheck’s design consideration is to use it for a security check ( validation) and creating an identity object. Within your security check implementation, you have the following:

//Here the large data is assigned to the variable.
attrObject = JSONObject.parse(largeJSONString);

//This data is set into the AuthenticatedUser object.
Map<String, Object> userAttrsMap = new HashMap<String, Object>();
userAttrsMap.put("attributes",attrObject);
return new AuthenticatedUser(userId, displayName, this.getName(), userAttrsMap);

In this scenario this large data becomes part of the Securitycheck itself and will be serialized and attempted for persistence into the attribute store. When this data does not fit in the column, the transaction is rolled back and the error condition is propagated to the end user. Hence the error message you see - ” Unexpected error occured while storing data”.   Enabling detailed trace will indicate the actual cause of the issue in the server trace logs.

Either way, this approach is  not recommended at all in production systems because:

a) Every request from the client reaching the server goes through security introspection which will involve the server to load, check and update the securitycheck’s state. On systems taking heavy load ( production ) this can and will have performance costs. The process involves serializing the data and deserializing it later. In a distributed topology ( cluster or farms ) the request may end up in any of the nodes and these nodes will have to load and later save the security check's state to the store. All this will impact performance of your system.

b) At the end of successful authentication, the AuthenticatedUser object is propagated to the client application indicating completion of the login flow . Even if the SecurityCheck state were to be stored successfully in the attribute store ( with large data) transmitting large payloads over the network just to indicate successful login will be counter productive. For the enduser it may appear as if nothing has happened since they entered the credentials, while data indicating success is still getting downloaded.

c) Under heavy loads , the server will be strained from both a) and b) above.

You should consider cutting down the data that is propagated to the client within the authenticateduser object. Keep the data minimal within the AuthenticatedUser object.  Instead, you should offload obtaining large data to resource adapters , that can be accessed post successful login .


问:
javascript - How to define a property within a function?
So I can define a property on a function from the outside such as: createNewPerson.hmm = 3; and I get the result 3 when I use the alert. However if I try to do the same but from within a function (as in define a property within a function) it doesn't work.. I tried all the commented lines below. Is there a different way to achieve this or is it simply not possible? If it's not possible, then how does javascript append the .hmm property to the function and later call it?

Full code:

```<code>function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
//this.hello = hgfgh;

}
createNewPerson.hmm = 3;
alert(createNewPerson.hmm);
alert(createNewPerson.hello);
</code>```

答:
Hi please try below code,

jsFiddle

```<code>function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
this.hello = "hgfg";
this.name = name;
}
var cnp = new createNewPerson('de');
cnp.hmm = 3;
alert(cnp.hmm);
alert(cnp.hello);
alert(cnp.name);
</code>```

Body:
So I can define a property on a function from the outside such as: createNewPerson.hmm = 3; and I get the result 3 when I use the alert. However if I try to do the same but from within a function (as in define a property within a function) it doesn't work.. I tried all the commented lines below. Is there a different way to achieve this or is it simply not possible? If it's not possible, then how does javascript append the .hmm property to the function and later call it?

Full code:

function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
//this.hello = hgfgh;

}
createNewPerson.hmm = 3;
alert(createNewPerson.hmm);
alert(createNewPerson.hello);

Body:
Hi please try below code,

jsFiddle

function createNewPerson(name) {
//var hello = "hgfgh";
//hello: "hgfgh"
//hello = hgfgh;
this.hello = "hgfg";
this.name = name;
}
var cnp = new createNewPerson('de');
cnp.hmm = 3;
alert(cnp.hmm);
alert(cnp.hello);
alert(cnp.name);


问:
How to join 2 dataframes in Spark based on a wildcard/regex condition?
I have 2 dataframes df1 and df2.
Suppose there is a location column in df1 which may contain a regular URL or a URL with a wildcard, e.g.:

stackoverflow.com/questions/*

*.cnn.com

cnn.com/*/politics

The seconds dataframe df2 has url field which may contain only valid URLs without wildcards.

I need to join these two dataframes, something like df1.join(df2, $"location" matches $"url") if there was magic matches operator in join conditions.

After some googling I still don't see a way how to achieve this. How would you approach solving such problem?

答:
There exist "magic" matches operator - it is called rlike

```<code>val df1 = Seq("stackoverflow.com/questions/.*$","^*.cnn.com$", "nn.com/*/politics").toDF("location")
val df2 = Seq("stackoverflow.com/questions/47272330").toDF("url")

df2.join(df1, expr("url rlike location")).show
+--------------------+--------------------+
|                 url|            location|
+--------------------+--------------------+
|stackoverflow.com...|stackoverflow.com...|
+--------------------+--------------------+
</code>```

however there are some caveats:

Patterns have to be proper regular expressions, anchored in case of leading / trailing wildcards.

It is executed with Cartesian product (How can we JOIN two Spark SQL dataframes using a SQL-esque "LIKE" criterion?):

```<code>== Physical Plan ==
BroadcastNestedLoopJoin BuildRight, Inner, url#217 RLIKE location#211
:- *Project [value#215 AS url#217]
:  +- *Filter isnotnull(value#215)
:     +- LocalTableScan [value#215]
+- BroadcastExchange IdentityBroadcastMode
   +- *Project [value#209 AS location#211]
      +- *Filter isnotnull(value#209)
         +- LocalTableScan [value#209]
</code>```

It is possible to filter candidates using method I described in Efficient string matching in Apache Spark

Body:
There exist "magic" matches operator - it is called rlike

val df1 = Seq("stackoverflow.com/questions/.*$","^*.cnn.com$", "nn.com/*/politics").toDF("location")
val df2 = Seq("stackoverflow.com/questions/47272330").toDF("url")

df2.join(df1, expr("url rlike location")).show
+--------------------+--------------------+
|                 url|            location|
+--------------------+--------------------+
|stackoverflow.com...|stackoverflow.com...|
+--------------------+--------------------+

however there are some caveats:

Patterns have to be proper regular expressions, anchored in case of leading / trailing wildcards.

It is executed with Cartesian product (How can we JOIN two Spark SQL dataframes using a SQL-esque "LIKE" criterion?):

== Physical Plan ==
BroadcastNestedLoopJoin BuildRight, Inner, url#217 RLIKE location#211
:- *Project [value#215 AS url#217]
:  +- *Filter isnotnull(value#215)
:     +- LocalTableScan [value#215]
+- BroadcastExchange IdentityBroadcastMode
   +- *Project [value#209 AS location#211]
      +- *Filter isnotnull(value#209)
         +- LocalTableScan [value#209]

It is possible to filter candidates using method I described in Efficient string matching in Apache Spark


问:
Why does #define _LARGEFILE_SOURCE break these function pointers?
I have the following code in which the shared library being loaded is delivered as a pre-compiled binary. It is compiled with the linaro toolchain.

```<code>gbm_create_device(int fd)
{
   struct gbm_device *gbm = NULL;
   void *module;
   const struct gbm_backend *backend = NULL

   module = dlopen("/usr/lib/gbm/gbm_pvr.so", RTLD_NOW | RTLD_GLOBAL);
   backend = dlsym(module, "gbm_backend");
   gbm = backend->create_device(fd);

   gbm->surface_create(gbm, width, height, format, flags);
}

struct gbm_device {
   /* Hack to make a gbm_device detectable by its first element. */
   struct gbm_device *(*dummy)(int);

   int fd;
   const char *name;
   unsigned int refcount;
   struct stat stat;

   ...
   void (*bo_destroy)(struct gbm_bo *bo);

   struct gbm_surface *(*surface_create)(struct gbm_device *gbm,
                                         uint32_t width, uint32_t height,
                                         uint32_t format, uint32_t flags);
   struct gbm_bo *(*surface_lock_front_buffer)(struct gbm_surface *surface);
   ...
};
</code>```

The code normally works correctly. However, when I add the following defines, gbm->surface_create(...) jumps to the wrong memory location in the shared library. Why? It is not apparent to me from the official GNU page.

```<code>#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS=64
</code>```

Additional Information:

I used gdb to check the first step after gbm->surface_create(...)`

Without these defines:

```<code>0xb6beb5d0 in ?? () from /usr/lib/gbm/gbm_pvr.so
...
// Correct behavior
</code>```

With the defines:

```<code>0xb6c414a4 in ?? () from /usr/lib/gbm/gbm_pvr.so
...
// Segmentation fault
</code>```

答:
struct gbm_device contains a struct stat stat; member.

struct stat changes size depending on _LARGEFILE_SOURCE. It contains members off_t st_size; etc. that are 32-bit or 64-bit.

The struct in the binary compiled without _LARGEFILE_SOURCE and in your code compiled with _LARGEFILE_SOURCE are not ABI-compatible.

The function pointers are located after that member of the structure; changing the size of that member changes the apparent offsets of the following members, which is how the wrong function pointer values are being used.

Body:
I have the following code in which the shared library being loaded is delivered as a pre-compiled binary. It is compiled with the linaro toolchain.

gbm_create_device(int fd)
{
   struct gbm_device *gbm = NULL;
   void *module;
   const struct gbm_backend *backend = NULL

   module = dlopen("/usr/lib/gbm/gbm_pvr.so", RTLD_NOW | RTLD_GLOBAL);
   backend = dlsym(module, "gbm_backend");
   gbm = backend->create_device(fd);

   gbm->surface_create(gbm, width, height, format, flags);
}

struct gbm_device {
   /* Hack to make a gbm_device detectable by its first element. */
   struct gbm_device *(*dummy)(int);

   int fd;
   const char *name;
   unsigned int refcount;
   struct stat stat;

   ...
   void (*bo_destroy)(struct gbm_bo *bo);

   struct gbm_surface *(*surface_create)(struct gbm_device *gbm,
                                         uint32_t width, uint32_t height,
                                         uint32_t format, uint32_t flags);
   struct gbm_bo *(*surface_lock_front_buffer)(struct gbm_surface *surface);
   ...
};

The code normally works correctly. However, when I add the following defines, gbm->surface_create(...) jumps to the wrong memory location in the shared library. Why? It is not apparent to me from the official GNU page.

#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _FILE_OFFSET_BITS=64

Additional Information:

I used gdb to check the first step after gbm->surface_create(...)`

Without these defines:

0xb6beb5d0 in ?? () from /usr/lib/gbm/gbm_pvr.so
...
// Correct behavior

With the defines:

0xb6c414a4 in ?? () from /usr/lib/gbm/gbm_pvr.so
...
// Segmentation fault


问:
Angular environment variables on an ejected project
What I want to achieve?

Generating Environments variable depending on which NODE_ENV I am currently compiling on an Ejected project (ng eject).
The same of targeting the environment using the Angular Cli:
ng build --prod || ng build --dev.

What I tried?

Setting my NODE_ENV in my scripts:

package.json

```<code>   ...
   "start": "NODE_ENV=development webpack-dev-server --port=4200",
   "start:prod": "NODE_ENV=production webpack-dev-server --port=4200",
   ...
</code>```

As suggested here, I changed my AotPlugin in webpack and replace it with:

```<code>const environmentFiles = {
'development': 'environments/environment.dev.ts',
'production': 'environments/environment.prod.ts',
};

...
new AotPlugin({
...
 "hostReplacementPaths":
   "environments/environment.ts": environmentFiles[process.env.NODE_ENV]
</code>```

Try to run: npm run-script build:prod
But the AotPlugin doesn't look to replace (hostReplacementPaths) for me the Environment variables file (environment.dev.ts || environment.prod.ts).

Any idea?

Similiar questions:

Environment file replacement is broken after switching to webpack...

答:
Actually I just reverted my ejected project and back to use the CLI!
But... I solved it just copying and pasting my environments into environment.ts with a prebuild script!

```<code>"prebuild:dev": "cp environment/environment.dev.ts environment/environment.ts"
</code>```

you can also set your NODE variables to apply your conditions into your code:

How to set Environment variables from within package.json [Node.js]

For example:

```<code>npm run prebuild:dev
// will build my dev environment
npm run prebuild:prod
// will build my prod environment
</code>```

Body:
What I want to achieve?

Generating Environments variable depending on which NODE_ENV I am currently compiling on an Ejected project (ng eject).
The same of targeting the environment using the Angular Cli:
ng build --prod || ng build --dev.

What I tried?

Setting my NODE_ENV in my scripts:

package.json

   ...
   "start": "NODE_ENV=development webpack-dev-server --port=4200",
   "start:prod": "NODE_ENV=production webpack-dev-server --port=4200",
   ...

As suggested here, I changed my AotPlugin in webpack and replace it with:

const environmentFiles = {
'development': 'environments/environment.dev.ts',
'production': 'environments/environment.prod.ts',
};

...
new AotPlugin({
...
 "hostReplacementPaths":
   "environments/environment.ts": environmentFiles[process.env.NODE_ENV]

Try to run: npm run-script build:prod
But the AotPlugin doesn't look to replace (hostReplacementPaths) for me the Environment variables file (environment.dev.ts || environment.prod.ts).

Any idea?

Similiar questions:

Environment file replacement is broken after switching to webpack...

Body:
Actually I just reverted my ejected project and back to use the CLI!
But... I solved it just copying and pasting my environments into environment.ts with a prebuild script!

"prebuild:dev": "cp environment/environment.dev.ts environment/environment.ts"

you can also set your NODE variables to apply your conditions into your code:

How to set Environment variables from within package.json [Node.js]

For example:

npm run prebuild:dev
// will build my dev environment
npm run prebuild:prod
// will build my prod environment


问:
Laravel 5.2 Many to Many query relationship with where clause
I have a little problem, I have a table with Movies and another with Genres ex: Action, Adventure etc...

Table names:

movies

movie_genre

genres

I want to fetch all the Movies with the selected Genre ex: Action

```<code>$movies = Movie::with('genres')
            ->when($genre, function ($query) use ($genre) {
                        return $query->where('genres.id', $genre->id);
                    })
            ->paginate(20);
</code>```

This php code doesn't work, how can I make it work?

PS: The genre is transfered from the view by $_GET['genre'] and stocked in the variable $genre.

Edit after the answer of @Shane and @Marcin Nabiałek :

The relationship is set in the models and when I use your code directly like this:

```<code>Movie::with('genres', 'countries', 'type')
            ->when($type, function ($query) use ($type) {
                        return $query->where('medias.type_id', $type->id);
                    })
            ->whereHas('genres', function ($query) use ($genre) {
                 return $query->where('genres.id', $genre->id);
               })
            ->paginate(20);
</code>```

it work perfectly, but with the when() function it dosn't. I have to use the when() to make the condition work only if there is a genre selected by the user.

答:
You should use whereHas to get all movies that are assigned to given genre:

```<code>$movies = Movie::with('genres')
            ->when($genre, function ($query) use ($genre) {
                  $query->whereHas('genres', function($q) use ($genre) {
                     return $query->where('id', $genre->id);
                   });
            })->paginate(20);
</code>```

In case $genre is only id and not model, you should rather use:

```<code> return $query->where('id', $genre);
</code>```

and in case it's an array (user is allowed to choose multiple genres), you should use:

```<code> return $query->whereIn('id', (array) $genre);
</code>```

Body:
I have a little problem, I have a table with Movies and another with Genres ex: Action, Adventure etc...

Table names:

movies

movie_genre

genres

I want to fetch all the Movies with the selected Genre ex: Action

$movies = Movie::with('genres')
            ->when($genre, function ($query) use ($genre) {
                        return $query->where('genres.id', $genre->id);
                    })
            ->paginate(20);

This php code doesn't work, how can I make it work?

PS: The genre is transfered from the view by $_GET['genre'] and stocked in the variable $genre.

Edit after the answer of @Shane and @Marcin Nabiałek :

The relationship is set in the models and when I use your code directly like this:

Movie::with('genres', 'countries', 'type')
            ->when($type, function ($query) use ($type) {
                        return $query->where('medias.type_id', $type->id);
                    })
            ->whereHas('genres', function ($query) use ($genre) {
                 return $query->where('genres.id', $genre->id);
               })
            ->paginate(20);

it work perfectly, but with the when() function it dosn't. I have to use the when() to make the condition work only if there is a genre selected by the user.

Body:
You should use whereHas to get all movies that are assigned to given genre:

$movies = Movie::with('genres')
            ->when($genre, function ($query) use ($genre) {
                  $query->whereHas('genres', function($q) use ($genre) {
                     return $query->where('id', $genre->id);
                   });
            })->paginate(20);

In case $genre is only id and not model, you should rather use:

 return $query->where('id', $genre);

and in case it's an array (user is allowed to choose multiple genres), you should use:

 return $query->whereIn('id', (array) $genre);