问:
How do i filter an array inside of a array of objects?
I'm trying to filter a list by tags:

```<code>const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]
</code>```

I can filter the list by name using map and filter, my problem is when i try to list the products by tags. Do i have to use foreach inside of my products filter? There's another way of doing it?

答:
You can create a Set of selected tags, and use Array#some to check if at least one of the tags in the Set exists in the objects' tags list:

const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
];

const filterByTags = ['nature', 'family'];

const filterByTagSet = new Set(filterByTags);

const result = initialState.filter((o) =>
  o.tags.some((tag) => filterByTagSet.has(tag))
);

console.log(result);```

Body:
I'm trying to filter a list by tags:

const initialState = [
     {id:1 ,name: 'Product A', image: 'pic-001.jpg', tags: ['nature', 'camping', 'outdoor']},
     {id:2 ,name: 'Product B', image: 'pic-002.jpg', tags: ['winter', 'hiking', 'camping', 'snow']},
     {id:3 ,name: 'Product C', image: 'pic-003.jpg', tags: ['vacation', 'family', 'kids', 'river', 'lake', 'fishing']}
   ]

I can filter the list by name using map and filter, my problem is when i try to list the products by tags. Do i have to use foreach inside of my products filter? There's another way of doing it?


来源: stackexchange

问:
fatal error: unexpectedly found nil while unwrapping an Optional value on adding audio Swift
I'm trying to add some audio when a button is pressed and the code I use doesnt have any error until I run then I get the 'fatal error: unexpectedly found nil while unwrapping an Optional value' in the out put this line of code:

```<code>let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
</code>```

This is my entire code just for reference:

```<code>import UIKit
import AVFoundation

class ViewController: UIViewController {

let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for sound in soundFilenames {

        do {

            let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
            let audioPlayer = try AVAudioPlayer(contentsOf: url)

            audioPlayers.append(audioPlayer)
        }
        catch {

            audioPlayers.append(AVAudioPlayer())

        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(_ sender: UIButton) {

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}
</code>```

}

答:
Error is self-describing: url(forResource: withExtension:) returned nil and force-unwrapping it with ! causes your crash.

To fix this crash re-check that:

all files were added to the project

file names are written right in the code

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to add some audio when a button is pressed and the code I use doesnt have any error until I run then I get the 'fatal error: unexpectedly found nil while unwrapping an Optional value' in the out put this line of code:

let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!

This is my entire code just for reference:

import UIKit
import AVFoundation

class ViewController: UIViewController {

let soundFilenames = ["60gs", "check", "dada", "danceforme", "eat", "gods", "irelandbaby", "ko'd", "lefthand", "littlewerp", "nocalls", "precision", "sundaymorning", "surprise", "whothefuckisthatguy", "youlldonothing"]

var audioPlayers = [AVAudioPlayer]()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    for sound in soundFilenames {

        do {

            let url = Bundle.main.url(forResource:sound, withExtension: "mp3")!
            let audioPlayer = try AVAudioPlayer(contentsOf: url)

            audioPlayers.append(audioPlayer)
        }
        catch {

            audioPlayers.append(AVAudioPlayer())

        }
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

@IBAction func buttonTapped(_ sender: UIButton) {

    let audioPlayer = audioPlayers[sender.tag]
    audioPlayer.play()

}

}


答:
you can use indexOf function</p>

```<code>var foo = initialState.filter(function(elm){
  return elm.tags.indexOf("camping")>=0
});
</code>```

Title: How do i filter an array inside of a array of objects?

Body:
you can use indexOf function

var foo = initialState.filter(function(elm){
  return elm.tags.indexOf("camping")>=0
});


问:
Syntax error for UPDATE Table
It's since 2 hours that I am working with an UPDATE TABLE statement which gives me always Syntax error. I made this:

```<code>String falseValue = "False";
String emptyValue = "";
try {
        OrderListViewerModel orderlistviewermodell = (OrderListViewerModel) tableOrder.getSelectionModel().getSelectedItem();
        pst = conn.prepareStatement("UPDATE TABLE productList SET ordered = '" + falseValue + "', orderedshopphone = '" + emptyValue + "' WHERE barcode = " + orderlistviewermodell.getProductBarcode() + "");
        pst.executeUpdate();
        pst = conn.prepareStatement("DELETE FROM orderList WHERE productbarcode=?");
        pst.setString(1, orderlistviewermodell.getProductBarcode());
        pst.executeUpdate();
        pst.close();

    } catch (SQLException ex) {
        Logger.getLogger(StoreListViewerController.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

The Delete Works fine but the update not really. It says I have Syntax Error and check it out.

答:
the basic syntax of update query is

```<code>update table_name set col1 = val1 , col2 = val2 ,... [where condition];
</code>```

so there is no need of  TABLE key word.

your line should be

```<code>pst = conn.prepareStatement("UPDATE productList SET ordered = '" + falseValue + "', orderedshopphone = '" + emptyValue + "' WHERE barcode = " + orderlistviewermodell.getProductBarcode() + "");
</code>```

Title: Syntax error for UPDATE Table

Body:
It's since 2 hours that I am working with an UPDATE TABLE statement which gives me always Syntax error. I made this:

String falseValue = "False";
String emptyValue = "";
try {
        OrderListViewerModel orderlistviewermodell = (OrderListViewerModel) tableOrder.getSelectionModel().getSelectedItem();
        pst = conn.prepareStatement("UPDATE TABLE productList SET ordered = '" + falseValue + "', orderedshopphone = '" + emptyValue + "' WHERE barcode = " + orderlistviewermodell.getProductBarcode() + "");
        pst.executeUpdate();
        pst = conn.prepareStatement("DELETE FROM orderList WHERE productbarcode=?");
        pst.setString(1, orderlistviewermodell.getProductBarcode());
        pst.executeUpdate();
        pst.close();

    } catch (SQLException ex) {
        Logger.getLogger(StoreListViewerController.class.getName()).log(Level.SEVERE, null, ex);
    }

The Delete Works fine but the update not really. It says I have Syntax Error and check it out.

Body:
the basic syntax of update query is

update table_name set col1 = val1 , col2 = val2 ,... [where condition];

so there is no need of  TABLE key word.

your line should be

pst = conn.prepareStatement("UPDATE productList SET ordered = '" + falseValue + "', orderedshopphone = '" + emptyValue + "' WHERE barcode = " + orderlistviewermodell.getProductBarcode() + "");


问:
Setting the window icon in a nana C++ GUI application
I am using nana for building a GUI in my C++ application, which basically works fine. However, I have trouble setting the window icon under Windows:

```<code>nana::API::window_icon_default(nana::paint::image("hunger.ico"));
</code>```

There is definitely a file hunger.ico within the same folder as the executable, I double-checked that. That icon file is 32x32 in size (or 16x16). I also tried to retrieve the full path to the icon file, like so:

```<code>wchar_t buffer[MAX_PATH];
DWORD len = sizeof(buffer);
GetModuleFileName(nullptr, buffer, len);
std::wstring ws(buffer);
// concatenate ws and "hunger.ico" here
</code>```

But when I run the (console) application from within VS2015, the default window icon is used. Any ideas what I am missing here?

答:
This call works well for me.  The icon appears in the application window title bar and in the task bar.

```<code>nana::API::window_icon(
    myform.handle(),
    nana::paint::image("myicon.ico"));
</code>```

You need to pass in the handle of the application form ( why?  shouldn't  window_icon() accept the form and extract the handle for itself? ) and the icon file needs to be in the working folder with the different resolutions required

Body:
I am using nana for building a GUI in my C++ application, which basically works fine. However, I have trouble setting the window icon under Windows:

nana::API::window_icon_default(nana::paint::image("hunger.ico"));

There is definitely a file hunger.ico within the same folder as the executable, I double-checked that. That icon file is 32x32 in size (or 16x16). I also tried to retrieve the full path to the icon file, like so:

wchar_t buffer[MAX_PATH];
DWORD len = sizeof(buffer);
GetModuleFileName(nullptr, buffer, len);
std::wstring ws(buffer);
// concatenate ws and "hunger.ico" here

But when I run the (console) application from within VS2015, the default window icon is used. Any ideas what I am missing here?

Body:
This call works well for me.  The icon appears in the application window title bar and in the task bar.

nana::API::window_icon(
    myform.handle(),
    nana::paint::image("myicon.ico"));

You need to pass in the handle of the application form ( why?  shouldn't  window_icon() accept the form and extract the handle for itself? ) and the icon file needs to be in the working folder with the different resolutions required


问:
Decoding base64 from POST to use in PIL
I'm making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow.

I've looked at some examples (1, 2, 3), and I think I get the gist of the process, but I keep getting an error where Pillow can't read the string I gave it.

Here's what I've got so far:

```<code>import cStringIO
from PIL import Image
import base64

data = request.form
image_string = cStringIO.StringIO(base64.b64decode(data['img']))
image = Image.open(image_string)
</code>```

which gives the error:

```<code>IOError: cannot identify image file <cStringIO.StringIO object at 0x10f84c7a0>
</code>```

答:
Sorry for necromancy, but none of the answers worked completely for me. Here is code working on Python 3.6 and Flask 0.13.

Server:

```<code>from flask import Flask, jsonify, request
from io import BytesIO
from web import app
import base64
import re
import json
from PIL import Image

@app.route('/process_image', methods=['post'])
def process_image():
    image_data = re.sub('^data:image/.+;base64,', '', request.form['data'])
    im = Image.open(BytesIO(base64.b64decode(image_data)))
    return json.dumps({'result': 'success'}), 200, {'ContentType': 'application/json'}
</code>```

Client JS:

```<code>// file comes from file input
var reader = new FileReader();
reader.onloadend = function () {
    var fileName = file.name;
    $.post('/process_image', { data: reader.result, name: fileName });
};
reader.readAsDataURL(file);
</code>```

Title: Decoding base64 from POST to use in PIL

Body:
I'm making a simple API in Flask that accepts an image encoded in base64, then decodes it for further processing using Pillow.

I've looked at some examples (1, 2, 3), and I think I get the gist of the process, but I keep getting an error where Pillow can't read the string I gave it.

Here's what I've got so far:

import cStringIO
from PIL import Image
import base64

data = request.form
image_string = cStringIO.StringIO(base64.b64decode(data['img']))
image = Image.open(image_string)

which gives the error:

IOError: cannot identify image file <cStringIO.StringIO object at 0x10f84c7a0>

Body:
Sorry for necromancy, but none of the answers worked completely for me. Here is code working on Python 3.6 and Flask 0.13.

Server:

from flask import Flask, jsonify, request
from io import BytesIO
from web import app
import base64
import re
import json
from PIL import Image

@app.route('/process_image', methods=['post'])
def process_image():
    image_data = re.sub('^data:image/.+;base64,', '', request.form['data'])
    im = Image.open(BytesIO(base64.b64decode(image_data)))
    return json.dumps({'result': 'success'}), 200, {'ContentType': 'application/json'}

Client JS:

// file comes from file input
var reader = new FileReader();
reader.onloadend = function () {
    var fileName = file.name;
    $.post('/process_image', { data: reader.result, name: fileName });
};
reader.readAsDataURL(file);


问:
Build Mobile App for alexa?
Hi I have a custom skill running with alexa echo & is working fine. Now I need to build a mobile application (android native / Hybrid) that take input from my phone's mic, alexa processes this with my custom skill & return output that plays from my phone's speakers.

In short, I need an app doing all all echo is doing. Is it possible ? How ? And if yes, please provide me links that can be helpful. Any samples would be appreciated.

Thank you.

答:
Alexa does have an SDK using which you can build what you're looking for.
https://github.com/alexa/alexa-avs-sample-app/tree/master/samples/androidCompanionApp
This is the link to their companion app. </p>

<p>https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/content/avs-api-overview
This is their voice service API which states that you can access third party skills. </p>

Title: Build Mobile App for alexa?

Body:
Alexa does have an SDK using which you can build what you're looking for.
https://github.com/alexa/alexa-avs-sample-app/tree/master/samples/androidCompanionApp
This is the link to their companion app.

https://developer.amazon.com/public/solutions/alexa/alexa-voice-service/content/avs-api-overview
This is their voice service API which states that you can access third party skills.


问:
Sorting data using array
This is my components.ts.
I want to write a fuction that sorts array by counts and i will use the sorted array datas in html to create a chart.</p>

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html',
})
export class Dashboard {
  private data = [];
  constructor() {
    this.data = [{
      'maxTime': 30041,
      'minTime': 6453,
      'avgTime': 18949,
      'count': 4,
      'requestRouteTemplate': 'api/GetUserPostponesCountReport',
      'requestMethod': 'POST',
    },
  ...
  }
]
</code>```

答:
```<code>this.data.sort(function (a, b) {
  return a.count - b.count;
});
</code>```

Source: https://developer.mozilla.org/hu/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Or just an ES6 shortcut:

```<code>data.sort((a, b) => a.count - b.count );
</code>```

Because in one line you dont need {} also dont need return and also allowed the arrow function.

Title: Sorting data using array

Body:
This is my components.ts.
I want to write a fuction that sorts array by counts and i will use the sorted array datas in html to create a chart.

import { Component } from '@angular/core';
@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html',
})
export class Dashboard {
  private data = [];
  constructor() {
    this.data = [{
      'maxTime': 30041,
      'minTime': 6453,
      'avgTime': 18949,
      'count': 4,
      'requestRouteTemplate': 'api/GetUserPostponesCountReport',
      'requestMethod': 'POST',
    },
  ...
  }
]

Body:
this.data.sort(function (a, b) {
  return a.count - b.count;
});

Source: https://developer.mozilla.org/hu/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Or just an ES6 shortcut:

data.sort((a, b) => a.count - b.count );

Because in one line you dont need {} also dont need return and also allowed the arrow function.


问:
Why is my aspx designer file referencing user controls incorrectly?
I have the following user controls (for now, more will go in the same namespace)

```<code>Ortund.Project.UserControls.FooControl
Ortund.Project.UserControls.BarControl
</code>```

I've referenced these correctly in my web.config (I know this I have got these controls to work correctly on the page).

```<code><pages>
    <controls>
        <add tagPrefix="ortund" tagName="Foo" src="~/UserControls/FooControl.ascx" />
        <add tagPrefix="ortund" tagName="Bar" src="~/UserControls/BarControl.ascx" />
    </controls>
</pages>
</code>```

This allows me to use the controls in my markup as follows:

```<code><div>
    <ortund:Foo runat="server" ID="oFoo" />
    <ortund:Bar runat="server" ID="oBar" />
</div>
</code>```

At least, it would if the Designer file for the page correctly referenced them on the above-mentioned namespace.

Instead, what I find in my designer file is this:

```<code>    /// <summary>
    /// oFoo control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.UserControl oFoo;

    /// <summary>
    /// oBar control.
    /// </summary>
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.UserControl oBar;
</code>```

Now, I can go in and change it, but since the file is auto-generated, it tends to just change back again for no apparent reason. As a result, I'm not able to access any public fields I may have in the user control which is a major problem for functionality.

So why is my designer file so blatantly and so stupidly wrong then and how can I fix it?

答:
In my experience with UserControls misbehaving, it's usually because you've got something "weird" with the namespace of your controls, or there's an inheritance hierarchy that Visual Studio can't get its head around, or, you're doing something in a web.config that is below the application level (though this usually results in bits of the namespace being chopped off and the .designer.cs refusing to compile).

I've just created a "simple" reproduction of your case above and the designer gets the declaration right as:

```<code>protected global::Ortund.Project.UserControls.FooControl oFoo;
</code>```

One option you have is to act on the comment immediately above the declaration ("To modify move field declaration from designer file to code-behind file.") and move the declaration from the .designer.cs file into the .cs file. This may stop the designer regenerating an incorrect declaration, although the fact that it's already doing so may mean that there's something sufficiently wrong that it'll keep on doing it, despite your best efforts.

More information about your solution/project structure and the inheritance hierarchy (if any) for your UserControls and pages may help to narrow this down!

Body:
I have the following user controls (for now, more will go in the same namespace)

Ortund.Project.UserControls.FooControl
Ortund.Project.UserControls.BarControl

I've referenced these correctly in my web.config (I know this I have got these controls to work correctly on the page).

<pages>
    <controls>
        <add tagPrefix="ortund" tagName="Foo" src="~/UserControls/FooControl.ascx" />
        <add tagPrefix="ortund" tagName="Bar" src="~/UserControls/BarControl.ascx" />
    </controls>
</pages>

This allows me to use the controls in my markup as follows:

    <ortund:Foo runat="server" ID="oFoo" />
    <ortund:Bar runat="server" ID="oBar" />

At least, it would if the Designer file for the page correctly referenced them on the above-mentioned namespace.

Instead, what I find in my designer file is this:

    ///
    /// oFoo control.
    ///
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.UserControl oFoo;

    ///
    /// oBar control.
    ///
    /// <remarks>
    /// Auto-generated field.
    /// To modify move field declaration from designer file to code-behind file.
    /// </remarks>
    protected global::System.Web.UI.UserControl oBar;

Now, I can go in and change it, but since the file is auto-generated, it tends to just change back again for no apparent reason. As a result, I'm not able to access any public fields I may have in the user control which is a major problem for functionality.

So why is my designer file so blatantly and so stupidly wrong then and how can I fix it?

Body:
In my experience with UserControls misbehaving, it's usually because you've got something "weird" with the namespace of your controls, or there's an inheritance hierarchy that Visual Studio can't get its head around, or, you're doing something in a web.config that is below the application level (though this usually results in bits of the namespace being chopped off and the .designer.cs refusing to compile).

I've just created a "simple" reproduction of your case above and the designer gets the declaration right as:

protected global::Ortund.Project.UserControls.FooControl oFoo;

One option you have is to act on the comment immediately above the declaration ("To modify move field declaration from designer file to code-behind file.") and move the declaration from the .designer.cs file into the .cs file. This may stop the designer regenerating an incorrect declaration, although the fact that it's already doing so may mean that there's something sufficiently wrong that it'll keep on doing it, despite your best efforts.

More information about your solution/project structure and the inheritance hierarchy (if any) for your UserControls and pages may help to narrow this down!


问:
Save current time as a cookie in Javascript
I am trying to get the time a user goes on a page and save it as a cookie (in JavaScript) I'm able to get the current time but I can't seem to be able to save it as a cookie.

The reason why I'm doing this is because I'd like to know how long it took my class to go from the first page to the last page of my training site. I collect the first time stamp when they load the first page, and I collect the second time stamp when they load the finale page (their are 5 pages).
I'm not sure if there is a better way of doing this with Javascript?

Here is my code: (thanks in advance)

var d = new Date();
document.getElementById("test").innerHTML = d;
docCookies.setItem("time", "test");```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <p id="test"></p></code>```

答:
Use following code. This will add your current date in cookie.</p>

```<code>var d = new Date();
document.cookie="time="+d;
</code>```

Body:
Use following code. This will add your current date in cookie.

var d = new Date();
document.cookie="time="+d;


问:
Limit the scroll for UITableView
I have a TableViewController:

As you see I have my own custom bar at the top.
The UITable View is just a static one, and I add a view at the top of UITableView.

The thing is when I scroll the TableView to top-side it become like bellow image, and I don't want it. is there any easy code that I can limit the scroll for the tableView?

答:
I had the same problem and asked our UX-Designer, how it would be better to do. He said, that both strict solutions (prevent bouncing or allow it as it is) are bad. It's better to allow bouncing but only for some space

My solution was:

```<code>override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == self.tableView {
        if scrollView.contentOffset.y < -64 {
            scrollView.scrollRectToVisible(CGRect(origin: CGPoint(x: 0, y: -64), size: scrollView.frame.size), animated: false)
            scrollView.scrollRectToVisible(CGRect(origin: CGPoint.zero, size: scrollView.frame.size), animated: true)
        }
    }
}
</code>```

Where 64 was that "some space" for me. Code stops tableView at -64 from the top and brings it up with an animation.
Good luck!

Title: Limit the scroll for UITableView

Body:
I had the same problem and asked our UX-Designer, how it would be better to do. He said, that both strict solutions (prevent bouncing or allow it as it is) are bad. It's better to allow bouncing but only for some space

My solution was:

override func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if scrollView == self.tableView {
        if scrollView.contentOffset.y < -64 {
            scrollView.scrollRectToVisible(CGRect(origin: CGPoint(x: 0, y: -64), size: scrollView.frame.size), animated: false)
            scrollView.scrollRectToVisible(CGRect(origin: CGPoint.zero, size: scrollView.frame.size), animated: true)
        }
    }
}

Where 64 was that "some space" for me. Code stops tableView at -64 from the top and brings it up with an animation.
Good luck!


问:
How to implement IP filter on 2 billion IP addresses?
We have different projects and one of them is white label DSP solution .
Our client requested to enable the filtering of all incoming traffic by IP.
They gave us the list of addresses which contains 2.05 billion records and it should work in real-time.

These addresses can be compacted into 6 million ranges. We have only 10 milliseconds to conduct this check-up.

This task should be implemented using NodeJS.

Do you have any suggestion on how to get it done or which mechanism should be appropriate for this task?

答:
It must be easy to load already sorted IPs to that kind of structure. Just walk down through your billions and fill:

```<code>{
    100: {
        150: {
            200: [250, 251],
            205: [250]
        }
    },
    105: {
        110: {
            115: [120]
        },
        115: {
            150: [200]
        }
    }
}
</code>```

Then just check the key presence for each octet of an IP that must be filtered.

JavaScript optimizes integer-dictionaries and uses the binary search on them.

I don't know if there is unsigned byte in NodeJS, or you need tens of gigabytes of RAM.

OwnerDisplayName: Irina Kovalenko

Body:
It must be easy to load already sorted IPs to that kind of structure. Just walk down through your billions and fill:

{
    100: {
        150: {
            200: [250, 251],
            205: [250]
        }
    },
    105: {
        110: {
            115: [120]
        },
        115: {
            150: [200]
        }
    }
}

Then just check the key presence for each octet of an IP that must be filtered.

JavaScript optimizes integer-dictionaries and uses the binary search on them.

I don't know if there is unsigned byte in NodeJS, or you need tens of gigabytes of RAM.


问:
How can I save data from one DB to another DB using OSB?
I am new in OSB. I have a demo project. Where I need some modification.

I have a database in Oracle from where I fetch some data using db pooling. After than I run a loop and assign the specific field in a variable. I have also a business service where I save the data.

Now my question is how can I save those data that I have assigned in variable into another database?

As I am new in OSB so I am confused my question is perfect enough or not. Please help me in this regard..

答:
step 1 ) You need to configure the DB Adapter as suggested in above reply.
Step 2) Use replace to transform your data stored in your variable, so that it can be accepted as request by business service  of DB adapter.</p>


问:
Need to include a variable in a function of a query in Laravel
I have something like this:

```<code>$configurations = Configs:all();

foreach($configs as $config){

$documents = document::whereHas('user', function ($q) {
$q->where("portal_id", $config->id),})->get()

...
}
</code>```

This does not work because $config is not defined in the query function.

How do I put the $config->id object there?

答:
A closure encapsulates its scope, meaning that it has no access to the scope in which it is defined or executed. It is, however, possible to inherit variables from the parent scope (where the closure is defined) into the closure with the use keyword:</p>

```<code>$documents = document::whereHas('user', function ($q) use ($config) {
$q->where("portal_id", $config->id),})->get()

}
</code>```

Body:
I have something like this:

$configurations = Configs:all();

foreach($configs as $config){

$documents = document::whereHas('user', function ($q) {
$q->where("portal_id", $config->id),})->get()

...
}

This does not work because $config is not defined in the query function.

How do I put the $config->id object there?

Body:
A closure encapsulates its scope, meaning that it has no access to the scope in which it is defined or executed. It is, however, possible to inherit variables from the parent scope (where the closure is defined) into the closure with the use keyword:

$documents = document::whereHas('user', function ($q) use ($config) {
$q->where("portal_id", $config->id),})->get()

}


问:
Stat_function on ggplot doesn't work
I have a problem with ggplot, especially with stat_function.

I want to plot my distribution, then I want to calculate the Chi-square theoretical distribution and plot it on my actual plot.
Without ggplot, I made this with a simple lines()

```<code>res.lk <- apply (as.matrix(baf_matrix$res.fst), 2, FUN = function (x) baf_matrix$res.fst*4 / (mean(baf_matrix$res.fst)))

hist(res.lk, probability = T, breaks = 100,main = "LK distribution",
xlab ="LK")
x = c(0:as.integer(max(res.lk)))
lines(x,dchisq(x,df=4),lwd=3,col="orange")
</code>```

Now to make it with ggplot I do this:

Y = as.data.frame(res.lk)

ggplot(data = Y , aes( x = Lk )) + geom_histogram( binwidth=.1, color="black", fill="white" ) + stat_function( fun = dchisq(c(0:as.integer(max(res.lk))),df=4), lwd = 3, col = "orange")  + theme_bw()

And I get this error : Warning message:
Computation failed in stat_function():
'what' must be a function or character string

This is what my data looks like :
The Lk distribution

I'm trying to fix it but I didn't find how. Can somebody help me please?? Thank you a lot in advance.

答:
Note: it would really help if you included example data for us to work with.

The argument fun has to be a function. You're passing a vector. Also, because the distribution line only depends on a single value in the data, it'd be better to use annotate:

```<code>xseq <- seq(max(Y$res.lk))

ggplot(data = Y, aes(x = Lk)) +
  geom_histogram(binwidth = .1, color="black", fill="white") +
  annotate(
    geom = "line",
    x = xseq,
    y = dchisq(xseq, df = 4),
    width = 3,
    color = "orange"
    ) +
  theme_bw()
</code>```

Title: Stat_function on ggplot doesn't work

Body:
I have a problem with ggplot, especially with stat_function.

I want to plot my distribution, then I want to calculate the Chi-square theoretical distribution and plot it on my actual plot.
Without ggplot, I made this with a simple lines()

res.lk <- apply (as.matrix(baf_matrix$res.fst), 2, FUN = function (x) baf_matrix$res.fst*4 / (mean(baf_matrix$res.fst)))

hist(res.lk, probability = T, breaks = 100,main = "LK distribution",
xlab ="LK")
x = c(0:as.integer(max(res.lk)))
lines(x,dchisq(x,df=4),lwd=3,col="orange")

Now to make it with ggplot I do this:

Y = as.data.frame(res.lk)

ggplot(data = Y , aes( x = Lk )) + geom_histogram( binwidth=.1, color="black", fill="white" ) + stat_function( fun = dchisq(c(0:as.integer(max(res.lk))),df=4), lwd = 3, col = "orange")  + theme_bw()

And I get this error : Warning message:
Computation failed in stat_function():
'what' must be a function or character string

This is what my data looks like :
The Lk distribution

I'm trying to fix it but I didn't find how. Can somebody help me please?? Thank you a lot in advance.

Body:
Note: it would really help if you included example data for us to work with.

The argument fun has to be a function. You're passing a vector. Also, because the distribution line only depends on a single value in the data, it'd be better to use annotate:

xseq <- seq(max(Y$res.lk))

ggplot(data = Y, aes(x = Lk)) +
  geom_histogram(binwidth = .1, color="black", fill="white") +
  annotate(
    geom = "line",
    x = xseq,
    y = dchisq(xseq, df = 4),
    width = 3,
    color = "orange"
    ) +
  theme_bw()


问:
Unknown attribute type (Object) for attribute data
JSP Page error. How to solve the "Unknown attribute type (Object) for attribute data." ERROR.
and the error point to

">
Below is my JSP code.

```<code><%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="kendo" uri="http://www.kendoui.com/jsp/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link href="resources/styles/kendo.common.min.css" rel="stylesheet"
    type="text/css" />
<link href="resources/styles/kendo.default.min.css" rel="stylesheet"
    type="text/css" />

<script src="resources/js/jquery.min.js"></script>
<script src="resources/js/kendo.web.min.js"></script>

</head>
<body>
<%
    List<String> data = new ArrayList<String>();
    data.add("adaf");
    data.add("bdfa");
    data.add("cdasf");
%>

<div class="container">
<div class="row">
<kendo:dropDownList name="things">
    <kendo:dataSource data="<%=data %>">
    </kendo:dataSource>
</kendo:dropDownList>
</div>
</div>
</body>
</html>
</code>```

ERROR Message:

```<code>SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /index.jsp(32,1) Unknown attribute type (Object) for attribute data.
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:236)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:1199)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:846)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:865)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
    at org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1763)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:334)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:321)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)
</code>```

My Environment:
Tomcat 6.0
JDK1.7

答:
When you place a JSP expression (<%=data %>) in you JSP page, it should contain a string. In your case, the Kendo DataSource data attribute expects an array.

Try converting <%=data %> to a string in the form ["adaf", "bdfa", "cdasf"] using the following:

```<code>${fn:join(data, ', ')}
</code>```

Body:
JSP Page error. How to solve the "Unknown attribute type (Object) for attribute data." ERROR.
and the error point to

">
Below is my JSP code.

<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="kendo" uri="http://www.kendoui.com/jsp/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link href="resources/styles/kendo.common.min.css" rel="stylesheet"
    type="text/css" />
<link href="resources/styles/kendo.default.min.css" rel="stylesheet"
    type="text/css" />

<%
    List<String> data = new ArrayList<String>();
    data.add("adaf");
    data.add("bdfa");
    data.add("cdasf");
%>

<kendo:dropDownList name="things">
    <kendo:dataSource data="<%=data %>">
    </kendo:dataSource>
</kendo:dropDownList>

ERROR Message:

SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /index.jsp(32,1) Unknown attribute type (Object) for attribute data.
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:236)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.checkXmlAttributes(Validator.java:1199)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:846)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Validator$ValidateVisitor.visit(Validator.java:865)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
    at org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Validator.validateExDirectives(Validator.java:1763)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:334)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:321)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Unknown Source)

My Environment:
Tomcat 6.0
JDK1.7

Body:
When you place a JSP expression (<%=data %>) in you JSP page, it should contain a string. In your case, the Kendo DataSource data attribute expects an array.

Try converting <%=data %> to a string in the form ["adaf", "bdfa", "cdasf"] using the following:

${fn:join(data, ', ')}


问:
Unable to cast object of type 'HtmlAgilityPack.HtmlDocument' to type 'mshtml.IHTMLDocument2'
iam to Unable to cast object of type 'HtmlAgilityPack.HtmlDocument' to type 'mshtml.IHTMLDocument2' </p>

```<code>HTMLDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
</code>```

答: It is because HTMLDocument does not implement IHTMLDocument2 so there's no known path to perform the cast.

Body:
iam to Unable to cast object of type 'HtmlAgilityPack.HtmlDocument' to type 'mshtml.IHTMLDocument2'

HTMLDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;


答:
In order to cast type A to type B, one of following should be true

Type A should be inherited from type B, or it should implement type B if it's an interface. Implicit conversion will work in this case

Type B should be inherited from type A and variable which you are casting should hold an instance of type B.

There should be explicit operator defined in either type which performs conversion

If none is true, then you'll get a runtime exception. For types HtmlAgilityPack.HtmlDocument and mshtml.IHTMLDocument2 both conditions are not satisfied.

UPDATE: Seems like you have a typo - instead of declaring doc variable as HTMLDocument you have declared it as HtmlDocument. C# is a case-sensitive language.

Further reading: Casting and Type Conversions (C# Programming Guide)

Title: Unable to cast object of type 'HtmlAgilityPack.HtmlDocument' to type 'mshtml.IHTMLDocument2'


问:
access to Kendo pop up editor input text box
I have a Kendo grid which has a pop up editor,when I click on the edit,it pop ups an editor box which I can edit field,in the editor I have text boxes which is created dynamically,how can access them?because my code is correct but no reaction I get ,here are my fields and at the end is my code:</p>

```<code> columns: [
                                              { field: 'userName', title: 'userName', width: '100px'},
                                              { field: 'Password', title: 'Password', width: '80px' },

                                              { command: ["edit"], title: " ", width: "100px" }],
                        editable: "popup",

 $('[name="userName"]').click(function () {

        alert("you can not edit username");
    });
</code>```

答:
You can also hide your element to prevent accessing:</p>

```<code>edit: function(e) {
e.container.find("input[name=userName]").parent().hide(); }
</code>```

Body:
I have a Kendo grid which has a pop up editor,when I click on the edit,it pop ups an editor box which I can edit field,in the editor I have text boxes which is created dynamically,how can access them?because my code is correct but no reaction I get ,here are my fields and at the end is my code:

 columns: [
                                              { field: 'userName', title: 'userName', width: '100px'},
                                              { field: 'Password', title: 'Password', width: '80px' },

                                              { command: ["edit"], title: " ", width: "100px" }],
                        editable: "popup",

 $('[name="userName"]').click(function () {

        alert("you can not edit username");
    });

Body:
You can also hide your element to prevent accessing:

edit: function(e) {
e.container.find("input[name=userName]").parent().hide(); }


问:
WPF AutoCompleteBox Style DataTemplate Bind ValueMemberPath To Content
So I have an

```<code><controls:AutoCompleteBox ItemsSource="{Binding Nationalities}" SelectedItem="{Binding IDIssueCountry, Mode=TwoWay}" ValueMemberPath="NationalityName"/>
</code>```

And a style for itemtemplate that i want its content bound to ValueMemberPath's value:

```<code><Setter Property="ItemTemplate">
    <Setter.Value>
        <DataTemplate>
            <Label Content="{What Binding to put here to get ValueMemberPath's value}"/>
        </DataTemplate>
    </Setter.Value>
</code>```

Thanks in advance

P.S: TemplateBinding does not find ValueMemberPath..

答:
What about this?

```<code><Label Content="{Binding NationalityName}"/>
</code>```

Should work assuming that NationalityName is a property of an item in the Nationalities collection.

Note that you cannot bind the Content property of the Label to the property whose name is specified by the ValueMemberPath if that's what you are trying to do.

The value of the ValueMemberPath is used internally by the control to get the value of the underlying data object using reflection.

Body:
So I have an

<controls:AutoCompleteBox ItemsSource="{Binding Nationalities}" SelectedItem="{Binding IDIssueCountry, Mode=TwoWay}" ValueMemberPath="NationalityName"/>

And a style for itemtemplate that i want its content bound to ValueMemberPath's value:

<Setter Property="ItemTemplate">
    <Setter.Value>
        <DataTemplate>

        </DataTemplate>
    </Setter.Value>

Thanks in advance

P.S: TemplateBinding does not find ValueMemberPath..

Body:
What about this?

<Label Content="{Binding NationalityName}"/>

Should work assuming that NationalityName is a property of an item in the Nationalities collection.

Note that you cannot bind the Content property of the Label to the property whose name is specified by the ValueMemberPath if that's what you are trying to do.

The value of the ValueMemberPath is used internally by the control to get the value of the underlying data object using reflection.


问:
readable code lines R
Is there a shortcut to add a new line into the R (RStudio) code?

I would like to avoid something like gapminder%>%filter(continent=="Asia")%>%group_by(year)%>%summarise(mean_pop=mean(pop))%>%ggplot(aes(x=year,y=mean_pop))+geom_point()+geom_line()+theme_bw()

by using

```<code>gapminder %>%
   filter(continent == "Asia") %>%
   group_by(year) %>%
   summarise(mean_pop = mean(pop)) %>%
     ggplot(aes(x = year, y = mean_pop)) +
     geom_point() +
     geom_line() +
     theme_bw()
</code>```

but without holding the space bar all the time..  and I googled now nearly half an hour and just didn't find a shortcut. Can't believe it?!
So how all are doing this?

答:
In your case try to use ; and not %>%.

Example:

```<code>gapminder;filter(continent=="Asia");group_by(year);summarise(mean_pop=mean(pop))
</code>```

Press CTRL + SHIFT + A or select all code and go to Code-> Reformat code

Result:

```<code>gapminder
filter(continent == "Asia")
group_by(year)
summarise(mean_pop = mean(pop))
</code>```

Title: readable code lines R

Body:
Is there a shortcut to add a new line into the R (RStudio) code?

I would like to avoid something like gapminder%>%filter(continent=="Asia")%>%group_by(year)%>%summarise(mean_pop=mean(pop))%>%ggplot(aes(x=year,y=mean_pop))+geom_point()+geom_line()+theme_bw()

by using

gapminder %>%
   filter(continent == "Asia") %>%
   group_by(year) %>%
   summarise(mean_pop = mean(pop)) %>%
     ggplot(aes(x = year, y = mean_pop)) +
     geom_point() +
     geom_line() +
     theme_bw()

but without holding the space bar all the time..  and I googled now nearly half an hour and just didn't find a shortcut. Can't believe it?!
So how all are doing this?

Body:
In your case try to use ; and not %>%.

Example:

gapminder;filter(continent=="Asia");group_by(year);summarise(mean_pop=mean(pop))

Press CTRL + SHIFT + A or select all code and go to Code-> Reformat code

Result:

gapminder
filter(continent == "Asia")
group_by(year)
summarise(mean_pop = mean(pop))


问:
Unable to extract in GDB the values where FPE is occuring
I took the advice that is given in the comments of this question Gfortran does not tell me what sort of FPE it is i.e. start up GDB , set a breakpoint to that line and inspect the values of the operation. At the outset my program is based on Fortran 77 code(I plan to migrate it to F90 after running this "test case" an idealistic CFD data test) and uses NetCDF shared libraries on Ubuntu 16.04 LTS. I use the gfortran 4.8.5 compiler(can upgrade to 5.x if required).

This is how the program is compiled

```<code>gfortran -Wall -O0 -c -g -fbacktrace -ffpe-trap=invalid,denormal,zero,overflow,underflow ${tool}.f ${ncdf_incs}
</code>```

Now I started gdb in the directory where the program is located and then I typed

```<code>break inv_cart.f:1221
</code>```

which is where the FPE is occurring(a divide by zero error). When I do this I get this message -

```<code>  Make breakpoint based on future shared library load (y/n) ?
</code>```

So I searched SO for this problem and I got this previously Q/A - How to set breakpoints with shared libraries  and this is what I did

```<code>set breakpoint pending on
break inv_cart.f:1221
</code>```

UPDATE

I had an oversight. After I run break  I get this error message

```<code>No symbol table is loaded. Use the "file" command
Breakpoint 1 (inv_cart.f:1221) is pending.
</code>```

END UPDATE

After I do this I get the same error I got when I ran inv_cart within gdb or  as  stand alone.

```<code>Program received signal SIGFPE - arithmetic exception
</code>```

followed by a memory address and  couple of question marks followed by ().
So I quit gdb and then it tells me that there is a a debugging session that is still active.

So my question still remains - How do I obtain the values where the FPE is occurring ?

答:
This is a straightforward problem after the update has been noticed by me.

I looked up this question - gdb no symbol table is loaded  and I went ahead and did this

```<code>file inv_cart
</code>```

and finally the symbol table was loaded and to my joy I ran the program again via gdb and was able to print the value of the piece of code where the FPE was occurring.

Body:
I took the advice that is given in the comments of this question Gfortran does not tell me what sort of FPE it is i.e. start up GDB , set a breakpoint to that line and inspect the values of the operation. At the outset my program is based on Fortran 77 code(I plan to migrate it to F90 after running this "test case" an idealistic CFD data test) and uses NetCDF shared libraries on Ubuntu 16.04 LTS. I use the gfortran 4.8.5 compiler(can upgrade to 5.x if required).

This is how the program is compiled

gfortran -Wall -O0 -c -g -fbacktrace -ffpe-trap=invalid,denormal,zero,overflow,underflow ${tool}.f ${ncdf_incs}

Now I started gdb in the directory where the program is located and then I typed

break inv_cart.f:1221

which is where the FPE is occurring(a divide by zero error). When I do this I get this message -

  Make breakpoint based on future shared library load (y/n) ?

So I searched SO for this problem and I got this previously Q/A - How to set breakpoints with shared libraries  and this is what I did

set breakpoint pending on
break inv_cart.f:1221

UPDATE

I had an oversight. After I run break  I get this error message

No symbol table is loaded. Use the "file" command
Breakpoint 1 (inv_cart.f:1221) is pending.

END UPDATE

After I do this I get the same error I got when I ran inv_cart within gdb or  as  stand alone.

Program received signal SIGFPE - arithmetic exception

followed by a memory address and  couple of question marks followed by ().
So I quit gdb and then it tells me that there is a a debugging session that is still active.

So my question still remains - How do I obtain the values where the FPE is occurring ?

Body:
This is a straightforward problem after the update has been noticed by me.

I looked up this question - gdb no symbol table is loaded  and I went ahead and did this

file inv_cart

and finally the symbol table was loaded and to my joy I ran the program again via gdb and was able to print the value of the piece of code where the FPE was occurring.


问:
Can I populate Session Variable with a query result?
Is populating PHP session variables with a query result possible - if so,

what is the proper syntax?

My code:-

```<code>session_start();
while($rows=mysql_fetch_array($result)){
   $_SESSION['userid'] = $rows['id'];
   $_SESSION['firstname'] = $rows['firstname'];
   $_SESSION['lastname'] = $rows['lastname'];
}
</code>```

I tried this code above with no positive result.

答:
Yes you can store the result in session

Try this

```<code>session_start();
$data='';
while($rows=mysql_fetch_array($result)){
    $user['userid'] = $rows['id'];
    $user['firstname'] = $rows['firstname'];
    $user['lastname'] = $rows['lastname'];
    $data[]=$user;

}
$_SESSION['Data'] = $data;
</code>```

Body:
Is populating PHP session variables with a query result possible - if so,

what is the proper syntax?

My code:-

session_start();
while($rows=mysql_fetch_array($result)){
   $_SESSION['userid'] = $rows['id'];
   $_SESSION['firstname'] = $rows['firstname'];
   $_SESSION['lastname'] = $rows['lastname'];
}

I tried this code above with no positive result.

Body:
Yes you can store the result in session

Try this

session_start();
$data='';
while($rows=mysql_fetch_array($result)){
    $user['userid'] = $rows['id'];
    $user['firstname'] = $rows['firstname'];
    $user['lastname'] = $rows['lastname'];
    $data[]=$user;

}
$_SESSION['Data'] = $data;


问:
Creating a new variable in a data frame and changing its values in one step
I have a column which is part of a data frame, df. It is full of integers. Let's say it is the number of houses sold in a day by a reality compant. Let's call it df$houses. I want to make a second column called df$quant where the number of houses is categorized, with 0 being 0-2 houses sold in a day, 1 being 3-5 houses, 2 being 6-9 houses and 3 being more than 10 houses? I could do this in two steps.

1) Create the new column df$quant from df$houses:

```<code>df$quant <- df$houses
</code>```

2) Change the values of df$quant:

```<code>df$quant[which(df$quant <= 2)] <- 0
</code>```

etc.

I would like to do this in one step though, making the new variable and filling it with the proper values. Mostly, so I don't have to worry about getting the order of the lines of code in the second step right. It would be more robust.

Could this be done with an if statement?

Thanks a lot.

答:
I would do something like this: (using cut)

```<code>x <- 1:11
df <- data.frame(x)

myFunction <- function(x) as.integer(cut(x, c(-1, 2, 5, 9, max(x)))) - 1
df$new <- myFunction(df$x)
df
    x new
1   1   0
2   2   0
3   3   1
4   4   1
5   5   1
6   6   2
7   7   2
8   8   2
9   9   2
10 10   3
11 11   3
</code>```

Body:
I have a column which is part of a data frame, df. It is full of integers. Let's say it is the number of houses sold in a day by a reality compant. Let's call it df$houses. I want to make a second column called df$quant where the number of houses is categorized, with 0 being 0-2 houses sold in a day, 1 being 3-5 houses, 2 being 6-9 houses and 3 being more than 10 houses? I could do this in two steps.

1) Create the new column df$quant from df$houses:

df$quant <- df$houses

2) Change the values of df$quant:

df$quant[which(df$quant <= 2)] <- 0

etc.

I would like to do this in one step though, making the new variable and filling it with the proper values. Mostly, so I don't have to worry about getting the order of the lines of code in the second step right. It would be more robust.

Could this be done with an if statement?

Thanks a lot.

Body:
I would do something like this: (using cut)

x <- 1:11
df <- data.frame(x)

myFunction <- function(x) as.integer(cut(x, c(-1, 2, 5, 9, max(x)))) - 1
df$new <- myFunction(df$x)
df
    x new
1   1   0
2   2   0
3   3   1
4   4   1
5   5   1
6   6   2
7   7   2
8   8   2
9   9   2
10 10   3
11 11   3


问:
SSIS Derived Column condition to replace null values based on a specific date
I am working on a SSIS Package that will populate a SharePoint 2013 list with data from other SP lists.

I have created a Derived Column in the package, which is intended to replace null based on dates that are greater than or equal to a specific date in the data list. However, I am having trouble with the expression. Below is a condition and expression example that I am have trouble with.

```<code>REPLACENULL(ColumnName,"mm/dd/yyyy" > = GETDATE())
</code>```

Any assistance to point out what I am doing wrong is appreciated.

答:
Use this expression:

```<code>((DT_DATE)"9-1-2016") >=  (DT_DATE)ColumnName ? NULL((DT_WSTR, 50)) : ColumnName
</code>```

Notice: REPLACENULL is not useful for you here. What REPLACENULL does is that it:

Returns the value of second expression parameter if the value of first expression parameter is NULL". (See here)

You don't want to replace NULL, you want NULL!

Body:
I am working on a SSIS Package that will populate a SharePoint 2013 list with data from other SP lists.

I have created a Derived Column in the package, which is intended to replace null based on dates that are greater than or equal to a specific date in the data list. However, I am having trouble with the expression. Below is a condition and expression example that I am have trouble with.

REPLACENULL(ColumnName,"mm/dd/yyyy" > = GETDATE())

Any assistance to point out what I am doing wrong is appreciated.

Body:
Use this expression:

((DT_DATE)"9-1-2016") >=  (DT_DATE)ColumnName ? NULL((DT_WSTR, 50)) : ColumnName

Notice: REPLACENULL is not useful for you here. What REPLACENULL does is that it:

Returns the value of second expression parameter if the value of first expression parameter is NULL". (See here)

You don't want to replace NULL, you want NULL!


问:
How do you keep relative positioning from poping out of the box?
I am trying to use relative positioning for other reasons, and data in my div is popuping out of the container div in ie7.

Can you guys give me some idea what is going?

Also, I can just remove position: relative;.   That is need for my line highlighting code.

Thanks,
Grae

Here is the code:

```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >
<html>
<head></p>

<p></head>
<body>
    <div style="overflow:auto; height:350px; border: 1px solid #00ff00">
        <table>
            <tr><br>
                <td>
                    <div style="position:relative;">
                        <PRE>
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
                        </PRE>
                    </div>
                </td>
            </tr>
        </table>
    </div>
</body>
```

答:
I am not sure if the following is a valid solution for you, but it worked for me.

You can add position:relative to your first div. (The one with the overflow:auto)

P.S. removing the width="100%" attribute from the table, or just reducing the width, will remove the horizontal scroll.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use relative positioning for other reasons, and data in my div is popuping out of the container div in ie7.

Can you guys give me some idea what is going?

Also, I can just remove position: relative;.   That is need for my line highlighting code.

Thanks,
Grae

Here is the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" >

Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line
Test Line


问:
Insert HTML element after a specific div class name with Typescript & Angular
What I want to do is to insert a component inside a div, after a specific div with a specific class name. How do I do this in typescript?

```<code><div class ="{{order.orderId}}">
    <div class="enter-here"></div>
<other html elements here>
</div>
</code>```

And TypeScript:

```<code> insertDiv(){
    insert.component.after.className.enter-here;
 }
</code>```

答:
Inserting new element is not the angular way of doing it, when using angular DOM manipulation should be avoided as much as possible. In your question you haven't mentioned what will be the contents of .enter-here, so I am assuming it is just plain text:

In your html:

```<code><div class ="{{order.orderId}}">
    <div *ngIf="showEnterHereDiv" class="enter-here">
      some text or list which should be visible after showDiv is called
    </div>
    <other html elements here>
</div>
</code>```

In your typescript:

```<code>// hidden by default
showEnterHereDiv: boolean = false;

...

showDiv() {
    // call this method to show the div
    this.showEnterHereDiv = true;
}

hideDiv() {
    this.showEnterHereDiv = false;
}
</code>```

Body:
What I want to do is to insert a component inside a div, after a specific div with a specific class name. How do I do this in typescript?

<other html elements here>

And TypeScript:

 insertDiv(){
    insert.component.after.className.enter-here;
 }

Body:
Inserting new element is not the angular way of doing it, when using angular DOM manipulation should be avoided as much as possible. In your question you haven't mentioned what will be the contents of .enter-here, so I am assuming it is just plain text:

In your html:

<div class ="{{order.orderId}}">
    <div *ngIf="showEnterHereDiv" class="enter-here">
      some text or list which should be visible after showDiv is called
    </div>
    <other html elements here>
</div>

In your typescript:

// hidden by default
showEnterHereDiv: boolean = false;

...

showDiv() {
    // call this method to show the div
    this.showEnterHereDiv = true;
}

hideDiv() {
    this.showEnterHereDiv = false;
}


问:
make .htaccess to prevent navigating to directories
I have this .htaccess

```<code>DirectorySlash On
RewriteEngine On

RewriteRule /?\.htaccess$ - [F,L]

# Remove trailing slash
RewriteRule ^(.*)/$ /project/$1 [R,L]

# Map every link to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/project/index.php.*$
RewriteRule ^(.*)$ /project/index.php?___MYROUTER=$1 [QSA,END]
</code>```

but when I'm navigating to one of directories next to my .htaccess file like css folder in browser, with this address:

http://localhost/project/css

then my address will be changes to:

http://localhost/project/css?___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css

and in firefox this is the result:

The page isn’t redirecting properly

Firefox has detected that the server is redirecting the request for
  this address in a way that will never complete.

```<code>This problem can sometimes be caused by disabling or refusing to accept cookies.
</code>```

but other addresses those are not pointing to an existing directory, will be ok like:

http://localhost/project/mycontroller

this address is ok and will not be changed to anything else

What is the problem with my .htaccess?

this is my log file

答:
That is because Apache is adding a trailing slash in front of directories after mod_dir module has completed execution.

You can add a trailing slash in front of directories yourself using a separate rule.

```<code>DirectorySlash On
RewriteEngine On

RewriteRule /?\.htaccess$ - [F,L]

# Remove trailing slash for non directories
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /project/$1 [R,L]

# add a trailing slash to directories
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]

# Map every link to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/project/index\.php [NC]
RewriteRule ^(.*)$ project/index.php?___MYROUTER=$1 [QSA,END]
</code>```

Body:
I have this .htaccess

DirectorySlash On
RewriteEngine On

RewriteRule /?\.htaccess$ - [F,L]

# Remove trailing slash
RewriteRule ^(.*)/$ /project/$1 [R,L]

# Map every link to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/project/index.php.*$
RewriteRule ^(.*)$ /project/index.php?___MYROUTER=$1 [QSA,END]

but when I'm navigating to one of directories next to my .htaccess file like css folder in browser, with this address:

http://localhost/project/css

then my address will be changes to:

http://localhost/project/css?___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css&___MYROUTER=css

and in firefox this is the result:

The page isn’t redirecting properly

Firefox has detected that the server is redirecting the request for
  this address in a way that will never complete.

This problem can sometimes be caused by disabling or refusing to accept cookies.

but other addresses those are not pointing to an existing directory, will be ok like:

http://localhost/project/mycontroller

this address is ok and will not be changed to anything else

What is the problem with my .htaccess?

this is my log file

Body:
That is because Apache is adding a trailing slash in front of directories after mod_dir module has completed execution.

You can add a trailing slash in front of directories yourself using a separate rule.

DirectorySlash On
RewriteEngine On

RewriteRule /?\.htaccess$ - [F,L]

# Remove trailing slash for non directories
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /project/$1 [R,L]

# add a trailing slash to directories
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R=301,NE]

# Map every link to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/project/index\.php [NC]
RewriteRule ^(.*)$ project/index.php?___MYROUTER=$1 [QSA,END]


问:
VBA: How to open most recent two excel files in the folder
I have trying to open the most recent two excel file in the folder so far i did open the latest file in folder but i have to open 2nd latest file in folder. refer below code. please suggest how to open 2nd most recent file?</p>

```<code>Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1 As Workbook
Dim wb2 As Workbook
  FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)

        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

                Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)

End Sub
</code>```

答:
Here's another way to tackle the problem.  Create a sorted list and then process the first 2 files:</p>

```<code>Sub Lastest2Files()
   Dim rs As ADODB.Recordset
   Dim fs As FileSystemObject
   Dim Folder As Folder
   Dim File As File

   'create a recordset to store file info
   Set rs = New ADODB.Recordset
   rs.fields.Append "FileName", adVarChar, 100
   rs.fields.Append "Modified", adDate
   rs.Open

   'build the list of files and sort
   Set fs = New FileSystemObject
   Set Folder = fs.GetFolder("C:\aatemp")

   For Each File In Folder.Files
      rs.AddNew
      rs("FileName") = File.Path
      rs("Modified") = File.DateLastModified
   Next

   rs.Sort = "Modified DESC"

   'process the first 2 files
   rs.MoveFirst
   Set wb2 = Workbooks.Open(rs.fields("FileName").value)
   rs.MoveNext
   Set wb2 = Workbooks.Open(rs.fields("FileName").value)
End Sub
</code>```

Body:
I have trying to open the most recent two excel file in the folder so far i did open the latest file in folder but i have to open 2nd latest file in folder. refer below code. please suggest how to open 2nd most recent file?

Sub findingdiff()
Dim FileSys, objFile, myFolder, c As Object
Dim wb1 As Workbook
Dim wb2 As Workbook
  FolderName = ("C:\Users\ashokkumar.d\Desktop\Test\do\")
                Set FileSys = CreateObject("Scripting.FileSystemObject")
                Set myFolder = FileSys.GetFolder(FolderName)

        dteFile = DateSerial(1900, 1, 1)
        For Each objFile In myFolder.Files
            If InStr(1, objFile.Name, ".xls") > 0 Then
                If objFile.DateLastModified > dteFile Then
                    dteFile = objFile.DateLastModified
                    strFilename = objFile.Name
                End If
            End If
        Next objFile
'opening of latest file in the folder

                Set wb2 = Workbooks.Open(FolderName & Application.PathSeparator & strFilename)

End Sub

Body:
Here's another way to tackle the problem.  Create a sorted list and then process the first 2 files:

Sub Lastest2Files()
   Dim rs As ADODB.Recordset
   Dim fs As FileSystemObject
   Dim Folder As Folder
   Dim File As File

   'create a recordset to store file info
   Set rs = New ADODB.Recordset
   rs.fields.Append "FileName", adVarChar, 100
   rs.fields.Append "Modified", adDate
   rs.Open

   'build the list of files and sort
   Set fs = New FileSystemObject
   Set Folder = fs.GetFolder("C:\aatemp")

   For Each File In Folder.Files
      rs.AddNew
      rs("FileName") = File.Path
      rs("Modified") = File.DateLastModified
   Next

   rs.Sort = "Modified DESC"

   'process the first 2 files
   rs.MoveFirst
   Set wb2 = Workbooks.Open(rs.fields("FileName").value)
   rs.MoveNext
   Set wb2 = Workbooks.Open(rs.fields("FileName").value)
End Sub


问:
Rails3 Beta4 Devise Delayed_job configuration
I want to use delayed_job to send email in backend, this is
/config/initializers/setup_mail.rb

```<code>ActionMailer::Base.smtp_settings = {
    :address              => "smtp.gmail.com",
    :port                 => 587,
    :domain               => DOMAIN,
    :user_name            => USERNAME,
    :password             => PASSWORD,
    :authentication       => "plain",
    :enable_starttls_auto => true
}
</code>```

so I want to know how to configure the delayed_job to send mail in backend.Thank you.

答:
you should use action mailer tutorial first http://edgeguides.rubyonrails.org/action_mailer_basics.html then just mark your mail for performing in delayed_job:

```<code>class UserMailer < ActionMailer::Base
  default :from => "notifications@example.com"

  def welcome_email(user)
    @user = user
    @url  = "http://example.com/login"
    mail(:to => user.email,
         :subject => "Welcome to My Awesome Site")
  end

  handle_asynchronously :welcome_email
end
</code>```

You can also call handle asynchronously in config:

```<code>UserMailer.handle_asynchronously :welcome_email
</code>```

Body:
I want to use delayed_job to send email in backend, this is
/config/initializers/setup_mail.rb

ActionMailer::Base.smtp_settings = {
    :address              => "smtp.gmail.com",
    :port                 => 587,
    :domain               => DOMAIN,
    :user_name            => USERNAME,
    :password             => PASSWORD,
    :authentication       => "plain",
    :enable_starttls_auto => true
}

so I want to know how to configure the delayed_job to send mail in backend.Thank you.

Body:
you should use action mailer tutorial first http://edgeguides.rubyonrails.org/action_mailer_basics.html then just mark your mail for performing in delayed_job:

class UserMailer < ActionMailer::Base
  default :from => "notifications@example.com"

  def welcome_email(user)
    @user = user
    @url  = "http://example.com/login"
    mail(:to => user.email,
         :subject => "Welcome to My Awesome Site")
  end

  handle_asynchronously :welcome_email
end

You can also call handle asynchronously in config:

UserMailer.handle_asynchronously :welcome_email


问:
Get variable value from another class
I want to save some variables for future reference so I declared a class Container.cs

```<code>public class Container
{
    public static String verifierCode;
}
</code>```

and then I have my HomeController.cs where I update the Container's variables values:

```<code>public class HomeController : Controller
{
    public ActionResult ValidateTwitterAuth()
    {
        Container.verifierCode = Request.Query.ElementAt(2).Value;
        //do some stuff
    }
    public String sendTweet(String NewTweet)
    {
        var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(Container.verifierCode, Container.authorizationId);
        var user = Tweetinvi.User.GetAuthenticatedUser(userCreds);
        user.PublishTweet(NewTweet);
        return "sent!";
    }
}
</code>```

It gets updated in the ValidateTwitterAuth with the specific values but when the sendTweet method is called the Container.verifierCode is null.
I obviously tried to debug it but if I add the variable to quickwatch i get that

error CS0103: The name 'Container' does not exist in current context

Also, both the class and the container are in the same namespace.
Any idea/tip why this is happening? I am just trying to declare a global variable which I can access from other classes/controllers.

I apologise if this may sound like a beginner question but I'm just starting to get my hands on asp.net

EDIT: From the answers, my way of handling with the problem was wrong. Therefore I installed the Microsoft.AspNetCore.Session NuGet Package and used it like this:

```<code> HttpContext.Session.SetString("verifierCode", Request.Query.ElementAt(2).Value);
 HttpContext.Session.SetString("authorizationId", Request.Query.ElementAt(0).Value);
</code>```

and now it works. Thank you all for the answers!

答:
You can store this data into session instead of class.as per below example

```<code>public class HomeController : Controller
    {
        public ActionResult ValidateTwitterAuth()
        {
            Session["verifierCode"] = Request.Query.ElementAt(2).Value;
            //do some stuff
        }
        public String sendTweet(String NewTweet)
        {
            var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(Session["verifierCode"], Container.authorizationId);
            var user = Tweetinvi.User.GetAuthenticatedUser(userCreds);
            user.PublishTweet(NewTweet);
            return "sent!";
        }
    }
</code>```

i have just change only verify code

Title: Get variable value from another class

Body:
I want to save some variables for future reference so I declared a class Container.cs

public class Container
{
    public static String verifierCode;
}

and then I have my HomeController.cs where I update the Container's variables values:

public class HomeController : Controller
{
    public ActionResult ValidateTwitterAuth()
    {
        Container.verifierCode = Request.Query.ElementAt(2).Value;
        //do some stuff
    }
    public String sendTweet(String NewTweet)
    {
        var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(Container.verifierCode, Container.authorizationId);
        var user = Tweetinvi.User.GetAuthenticatedUser(userCreds);
        user.PublishTweet(NewTweet);
        return "sent!";
    }
}

It gets updated in the ValidateTwitterAuth with the specific values but when the sendTweet method is called the Container.verifierCode is null.
I obviously tried to debug it but if I add the variable to quickwatch i get that

error CS0103: The name 'Container' does not exist in current context

Also, both the class and the container are in the same namespace.
Any idea/tip why this is happening? I am just trying to declare a global variable which I can access from other classes/controllers.

I apologise if this may sound like a beginner question but I'm just starting to get my hands on asp.net

EDIT: From the answers, my way of handling with the problem was wrong. Therefore I installed the Microsoft.AspNetCore.Session NuGet Package and used it like this:

 HttpContext.Session.SetString("verifierCode", Request.Query.ElementAt(2).Value);
 HttpContext.Session.SetString("authorizationId", Request.Query.ElementAt(0).Value);

and now it works. Thank you all for the answers!

Body:
You can store this data into session instead of class.as per below example

public class HomeController : Controller
    {
        public ActionResult ValidateTwitterAuth()
        {
            Session["verifierCode"] = Request.Query.ElementAt(2).Value;
            //do some stuff
        }
        public String sendTweet(String NewTweet)
        {
            var userCreds = AuthFlow.CreateCredentialsFromVerifierCode(Session["verifierCode"], Container.authorizationId);
            var user = Tweetinvi.User.GetAuthenticatedUser(userCreds);
            user.PublishTweet(NewTweet);
            return "sent!";
        }
    }

i have just change only verify code


问:
Cannot have different system properties values for different tasks
I am trying to create 2 tasks to execute the sonarcube task. I want to be able to specify different properties depending on the task

```<code>   task sonarqubePullRequest(type: Test){

        System.setProperty( "sonar.projectName", "sonarqubePullRequest")
        System.setProperty("sonar.projectKey", "sonarqubePullRequest")
        System.setProperty("sonar.projectVersion", serviceVersion)
        System.setProperty("sonar.jacoco.reportPath",
        "${project.buildDir}/jacoco/test.exec")

        tasks.sonarqube.execute()
    }

task sonarqubeFullScan(type: Test){
    System.setProperty("sonar.projectName", "sonarqubeFullScan")
    System.setProperty("sonar.projectKey", "sonarqubeFullScan")
    System.setProperty("sonar.projectVersion", serviceVersion)
    System.setProperty("sonar.jacoco.reportPath",
    "${project.buildDir}/jacoco/test.exec")
    tasks.sonarqube.execute()
}
</code>```

The tasks work but there seems to be an issue with the properties I am setting

if I run the first task which is sonarqubePullRequest then everything is fine, but if run sonarqubeFullScan then if uses the values specified in the sonarqubePullRequest. so the project name is set sonarqubePullRequest

it is as if those properties are set at run time and cannot be updated. I feel like I am missing something obvious any suggestions greatly received.

答:
First of all: NEVER use execute() on tasks. The method is not part of the public Gradle API and therefor, its behaviour can change or be undefined. Gradle will execute the tasks on its own, either because you specified them (command line or settings.gradle) or as task dependencies.

The reason, why your code does not work, is the difference between the configuration phase and the execution phase. In the configuration phase, all the (configuration) code in your task closures is executed, but not the tasks. So, you'll always overwrite the system properties. Only (internal) task actions, doFirst and doLast closures are executed in the execution phase. Please note, that every task is only executed ONCE in a build, so your approach to parametrize a task twice will never work.

Also, I do not understand why you are using system properties to configure your sonarqube task. You can simply configure the task directly via:

```<code>sonarqube {
    properties {
        property 'sonar.projectName', 'sonarqubePullRequest'
        // ...
    }
}
</code>```

Now you can configure the sonarqube task. To distinguish between your two cases, you can add a condition for different property values. The next example makes use of a project property as condition:

```<code>sonarqube {
    properties {
        // Same value for both cases
        property 'sonar.projectVersion', serviceVersion
        // Value based on condition
        if (project.findProperty('fullScan') {
            property 'sonar.projectName', 'sonarqubeFullScan'
        } else {
            property 'sonar.projectName', 'sonarqubePullRequest'
        }
    }
}
</code>```

Alternatively, you can add another task of the type SonarQubeTask. This way, you could parametrize both tasks differently and call them (via command line or dependency) whenever you need them:

```<code>sonarqube {
    // Generated by the plugin, parametrize like described above
}

task sonarqubeFull(type: org.sonarqube.gradle.SonarQubeTask) {
    // Generated by your build script, parametrize in the same way
}
</code>```

Body:
I am trying to create 2 tasks to execute the sonarcube task. I want to be able to specify different properties depending on the task

   task sonarqubePullRequest(type: Test){

        System.setProperty( "sonar.projectName", "sonarqubePullRequest")
        System.setProperty("sonar.projectKey", "sonarqubePullRequest")
        System.setProperty("sonar.projectVersion", serviceVersion)
        System.setProperty("sonar.jacoco.reportPath",
        "${project.buildDir}/jacoco/test.exec")

        tasks.sonarqube.execute()
    }

task sonarqubeFullScan(type: Test){
    System.setProperty("sonar.projectName", "sonarqubeFullScan")
    System.setProperty("sonar.projectKey", "sonarqubeFullScan")
    System.setProperty("sonar.projectVersion", serviceVersion)
    System.setProperty("sonar.jacoco.reportPath",
    "${project.buildDir}/jacoco/test.exec")
    tasks.sonarqube.execute()
}

The tasks work but there seems to be an issue with the properties I am setting

if I run the first task which is sonarqubePullRequest then everything is fine, but if run sonarqubeFullScan then if uses the values specified in the sonarqubePullRequest. so the project name is set sonarqubePullRequest

it is as if those properties are set at run time and cannot be updated. I feel like I am missing something obvious any suggestions greatly received.

Body:
First of all: NEVER use execute() on tasks. The method is not part of the public Gradle API and therefor, its behaviour can change or be undefined. Gradle will execute the tasks on its own, either because you specified them (command line or settings.gradle) or as task dependencies.

The reason, why your code does not work, is the difference between the configuration phase and the execution phase. In the configuration phase, all the (configuration) code in your task closures is executed, but not the tasks. So, you'll always overwrite the system properties. Only (internal) task actions, doFirst and doLast closures are executed in the execution phase. Please note, that every task is only executed ONCE in a build, so your approach to parametrize a task twice will never work.

Also, I do not understand why you are using system properties to configure your sonarqube task. You can simply configure the task directly via:

sonarqube {
    properties {
        property 'sonar.projectName', 'sonarqubePullRequest'
        // ...
    }
}

Now you can configure the sonarqube task. To distinguish between your two cases, you can add a condition for different property values. The next example makes use of a project property as condition:

sonarqube {
    properties {
        // Same value for both cases
        property 'sonar.projectVersion', serviceVersion
        // Value based on condition
        if (project.findProperty('fullScan') {
            property 'sonar.projectName', 'sonarqubeFullScan'
        } else {
            property 'sonar.projectName', 'sonarqubePullRequest'
        }
    }
}

Alternatively, you can add another task of the type SonarQubeTask. This way, you could parametrize both tasks differently and call them (via command line or dependency) whenever you need them:

sonarqube {
    // Generated by the plugin, parametrize like described above
}

task sonarqubeFull(type: org.sonarqube.gradle.SonarQubeTask) {
    // Generated by your build script, parametrize in the same way
}


问:
NavController's push doesn't show Google Maps
I am trying to draw a map when a button is clicked. However, it doesn't seem to work when I use NavController.push(), but only with NavController.setRoot(). I don't get any errors, so I can't figure out what causes this.

This is the class that draws the map:

```<code>declare var google: any;

@Component({
  selector: 'page-Map',
  templateUrl: 'Map.html'
})

export class MapPage {

  public directionsService: any;
  public directionsDisplay: any;
  public directions: any;
  map: any;
  markers = [];

  constructor(private _theme: ThemeService, private shareService: ShareService, public ajaxService: AjaxService) {
    let rendererOptions = { draggable: true };
    this.directionsService = new google.maps.DirectionsService;
    let googleDiplay = new google.maps.DirectionsRenderer(rendererOptions);
    this.directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
    this.initMap();

  }

  //initialises the map
  initMap() {
    var point = { lat: 12.65, lng: 12.5683 };
    let divMap = (<HTMLInputElement>document.getElementById('map'));
    this.map = new google.maps.Map(divMap, {
      center: point,
      zoom: 15,
      disableDefaultUI: true,
      draggable: true,
      zoomControl: true,
    });
    let locationOptions = { timeout: 30000, enableHighAccuracy: true, maximumAge: 0 };

    navigator.geolocation.getCurrentPosition((position) => {
      this.map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    }, (error) => { }, locationOptions);

    //create marker and set to initialised map
    var myLatLng = this.map.getCenter();
    this.directionsDisplay.setMap(this.map);
  }
}
</code>```

This is the HTML:

```<code><ion-header>
    <ion-navbar>
      <ion-title>Location</ion-title>
    </ion-navbar>
  </div>
</ion-header>

<ion-content>
  <div id="map"></div>
</ion-content>
</code>```

答:
I have fixed the problem. The reason why it didn't work was that the id='map' was already in use, so I changed the id to id=map3 in the Map.html. So now my HTML file looks like this:

```<code>enter code here
</code>```

I also changed

let divMap = (<HTMLInputElement>document.getElementById('map'));
 to

let divMap = (<HTMLInputElement>document.getElementById('map3'));

and the CSS:

#map3 {
  height: 100%;
}

and the HTML:

```<code><ion-header>
    <ion-navbar>
      <ion-title>Location</ion-title>
    </ion-navbar>
  </div>
</ion-header>

<ion-content>
  <div id="map3"></div>
</ion-content>
</code>```

Body:
I am trying to draw a map when a button is clicked. However, it doesn't seem to work when I use NavController.push(), but only with NavController.setRoot(). I don't get any errors, so I can't figure out what causes this.

This is the class that draws the map:

declare var google: any;

@Component({
  selector: 'page-Map',
  templateUrl: 'Map.html'
})

export class MapPage {

  public directionsService: any;
  public directionsDisplay: any;
  public directions: any;
  map: any;
  markers = [];

  constructor(private _theme: ThemeService, private shareService: ShareService, public ajaxService: AjaxService) {
    let rendererOptions = { draggable: true };
    this.directionsService = new google.maps.DirectionsService;
    let googleDiplay = new google.maps.DirectionsRenderer(rendererOptions);
    this.directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
    this.initMap();

  }

  //initialises the map
  initMap() {
    var point = { lat: 12.65, lng: 12.5683 };
    let divMap = (<HTMLInputElement>document.getElementById('map'));
    this.map = new google.maps.Map(divMap, {
      center: point,
      zoom: 15,
      disableDefaultUI: true,
      draggable: true,
      zoomControl: true,
    });
    let locationOptions = { timeout: 30000, enableHighAccuracy: true, maximumAge: 0 };

    navigator.geolocation.getCurrentPosition((position) => {
      this.map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude));
    }, (error) => { }, locationOptions);

    //create marker and set to initialised map
    var myLatLng = this.map.getCenter();
    this.directionsDisplay.setMap(this.map);
  }
}

This is the HTML:

<ion-header>
    <ion-navbar>
      <ion-title>Location</ion-title>
    </ion-navbar>

</ion-header>

<ion-content>

</ion-content>

Body:
I have fixed the problem. The reason why it didn't work was that the id='map' was already in use, so I changed the id to id=map3 in the Map.html. So now my HTML file looks like this:

enter code here

I also changed

let divMap = (<HTMLInputElement>document.getElementById('map'));
 to

let divMap = (<HTMLInputElement>document.getElementById('map3'));

and the CSS:

#map3 {
  height: 100%;
}

and the HTML:

<ion-header>
    <ion-navbar>
      <ion-title>Location</ion-title>
    </ion-navbar>
  </div>
</ion-header>

<ion-content>
  <div id="map3"></div>
</ion-content>


问:
executing scripts on Google App Engine localhost
is there an easy way to execute scripts on Google App Engine localhost?
For instance i have few scripts to generate pilot data, it's quite painful to copy-and-paste them to the interactive console all the time.

Currently, i'm using a simple bash script to do this, but i'm not sure this is the best solution.

curl --data-urlencode "code=`cat src/gen_pilot_data.py`" http://localhost:8079/_ah/admin/interactive/execute

thanks,
 V

答:
Check out remote_api_shell.py, included in the SDK. This lets you run code on your local machine against APIs on your App Engine app, be they in production or on the dev_appserver.

The other option you have is to make your scripts into handlers, and simply GET or POST to the relevant URLs.


问:
Should I enable or disable dynamic proxies with entity framework 4.1 and MVC3?
Could someone offer up some advice or point out some blogs/articles that could help with making this decision? The proxies seem very foreign to me and I'm hesitant to use them. I like the ability to control Lazy Loading by using virtual properties in my model, but that's pretty much all the benefits that I can see. My application is a simple MVC web application and I don't need to wire up any hooks into the context for when the entities experience a changed state.

Anyway, here's my very limited list of pros and cons right now, let me know if I'm off base with any of this.

Pros

On 'Save' or 'Update',  I get seamless with 'Apply'Changes'

Lazy-Loading configuration is very easy.

Cons

Never used proxies before for my entities, this is a change in
approach that just seems uncomfortable for myself and fellow team
members.

Awkward to debug.

Requires extra code if I want serialize/de-serialize

On 'Save' or 'Update', the proxy must be the same object that was retrieved from the context.

答:
Use Automapper 4.2.1. New version is not having DynamicMap</p>

```<code>var parents = parentsRepo.GetAll().ToList();
Mapper.CreateMap<Parent,ParentDto>();
var parentsDto = Mapper.DynamicMap<List<ParentDto>>(parents);
</code>```

Body:
Use Automapper 4.2.1. New version is not having DynamicMap

var parents = parentsRepo.GetAll().ToList();
Mapper.CreateMap<Parent,ParentDto>();
var parentsDto = Mapper.DynamicMap<List<ParentDto>>(parents);