问:
How to implement a method with an unknown number of arguments?
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

```<code>public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}
</code>```

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

```<code>void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}
</code>```

答:
this is a very interesting Question.you can use method overloading concept if you know the maximum number of arguments coming.

lets say you know that at max user can give 2 parameters then you can do something like this.

```<code>public void implementation(){
System.out.println("method with zero args")
}

public void implementation(String arg1){
System.out.println("method with one args and is:-"+arg1)
}

public void implementation(String arg1,String arg2){
System.out.println("method with two  args and are :-"+arg1+"  "+arg2)
}
</code>```

if you dont know the maximum number of args you can implement in multiple ways.
 1.create a collection and store them in collection object and pass the object as argument.

```<code>List args= new List();
l.add(arg1)
----------
----------
----------
l.add(argn)
</code>```

now pass this as argument to the function call as

```<code>objecReference.implementation(l)
</code>```

2.using var arg methods.
this is the very easy way to solve this kind of problems from java 1.8.

in implementation

```<code>public String implementation(int(change to required datattype)...x){
    //here x will act like an array
    for(int a:x){//iam assuming int values are coming
    System.out.println(a)
}
}
</code>```

now you can call this function with atleast 0 args like

```<code>    objecReference.implementation()
    objecReference.implementation(10)
    objecReference.implementation(10,20)
    objecReference.implementation(12,23,34,5,6)
</code>```

Body:
I have 1 interface and 3 class. I would like the class to be able to both implement the interface which need a transform method. This method must exist but there can't be more than one per class. I don't know the number of parameters taken by this class.

Example :

public interface A{
    public void transform(Object ... args);
}

public class B implements A{
    public void transform(String a){
        System.out.println(a);
    }
}

public class C implements A{
    public void transform(Integer a, Character b){
        System.out.println(a+b);
    }
}

// super generic case if possible with Objects + primitive
public class D implements A{
    public void transform(int a, String b){
        System.out.println(a+b);
    }
}

This doesn't work. But I hope you got the idea. Is something like this possible in java ? How should I call them in a generic way ? Let's say if I have an other method like :

void callTransf(A a, Object ... objs){
    Method m = a.getClass().getMethods()[0];
    m.invoke(a, objs)
}

Body:
this is a very interesting Question.you can use method overloading concept if you know the maximum number of arguments coming.

lets say you know that at max user can give 2 parameters then you can do something like this.

public void implementation(){
System.out.println("method with zero args")
}

public void implementation(String arg1){
System.out.println("method with one args and is:-"+arg1)
}

public void implementation(String arg1,String arg2){
System.out.println("method with two  args and are :-"+arg1+"  "+arg2)
}

if you dont know the maximum number of args you can implement in multiple ways.
 1.create a collection and store them in collection object and pass the object as argument.

List args= new List();
l.add(arg1)
----------
----------
----------
l.add(argn)

now pass this as argument to the function call as

objecReference.implementation(l)

2.using var arg methods.
this is the very easy way to solve this kind of problems from java 1.8.

in implementation

public String implementation(int(change to required datattype)...x){
    //here x will act like an array
    for(int a:x){//iam assuming int values are coming
    System.out.println(a)
}
}

now you can call this function with atleast 0 args like

    objecReference.implementation()
    objecReference.implementation(10)
    objecReference.implementation(10,20)
    objecReference.implementation(12,23,34,5,6)


来源: stackexchange

问:
How to temporarily disable XSS protection in modern browsers for testing?
Is it possible to temporarily disable the XSS protection found in modern browsers for testing purposes?

I'm trying to explain to a co-worker what happens when one sends this to an XSS-vulnerable web form:

```<code><script>alert("Danger");</script>
</code>```

However, it appears that both Chrome and Firefox are preventing the XSS popup. Can I disable this protection so I can fully see the results of my actions?

答:
You can redirect the user to another local web page when the form is submitted and print the infected data. Chrome will not detect that.

Hint: You can use sessions / cookies to store the infected data between the 2 pages.

Example in PHP:

index.php

```<code><?php
    setcookie('infected', $_POST['infected']);

    if($_POST['infected'])
        header('location: show.php');
?>

<form action="index.php" method="POST" />
    <p>
        Username: <input type="text" name="infected" />
        <input type="submit" value="Add Comment" />
    </p>
</form>
</code>```

show.php

```<code>echo $_COOKIE['data'];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to temporarily disable the XSS protection found in modern browsers for testing purposes?

I'm trying to explain to a co-worker what happens when one sends this to an XSS-vulnerable web form:

However, it appears that both Chrome and Firefox are preventing the XSS popup. Can I disable this protection so I can fully see the results of my actions?

Body:
You can redirect the user to another local web page when the form is submitted and print the infected data. Chrome will not detect that.

Hint: You can use sessions / cookies to store the infected data between the 2 pages.

Example in PHP:

index.php

<?php
    setcookie('infected', $_POST['infected']);

    if($_POST['infected'])
        header('location: show.php');
?>

<form action="index.php" method="POST" />
    <p>
        Username: <input type="text" name="infected" />
        <input type="submit" value="Add Comment" />
    </p>
</form>

show.php

echo $_COOKIE['data'];


问:
How can I reshape data from long to wide
** Sample data added after comment**

What I have:

pmts <- data.frame(stringsAsFactors=FALSE,
           name = c("johndoe", "johndoe", "janedoe", "foo", "foo", "foo"),
           pmt_amount = c(550L, 550L, 995L, 375L, 375L, 375L),
           pmt_date = c("9/1/16", "11/1/16", "12/15/16", "1/5/17", "3/5/17", "5/5/17")
)

#>      name pmt_amount pmt_date
#> 1 johndoe        550   9/1/16
#> 2 johndoe        550  11/1/16
#> 3 janedoe        995 12/15/16
#> 4     foo        375   1/5/17
#> 5     foo        375   3/5/17
#> 6     foo        375   5/5/17
```

<p>What I am looking to achieve:</p>

<pre class="lang-r prettyprint-override"><code>read.table(header = T, text =
"name    pmt_amount  first_pmt   second_pmt  third_pmt
johndoe    550        9/1/16       11/1/16    NA
  janedoe    995        12/15/16       NA       NA
  foo       375        1/5/17       3/5/17   5/5/17"
)

#>      name pmt_amount first_pmt second_pmt third_pmt
#> 1 johndoe        550    9/1/16    11/1/16      <NA>
#> 2 janedoe        995  12/15/16       <NA>      <NA>
#> 3     foo        375    1/5/17     3/5/17    5/5/17
</code>```

** End of update**

I have a large dataset with payment information for different products. Some of these products have a pay-in-full option as well as a two-pay and three-pay option. I need to create fields that would be First_Payment, Second_Payment, and Third_Payment and would populate NA in the respective fields if there was only one or two payments.

I've tried a couple options and the best workaround I have thus far is this:

pmts %>%
  group_by(Email, Name, Amount, Form.Title) %>%
  summarise(First_Payment = min(Payment.Date),
           Second_Payment = median(Payment.Date),
           Last_Payment = max(Payment.Date)) -> pmts
```

<p>This obviously is not ideal as is making up a payment date for the 2-pay plans and I would have to instruct the end-user to ignore this field and just look at the 1st and 3rd fields. </p>

<p>I also tried to summarise with partial sorts like this:</p>

<pre class="lang-r prettyprint-override"><code>n <- length(pmts$Payment.Date)
sort(pmts$Payment.Date,partial=n-1)[n-1]
</code>```

However, if there wasn't three payments for the person, it would take the n-1 date from the entire data set and apply to all other fields.

Ideally, I would have it so if it was a pay-in-full the the First_Payment field would have the date and the 2nd/3rd fields would say NA. The 2-pay would have 1st and 2nd dates and the 3rd field would say NA. And finally the 3 pay would have all 3 dates.

The end users here are not super data savvy so I'm trying to make this as easy to interpret as possible. Any suggestions would be tremendously appreciated. Thank you!

答:
You can use tidyr for this.

library(dplyr)
library(tidyr)

pmts <- tibble(
  name = c("johndoe", "johndoe", "janedoe", "foo", "foo", "foo"),
  pmt_amount = c(550L, 550L, 995L, 375L, 375L, 375L),
  pmt_date = lubridate::mdy(c("9/1/16", "11/1/16", "12/15/16", "1/5/17", "3/5/17", "5/5/17"))
)

pmts
#> # A tibble: 6 x 3
#>      name pmt_amount   pmt_date
#>     <chr>      <int>     <date>
#> 1 johndoe        550 2016-09-01
#> 2 johndoe        550 2016-11-01
#> 3 janedoe        995 2016-12-15
#> 4     foo        375 2017-01-05
#> 5     foo        375 2017-03-05
#> 6     foo        375 2017-05-05

pmts_long <- pmts %>%
  group_by(name) %>%
  arrange(name, pmt_date) %>%
  mutate(pmt = row_number()) %>%
  ungroup() %>%
  complete(name, nesting(pmt)) %>%
  fill(pmt_amount, .direction = "down")

pmts_long
#> # A tibble: 9 x 4
#>      name   pmt pmt_amount   pmt_date
#>     <chr> <int>      <int>     <date>
#> 1     foo     1        375 2017-01-05
#> 2     foo     2        375 2017-03-05
#> 3     foo     3        375 2017-05-05
#> 4 janedoe     1        995 2016-12-15
#> 5 janedoe     2        995         NA
#> 6 janedoe     3        995         NA
#> 7 johndoe     1        550 2016-09-01
#> 8 johndoe     2        550 2016-11-01
#> 9 johndoe     3        550         NA

pmts_wide <- pmts_long %>%
  gather("key", "val", -name, -pmt_amount, -pmt) %>%
  unite(pmt_number, key, pmt) %>%
  spread(pmt_number, val)

pmts_wide
#> # A tibble: 3 x 5
#>      name pmt_amount pmt_date_1 pmt_date_2 pmt_date_3
#> *   <chr>      <int>     <date>     <date>     <date>
#> 1     foo        375 2017-01-05 2017-03-05 2017-05-05
#> 2 janedoe        995 2016-12-15         NA         NA
#> 3 johndoe        550 2016-09-01 2016-11-01         NA
```

Body:
** Sample data added after comment**

What I have:

pmts <- data.frame(stringsAsFactors=FALSE,
           name = c("johndoe", "johndoe", "janedoe", "foo", "foo", "foo"),
           pmt_amount = c(550L, 550L, 995L, 375L, 375L, 375L),
           pmt_date = c("9/1/16", "11/1/16", "12/15/16", "1/5/17", "3/5/17", "5/5/17")
)

#>      name pmt_amount pmt_date
#> 1 johndoe        550   9/1/16
#> 2 johndoe        550  11/1/16
#> 3 janedoe        995 12/15/16
#> 4     foo        375   1/5/17
#> 5     foo        375   3/5/17
#> 6     foo        375   5/5/17

What I am looking to achieve:

read.table(header = T, text =
"name    pmt_amount  first_pmt   second_pmt  third_pmt
johndoe    550        9/1/16       11/1/16    NA
  janedoe    995        12/15/16       NA       NA
  foo       375        1/5/17       3/5/17   5/5/17"
)

#>      name pmt_amount first_pmt second_pmt third_pmt
#> 1 johndoe        550    9/1/16    11/1/16      <NA>
#> 2 janedoe        995  12/15/16       <NA>      <NA>
#> 3     foo        375    1/5/17     3/5/17    5/5/17

** End of update**

I have a large dataset with payment information for different products. Some of these products have a pay-in-full option as well as a two-pay and three-pay option. I need to create fields that would be First_Payment, Second_Payment, and Third_Payment and would populate NA in the respective fields if there was only one or two payments.

I've tried a couple options and the best workaround I have thus far is this:

pmts %>%
  group_by(Email, Name, Amount, Form.Title) %>%
  summarise(First_Payment = min(Payment.Date),
           Second_Payment = median(Payment.Date),
           Last_Payment = max(Payment.Date)) -> pmts

This obviously is not ideal as is making up a payment date for the 2-pay plans and I would have to instruct the end-user to ignore this field and just look at the 1st and 3rd fields.

I also tried to summarise with partial sorts like this:

n <- length(pmts$Payment.Date)
sort(pmts$Payment.Date,partial=n-1)[n-1]

However, if there wasn't three payments for the person, it would take the n-1 date from the entire data set and apply to all other fields.

Ideally, I would have it so if it was a pay-in-full the the First_Payment field would have the date and the 2nd/3rd fields would say NA. The 2-pay would have 1st and 2nd dates and the 3rd field would say NA. And finally the 3 pay would have all 3 dates.

The end users here are not super data savvy so I'm trying to make this as easy to interpret as possible. Any suggestions would be tremendously appreciated. Thank you!


答:
I think you are looking for this:</p>

```<code>db.collection.aggregate([
{$match: {}},
{$unwind: "$floors"},
{$unwind: "$floors.rooms"},
{$unwind: "$floors.rooms.devices"},
{$group: {
    _id: "$floors.rooms._id",
    d1: {$push: "$floors.rooms.devices"}
}},
{$unwind:"$d1"},
{$group: {
    _id: "ignore-me",
    devices: {$push: "$d1"}
}}

]).pretty();
</code>```

Title: MongoDB query embedded document array

Body:
I have the following document:

{
    "_id" : ObjectId("59299670266cc82a042f3817"),
    "_userId" : ObjectId("590a08dba07c1a1bee87b310"),
    "name" : "My home",
    "floors" : [
        {
            "_id" : ObjectId("59299670266cc82a042f4541"),
            "name" : "Floor 1",
            "rooms" : [
                {
                    "_id" : ObjectId("59299670266cc82a042f4551"),
                    "name" : "Room 1",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4561"),
                            "name" : "Device 1"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4562"),
                            "name" : "Device 2"
                        }
                    ]
                },
                {
                    "_id" : ObjectId("59299670266cc82a042f4552"),
                    "name" : "Room 2",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4563"),
                            "name" : "Device 3"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4564"),
                            "name" : "Device 4"
                        }
                    ]
                }
            ]
        },
        {
            "_id" : ObjectId("59299670266cc82a042f4542"),
            "name" : "Floor 2",
            "rooms" : [
                {
                    "_id" : ObjectId("59299670266cc82a042f4553"),
                    "name" : "Room 1",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4565"),
                            "name" : "Device 5"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4566"),
                            "name" : "Device 6"
                        }
                    ]
                },
                {
                    "_id" : ObjectId("59299670266cc82a042f4554"),
                    "name" : "Room 2",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4567"),
                            "name" : "Device 7"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4568"),
                            "name" : "Device 8"
                        }
                    ]
                }
            ]
        }
    ]
}

And I would like to get a list of all devices:

[
    {
        "_id" : ObjectId("59299670266cc82a042f4561"),
        "name" : "Device 1"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4562"),
        "name" : "Device 2"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4563"),
        "name" : "Device 3"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4564"),
        "name" : "Device 4"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4565"),
        "name" : "Device 5"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4566"),
        "name" : "Device 6"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4567"),
        "name" : "Device 7"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4568"),
        "name" : "Device 8"
    }
]

Is that possible with MongoDB?

I've tried it with aggregate and { $unwind: $floors.rooms.devices } or

{ $unwind: $floors }
{ $unwind: $floors.rooms }
{ $unwind: $floors.rooms.devices }

but the output is always empty. I don't know if I would get the output I want with $unwind at all.

Because I'm also using aggregate for other things a solution with it would be nice.

Body:
I think you are looking for this:

db.collection.aggregate([
{$match: {}},
{$unwind: "$floors"},
{$unwind: "$floors.rooms"},
{$unwind: "$floors.rooms.devices"},
{$group: {
    _id: "$floors.rooms._id",
    d1: {$push: "$floors.rooms.devices"}
}},
{$unwind:"$d1"},
{$group: {
    _id: "ignore-me",
    devices: {$push: "$d1"}
}}

]).pretty();


问:
Arm Linux sshd-telnetd Kernel Oops Tracking
I have an ARM-Linux Embedded system with Allwinner A20 CPU. It runs Debian Wheezy 7 with sunxi kernel 3.4.79.

I am getting this error in every a few days, totally random:
    https://drive.google.com/file/d/0B8-UCj5FQ1cVUXZYTEFQU1dRalU/view?usp=sharing

If you see clearly, the issue seems to be caused from SSHD or TELNETD, however I think it is hiding the real trouble. I am using exactly same eMMC image over hundreds of identical devices without any trouble.

For testing,

```<code>1) Disabled all kernel modules -> no luck.
2) Reduced CPU clock to 528Mhz - > No luck
3) Replaced power supply -> No luck
4) Replaced hardware -> No luck
</code>```

How can I trace this issue, and how can I find out the real reason of this oops ?

Note: The embedded system is running Asterisk 1.8.13.1 with 435 SIP Clients.

答:
To trace linux oops you can use gdb with vmlinux image.
For example, read this manual
http://opensourceforu.com/2011/01/understanding-a-kernel-oops/</p>

Body:
I have an ARM-Linux Embedded system with Allwinner A20 CPU. It runs Debian Wheezy 7 with sunxi kernel 3.4.79.

I am getting this error in every a few days, totally random:
    https://drive.google.com/file/d/0B8-UCj5FQ1cVUXZYTEFQU1dRalU/view?usp=sharing

If you see clearly, the issue seems to be caused from SSHD or TELNETD, however I think it is hiding the real trouble. I am using exactly same eMMC image over hundreds of identical devices without any trouble.

For testing,

1) Disabled all kernel modules -> no luck.
2) Reduced CPU clock to 528Mhz - > No luck
3) Replaced power supply -> No luck
4) Replaced hardware -> No luck

How can I trace this issue, and how can I find out the real reason of this oops ?

Note: The embedded system is running Asterisk 1.8.13.1 with 435 SIP Clients.


问:
How to iterate over an array that's inside an object in React JS
Imagine I have an array of objects like so:

```<code>const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]
</code>```

And I'm wanting to assign each of the images inside of the images array to a React component called CarrouselItem using props:

```<code>class CarrouselItem extends React.Component {
  render() {

    return (
      <div>
        <img src={this.props.imageUrl} />
      </div>
    )
  }
}
</code>```

Which is then placed into a parent component called Carrousel, where I loop over the object and return the images inside, to be placed inside of the CarrouselItem component:

```<code>class Carrousel extends React.Component {
  render() {
    return (
      <div>
        <h4>Slide image</h4>
        {chefs.map((chef, index) => {
          return <CarrouselItem imageUrl={chef.images[index]} />
        })}
      </div>
    )
  }
}
</code>```

What I expect to happen

The map function should iterate over all of the objects (in this case, just one of them) which then creates X number of CarrouselItem components, each with an  that's taken from the images array.

What actually happens

Unfortunately I'm only getting the first item in the array (in this case, 'http://lorempixel.com/400/400/sports/').

Could someone be so kind to explain where I'm going wrong here?

Link to CodePen.

答:
The reason why its only giving you one item, is because you are mapping over a chef and not his images.. so you only iterate once. Instead you just want to map over the images like so chefs.images.map

```<code>const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]

class Carrousel extends React.Component {
  render() {
    const elems = [];
    chefs.forEach( (chef) => {
        chef && chef.images.forEach( (image, j) => {
            elems.push(<CarrouselItem imageUrl={image} key={i} />)
        })
    })
    return (
      <div>
        <h4>Slide image</h4>
        {elems}
      </div>
    )
  }
}
</code>```

I would recommend you make a chef component that renders things like the chefs information, name, age, location, restaurant... etc.. and renders a carousel for each chef with their images.

Body:
Imagine I have an array of objects like so:

const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]

And I'm wanting to assign each of the images inside of the images array to a React component called CarrouselItem using props:

class CarrouselItem extends React.Component {
  render() {

    return (

    )
  }
}

Which is then placed into a parent component called Carrousel, where I loop over the object and return the images inside, to be placed inside of the CarrouselItem component:

class Carrousel extends React.Component {
  render() {
    return (

Slide image

        {chefs.map((chef, index) => {
          return <CarrouselItem imageUrl={chef.images[index]} />
        })}

    )
  }
}

What I expect to happen

The map function should iterate over all of the objects (in this case, just one of them) which then creates X number of CarrouselItem components, each with an  that's taken from the images array.

What actually happens

Unfortunately I'm only getting the first item in the array (in this case, 'http://lorempixel.com/400/400/sports/').

Could someone be so kind to explain where I'm going wrong here?

Link to CodePen.

Body:
The reason why its only giving you one item, is because you are mapping over a chef and not his images.. so you only iterate once. Instead you just want to map over the images like so chefs.images.map

const chefs = [
  {
    key: 1,
    images: ['http://lorempixel.com/400/400/sports/', 'http://lorempixel.com/400/400/abstract/', 'http://lorempixel.com/400/400/animals/', 'http://lorempixel.com/400/400/city/', 'http://lorempixel.com/400/400/people/']
  }
]

class Carrousel extends React.Component {
  render() {
    const elems = [];
    chefs.forEach( (chef) => {
        chef && chef.images.forEach( (image, j) => {
            elems.push(<CarrouselItem imageUrl={image} key={i} />)
        })
    })
    return (
      <div>
        <h4>Slide image</h4>
        {elems}
      </div>
    )
  }
}

I would recommend you make a chef component that renders things like the chefs information, name, age, location, restaurant... etc.. and renders a carousel for each chef with their images.


问:
Node.js: "process run out of memory"
I have the following code which leads to the error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

It doesn't make any difference whether I set --max_old_space_size=4096 (or bigger numbers) or not. I have 16 GB RAM on my PC.

System: win10/node.js 6.9.2/mongodb 3.4

I have over 16 000 000 messages in the "chatModel". With a smaller amount of messages the code works.

Do you have any suggestions how to solve the problem/optimize the code?

```<code>function sortOutMessages(){

var atSymbol = "@";
var rgx = new RegExp("^\\" +atSymbol);

chatModel.find({messageContent: rgx}, function (err, doc){

    var docs = doc;
    var docsLength = docs.length;

    for (var i =0; i<docsLength;i++) {
        var directedMessagesObj = new directedMessagesModel
        ({
            timeStamp: docs[i].timeStamp,
            channelName: docs[i].channelName,
            userName: docs[i].userName,
            userID: docs[i].userID,
            messageContent: docs[i].messageContent,
            messageLength: docs[i].messageLength,
            subscriber: docs[i].subscriber,
            turbo: docs[i].turbo,
            moderator: docs[i].moderator
        });

        directedMessagesObj.save({upsert:true}, function (err) {
            var fs = require('fs');
            if (err) {
                    fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n")
                    loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                    return console.log(err);
            }

        });
    }

});

}
</code>```

答:
I advise </p>

```<code> module.exports.asyncEach = function(iterableList, callback, done) {
  var i = -1,
    length = iterableList.length;

function loop() {
    i++;
    if (i === length) {
        done();
        return;
    }
    callback(iterableList[i], loop);
}
loop();
   };
</code>```

<p>then you call asyncEach  with async save model is very beter  </p>

Title: Node.js: "process run out of memory"

Body:
I have the following code which leads to the error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

It doesn't make any difference whether I set --max_old_space_size=4096 (or bigger numbers) or not. I have 16 GB RAM on my PC.

System: win10/node.js 6.9.2/mongodb 3.4

I have over 16 000 000 messages in the "chatModel". With a smaller amount of messages the code works.

Do you have any suggestions how to solve the problem/optimize the code?

function sortOutMessages(){

var atSymbol = "@";
var rgx = new RegExp("^\\" +atSymbol);

chatModel.find({messageContent: rgx}, function (err, doc){

    var docs = doc;
    var docsLength = docs.length;

    for (var i =0; i<docsLength;i++) {
        var directedMessagesObj = new directedMessagesModel
        ({
            timeStamp: docs[i].timeStamp,
            channelName: docs[i].channelName,
            userName: docs[i].userName,
            userID: docs[i].userID,
            messageContent: docs[i].messageContent,
            messageLength: docs[i].messageLength,
            subscriber: docs[i].subscriber,
            turbo: docs[i].turbo,
            moderator: docs[i].moderator
        });

        directedMessagesObj.save({upsert:true}, function (err) {
            var fs = require('fs');
            if (err) {
                    fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n")
                    loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                    return console.log(err);
            }

        });
    }

});

}

Body:
I advise

 module.exports.asyncEach = function(iterableList, callback, done) {
  var i = -1,
    length = iterableList.length;

function loop() {
    i++;
    if (i === length) {
        done();
        return;
    }
    callback(iterableList[i], loop);
}
loop();
   };

then you call asyncEach  with async save model is very beter


问:
Why would multiple simultaneous AJAX calls to the same ASP.NET MVC action cause the browser to block?
A few days back I asked this question:

Why does $.getJSON() block the browser?

I fire six jQuery async ajax requests at the same controller action pretty much all at once. Each request takes 10 seconds to return.

Through debugging and logging requests to the action method I notice that the requests are serialised and never run in parallel. i.e. I see a timeline in my log4net logs like this:

```
2010-12-13 13:25:06,633 [11164] INFO   - Got:1156
2010-12-13 13:25:16,634 [11164] INFO   - Returning:1156
2010-12-13 13:25:16,770 [7124] INFO   - Got:1426
2010-12-13 13:25:26,772 [7124] INFO   - Returning:1426
2010-12-13 13:25:26,925 [11164] INFO   - Got:1912
2010-12-13 13:25:36,926 [11164] INFO   - Returning:1912
2010-12-13 13:25:37,096 [9812] INFO   - Got:1913
2010-12-13 13:25:47,098 [9812] INFO   - Returning:1913
2010-12-13 13:25:47,283 [7124] INFO   - Got:2002
2010-12-13 13:25:57,285 [7124] INFO   - Returning:2002
2010-12-13 13:25:57,424 [11164] INFO   - Got:1308
2010-12-13 13:26:07,425 [11164] INFO   - Returning:1308
```

Looking at the network timeline in FireFox I see this:

Both the log sample above and the Firefox network timeline are for the same set of requests.

Are requests to the same action from the same page serialised? I'm aware of serialised access to the Session object in the same session, but no session data is being touched.

I stripped the client side code down to a single request (the longest running one) but this still blocks the browser, i.e. only when the ajax request completes does the browser respond to any link clicking.

What I also observe here (in Chrome's developer tools) is that upon clicking on a link when a long running ajax request is executing it reports a Failed to load resource error  immediately which suggests that the browser has killed (or is attempting to kill and waiting?) the ajax request:

However the browser still takes an age to redirect to the new page.

Are ajax requests really asynchronous or is this sleight of hand because javascript is actually single threaded?

Are my requests just taking too long for this to work?

The problem occurs in Firefox and IE as well.

I also changed the script to use $.ajax directly and explicitly set async: true.

I'm running this on IIS7.5, both the Windows 2008R2 and Windows 7 flavours do the same thing.

Debug and release builds also behave the same.

答:
The answer was staring me in the face.

ASP.NET Session State Overview:

Access to ASP.NET session state is exclusive per session, which means that if two different users make concurrent requests, access to each separate session is granted concurrently. However, if two concurrent requests are made for the same session (by using the same SessionID value), the first request gets exclusive access to the session information. The second request executes only after the first request is finished.

Annoyingly I'd skimmed paragraph this a couple of weeks ago not really taking in the full impact of the bold sentences. I had read that simply as "access to session state is serialised" and not "all requests, no matter whether you touch session state or not, are serialised" if the requests came from the same session.

Fortunately there is a work around in ASP.NET MVC3 and its possible to create session-less controllers. Scott Guthrie talks about these here:

Announcing ASP.NET MVC 3 (Release Candidate 2)

I installed MVC3 RC2 and upgraded the project. Decorating the controller in question with [SessionState(SessionStateBehavior.Disabled)] solves the problem.

And of course typically I just found this in Stack Overflow a few minutes ago:

Asynchronous Controller is blocking requests in ASP.NET MVC through jQuery

ContentLicense: CC BY-SA 2.5

Body:
A few days back I asked this question:

Why does $.getJSON() block the browser?

I fire six jQuery async ajax requests at the same controller action pretty much all at once. Each request takes 10 seconds to return.

Through debugging and logging requests to the action method I notice that the requests are serialised and never run in parallel. i.e. I see a timeline in my log4net logs like this:

2010-12-13 13:25:06,633 [11164] INFO   - Got:1156
2010-12-13 13:25:16,634 [11164] INFO   - Returning:1156
2010-12-13 13:25:16,770 [7124] INFO   - Got:1426
2010-12-13 13:25:26,772 [7124] INFO   - Returning:1426
2010-12-13 13:25:26,925 [11164] INFO   - Got:1912
2010-12-13 13:25:36,926 [11164] INFO   - Returning:1912
2010-12-13 13:25:37,096 [9812] INFO   - Got:1913
2010-12-13 13:25:47,098 [9812] INFO   - Returning:1913
2010-12-13 13:25:47,283 [7124] INFO   - Got:2002
2010-12-13 13:25:57,285 [7124] INFO   - Returning:2002
2010-12-13 13:25:57,424 [11164] INFO   - Got:1308
2010-12-13 13:26:07,425 [11164] INFO   - Returning:1308

Looking at the network timeline in FireFox I see this:

Both the log sample above and the Firefox network timeline are for the same set of requests.

Are requests to the same action from the same page serialised? I'm aware of serialised access to the Session object in the same session, but no session data is being touched.

I stripped the client side code down to a single request (the longest running one) but this still blocks the browser, i.e. only when the ajax request completes does the browser respond to any link clicking.

What I also observe here (in Chrome's developer tools) is that upon clicking on a link when a long running ajax request is executing it reports a Failed to load resource error  immediately which suggests that the browser has killed (or is attempting to kill and waiting?) the ajax request:

However the browser still takes an age to redirect to the new page.

Are ajax requests really asynchronous or is this sleight of hand because javascript is actually single threaded?

Are my requests just taking too long for this to work?

The problem occurs in Firefox and IE as well.

I also changed the script to use $.ajax directly and explicitly set async: true.

I'm running this on IIS7.5, both the Windows 2008R2 and Windows 7 flavours do the same thing.

Debug and release builds also behave the same.


问:
visual studio 2017 installer keeps asking me to update
I want to download the windows form application template for c# in visual studio 2017. but when I open the visual studio installer it's asking me to update, and when I finish updating its asking me again and I can never open the actual installer.

答:
Try this:

Start your Visual Studio 2017

Update it (https://learn.microsoft.com/en-us/visualstudio/install/update-visual-studio )

Restart the IDE

Then download the application template.


问:
Why does adding an extra field to struct greatly improves its performance?
I noticed that a struct wrapping a single float is significantly slower than using a float directly, with approximately half of the performance.

```<code>using System;
using System.Diagnostics;

struct Vector1 {

    public float X;

    public Vector1(float x) {
        X = x;
    }

    public static Vector1 operator +(Vector1 a, Vector1 b) {
        a.X = a.X + b.X;
        return a;
    }
}
</code>```

However, upon adding an additional 'extra' field, some magic seems to happen and performance once again becomes more reasonable:

```<code>struct Vector1Magic {

    public float X;
    private bool magic;

    public Vector1Magic(float x) {
        X = x;
        magic = true;
    }

    public static Vector1Magic operator +(Vector1Magic a, Vector1Magic b) {
        a.X = a.X + b.X;
        return a;
    }
}
</code>```

The code I used to benchmark these is as follows:

```<code>class Program {
    static void Main(string[] args) {
        int iterationCount = 1000000000;
        var sw = new Stopwatch();
        sw.Start();
        var total = 0.0f;
        for (int i = 0; i < iterationCount; i++) {
            var v = (float) i;
            total = total + v;
        }
        sw.Stop();
        Console.WriteLine("Float time was {0} for {1} iterations.", sw.Elapsed, iterationCount);
        Console.WriteLine("total = {0}", total);
        sw.Reset();
        sw.Start();
        var totalV = new Vector1(0.0f);
        for (int i = 0; i < iterationCount; i++) {
            var v = new Vector1(i);
            totalV += v;
        }
        sw.Stop();
        Console.WriteLine("Vector1 time was {0} for {1} iterations.", sw.Elapsed, iterationCount);
        Console.WriteLine("totalV = {0}", totalV);
        sw.Reset();
        sw.Start();
        var totalVm = new Vector1Magic(0.0f);
        for (int i = 0; i < iterationCount; i++) {
            var vm = new Vector1Magic(i);
            totalVm += vm;
        }
        sw.Stop();
        Console.WriteLine("Vector1Magic time was {0} for {1} iterations.", sw.Elapsed, iterationCount);
        Console.WriteLine("totalVm = {0}", totalVm);
        Console.Read();
    }
}
</code>```

With the benchmark results:

```<code>Float time was 00:00:02.2444910 for 1000000000 iterations.
Vector1 time was 00:00:04.4490656 for 1000000000 iterations.
Vector1Magic time was 00:00:02.2262701 for 1000000000 iterations.
</code>```

Compiler/environment settings:
OS: Windows 10 64 bit
Toolchain: VS2017
Framework: .Net 4.6.2
Target: Any CPU Prefer 32 bit

If 64 bit is set as the target, our results are more predictable, but significantly worse than what we see with Vector1Magic on the 32 bit target:

```<code>Float time was 00:00:00.6800014 for 1000000000 iterations.
Vector1 time was 00:00:04.4572642 for 1000000000 iterations.
Vector1Magic time was 00:00:05.7806399 for 1000000000 iterations.
</code>```

For the real wizards, I've included a dump of the IL here: https://pastebin.com/sz2QLGEx

Further investigation indicates that this seems to be specific to the windows runtime, as the mono compiler produces the same IL.

On the mono runtime, both struct variants have roughly 2x slower performance compared to the raw float. This is quite a bit different to the performance we see on .Net.

What's going on here?

*Note this question originally included a flawed benchmark process (Thanks Max Payne for pointing this out), and has been updated to more accurately reflect the timings.

答:
This should not happen. This is obviously some sort of missalignment that forces the JIT to not work like it should.

```<code>struct Vector1 //Works fast in 32 Bit
{
    public double X;
}

struct Vector1 //Works fast in 64 Bit and 32 Bit
{
    public double X;
    public double X2;
}
</code>```

You also must call:
Console.WriteLine(total); that increases the time exactly to Vector1Magic time which makes sense. The question still holds, why Vector1 is so slow.

Maybe structs are not optimized for sizeof(foo) < 64 Bit in 64 bit mode.

It seems that this was ansered 7 years ago:
Why is 16 byte the recommended size for struct in C#?

Body:
I noticed that a struct wrapping a single float is significantly slower than using a float directly, with approximately half of the performance.

using System;
using System.Diagnostics;

struct Vector1 {

    public float X;

    public Vector1(float x) {
        X = x;
    }

    public static Vector1 operator +(Vector1 a, Vector1 b) {
        a.X = a.X + b.X;
        return a;
    }
}

However, upon adding an additional 'extra' field, some magic seems to happen and performance once again becomes more reasonable:

struct Vector1Magic {

    public float X;
    private bool magic;

    public Vector1Magic(float x) {
        X = x;
        magic = true;
    }

    public static Vector1Magic operator +(Vector1Magic a, Vector1Magic b) {
        a.X = a.X + b.X;
        return a;
    }
}

The code I used to benchmark these is as follows:

class Program {
    static void Main(string[] args) {
        int iterationCount = 1000000000;
        var sw = new Stopwatch();
        sw.Start();
        var total = 0.0f;
        for (int i = 0; i < iterationCount; i++) {
            var v = (float) i;
            total = total + v;
        }
        sw.Stop();
        Console.WriteLine("Float time was {0} for {1} iterations.", sw.Elapsed, iterationCount);
        Console.WriteLine("total = {0}", total);
        sw.Reset();
        sw.Start();
        var totalV = new Vector1(0.0f);
        for (int i = 0; i < iterationCount; i++) {
            var v = new Vector1(i);
            totalV += v;
        }
        sw.Stop();
        Console.WriteLine("Vector1 time was {0} for {1} iterations.", sw.Elapsed, iterationCount);
        Console.WriteLine("totalV = {0}", totalV);
        sw.Reset();
        sw.Start();
        var totalVm = new Vector1Magic(0.0f);
        for (int i = 0; i < iterationCount; i++) {
            var vm = new Vector1Magic(i);
            totalVm += vm;
        }
        sw.Stop();
        Console.WriteLine("Vector1Magic time was {0} for {1} iterations.", sw.Elapsed, iterationCount);
        Console.WriteLine("totalVm = {0}", totalVm);
        Console.Read();
    }
}

With the benchmark results:

Float time was 00:00:02.2444910 for 1000000000 iterations.
Vector1 time was 00:00:04.4490656 for 1000000000 iterations.
Vector1Magic time was 00:00:02.2262701 for 1000000000 iterations.

Compiler/environment settings:
OS: Windows 10 64 bit
Toolchain: VS2017
Framework: .Net 4.6.2
Target: Any CPU Prefer 32 bit

If 64 bit is set as the target, our results are more predictable, but significantly worse than what we see with Vector1Magic on the 32 bit target:

Float time was 00:00:00.6800014 for 1000000000 iterations.
Vector1 time was 00:00:04.4572642 for 1000000000 iterations.
Vector1Magic time was 00:00:05.7806399 for 1000000000 iterations.

For the real wizards, I've included a dump of the IL here: https://pastebin.com/sz2QLGEx

Further investigation indicates that this seems to be specific to the windows runtime, as the mono compiler produces the same IL.

On the mono runtime, both struct variants have roughly 2x slower performance compared to the raw float. This is quite a bit different to the performance we see on .Net.

What's going on here?

*Note this question originally included a flawed benchmark process (Thanks Max Payne for pointing this out), and has been updated to more accurately reflect the timings.

Body:
This should not happen. This is obviously some sort of missalignment that forces the JIT to not work like it should.

struct Vector1 //Works fast in 32 Bit
{
    public double X;
}

struct Vector1 //Works fast in 64 Bit and 32 Bit
{
    public double X;
    public double X2;
}

You also must call:
Console.WriteLine(total); that increases the time exactly to Vector1Magic time which makes sense. The question still holds, why Vector1 is so slow.

Maybe structs are not optimized for sizeof(foo) < 64 Bit in 64 bit mode.

It seems that this was ansered 7 years ago:
Why is 16 byte the recommended size for struct in C#?


问:
Segmentation Fault in Initializing a structure
I'm aiming to implement an algorithm to check if a graph is topologic. But well, that's not the issue here. I'm getting a core dump when trying to initialize my graph structure with the given data.

```<code>Program received signal SIGSEGV, Segmentation fault.
0x00000000004009a3 in initGraph (numberNode=15, numberArc=17, g=0x1) at src/topologicGraphOp.c:45
45          g->numberNode = numberNode;
</code>```

I'm really confused because the issue seems so obvious and yet, I cannot find it after various tries so I'm hoping that someone will find that dumb error like "bah, it's obvious" because well... I'm out of luck...

Here is the structure :

```<code>typedef struct {
   int numberNode;
   int numberArc;

   int *distances;
   int *predecessors;

   float **matrix;
   queue *successors;

   char *graphTitle;
   char **nodeDescription;
   int *time;

} graph;
</code>```

And the function where the core dump seem to appear:

```<code>void initGraph(int numberNode, int numberArc, graph *g) {
    int i, j;

    g->numberNode = numberNode;
    g->numberArc = numberArc;
    g->nodeDescription = malloc(numberNode * sizeof (char));
    g->matrix = (float **) calloc(g->numberNode, sizeof (float*));

    for (i = 0; i < g->numberNode; i++) {
        g->matrix[i] = (float *) calloc(g->numberNode, sizeof (float));
        g->nodeDescription[i] = malloc(sizeof (char));
    }
}
</code>```

My main function just calls the initializing function.
Thanks a lot!

edit: The solution in the comment :)
I forgot to malloc my graph pointer before using it in the function.

答:
A segmentation fault virtually always means you are messing up a pointer in some way. Either during allocation, or during dereference (for reading or writing, that's the same thing here). You might also have changed the address it points to, for example by forgetting to dereference it on assignment (similar to *g = ...; becomes g = ...;); that particular mistake would be less likely with structures, but you never know...

Consequently, when you get a segmentation fault, always double-check all pointers involved in the problematic statement. In this case, g is the only pointer involved (both the parameter and the field numberNode are non-pointer variables), so g is the suspect part.

You don't show us how you call the initialization function, but in this case the code is simple enough that the cause should be obvious once you look at where the g parameter to initGraph() is coming from, and what its value (and address) is on entry to initGraph(). Is g allocated at all? Does g point to a sufficiently large block of memory to hold the entire structure? Has any relevant field (e.g. in the case of a pointer to a structure that itself contains pointers) been initialized, and is the value reasonable immediately before the problematic statement?

If you are still uncertain, look at the address and value of that pointer, either through the debugger or by adding something like printf("&g=(%p)",g); to the top of initGraph(). Invalid pointers have a tendency to stand out quite well from the noise of actual memory addresses.

Body:
I'm aiming to implement an algorithm to check if a graph is topologic. But well, that's not the issue here. I'm getting a core dump when trying to initialize my graph structure with the given data.

Program received signal SIGSEGV, Segmentation fault.
0x00000000004009a3 in initGraph (numberNode=15, numberArc=17, g=0x1) at src/topologicGraphOp.c:45
45          g->numberNode = numberNode;

I'm really confused because the issue seems so obvious and yet, I cannot find it after various tries so I'm hoping that someone will find that dumb error like "bah, it's obvious" because well... I'm out of luck...

Here is the structure :

typedef struct {
   int numberNode;
   int numberArc;

   int *distances;
   int *predecessors;

   float **matrix;
   queue *successors;

   char *graphTitle;
   char **nodeDescription;
   int *time;

} graph;

And the function where the core dump seem to appear:

void initGraph(int numberNode, int numberArc, graph *g) {
    int i, j;

    g->numberNode = numberNode;
    g->numberArc = numberArc;
    g->nodeDescription = malloc(numberNode * sizeof (char));
    g->matrix = (float **) calloc(g->numberNode, sizeof (float*));

    for (i = 0; i < g->numberNode; i++) {
        g->matrix[i] = (float *) calloc(g->numberNode, sizeof (float));
        g->nodeDescription[i] = malloc(sizeof (char));
    }
}

My main function just calls the initializing function.
Thanks a lot!

edit: The solution in the comment :)
I forgot to malloc my graph pointer before using it in the function.


问:
How to separate frequency from audio file (.wav)
I want to separate low, mid and high frequencies from .wav file.
for that i have used FFT to convert data from time domain to frequency domain.

code for reading file and applying Fast Fourier Transform with help of NAudio is like

```<code>OpenFileDialog file = new OpenFileDialog();
        file.ShowDialog();
        WaveFileReader reader = new WaveFileReader(file.FileName);
        int samepleRate = reader.WaveFormat.SampleRate;
        double ts = 1.0 / samepleRate;
        int _fftLength = 4096;
        double time = reader.TotalTime.TotalSeconds;
        int channels = reader.WaveFormat.Channels;
        int _m = (int)Math.Log(_fftLength, 2.0);
        float fileSize = (float)reader.Length / 1048576;
        if (fileSize < 2)
            window = 8;
        else if (fileSize > 2 && fileSize < 4)
            window = 16;
        else if (fileSize > 4 && fileSize < 8)
            window = 32;
        else if (fileSize > 8 && fileSize < 12)
            window = 128;
        else if (fileSize > 12 && fileSize < 20)
            window = 256;
        else if (fileSize > 20 && fileSize < 30)
            window = 512;
        else
            window = 2048;

        byte[] readBuffer = new byte[reader.Length];

        reader.Read(readBuffer,0,readBuffer.Length);
        float[] data = ConvertByteToFloat(readBuffer,readBuffer.Length);

        Complex[] fftBuffer= new Complex[_fftLength];
        int fftPos = 0;
        for (int i = 0; i < _fftLength; i++)
        {
            fftBuffer[fftPos].X = (float)(data[i] * NAudio.Dsp.FastFourierTransform.HammingWindow(i,_fftLength));
            fftBuffer[fftPos].Y = 0;
            fftPos++;
        }
        NAudio.Dsp.FastFourierTransform.FFT(true, _m, fftBuffer);

private float[] ConvertByteToFloat(byte[] array, int length)
    {
        int samplesNeeded = length / 4;
        float[] floatArr = new float[samplesNeeded];

        for (int i = 0; i < samplesNeeded; i++)
        {
            floatArr[i] = (float)BitConverter.ToInt32(array, i * 4);
        }

        return floatArr;
    }

 //ZedGraph code
        GraphPane myPane = zedGraphControl1.GraphPane;
        myPane.Title.Text = "Frequency domain output";
        PointPairList list1 = new PointPairList();
        PointPairList list2 = new PointPairList();
        for (int i = 0; i < fftBuffer.Length; i++)
        {
            list1.Add(i, fftBuffer[i].Y);
        }
        list2.Add(0, 0);
        //list2.Add(time, 0);uncomment this and remove below to plot time domain graph
        var maxIndex = -1;
        var maxValue = 0f;
        for (var j = 0; j < _fftLength / 2; j++)
        {
            var value = fftBuffer[j].X * fftBuffer[j].X
                + fftBuffer[j].Y * fftBuffer[j].Y;

            if (value > maxValue)
            {
                maxIndex = j;
                maxValue = value;
            }
            var freq = maxIndex == -1 ? 0
           : (ushort)Math.Round((_fftLength - maxIndex) / (_fftLength * ts));
            list2.Add(freq, 0);
        }
        if (myCurve1 != null && myCurve2 != null)
        {
            myCurve1.Clear();
            myCurve2.Clear();
        }

        myCurve1 = myPane.AddCurve(null, list1, Color.Blue, SymbolType.None);
        myCurve1.IsX2Axis = true;
        myCurve2 = myPane.AddCurve(null, list2, Color.Black, SymbolType.None);
        myPane.XAxis.Scale.MaxAuto = true;
        myPane.XAxis.Scale.MinAuto = true;
        myPane.YAxis.Title.Text = "Amplitude";
        myPane.XAxis.Title.Text = "Frequency";
        zedGraphControl1.AxisChange();
        zedGraphControl1.Invalidate();
</code>```

Now I got the frequency domain data and I have plotted it on ZedGraph with Amplitude on Y-axis and Frequency on X-axis.
FFT output on ZedGraph

Now I have complex data as FFT out with me, but how to separate below listed frequencies from given data and how to generate or play file of that particular frequency.

Low - 20Hz to 500Hz

Mid - 500Hz to 4KHz

High- 4KHz to 20KHz

Any advise or guidance would be greatly appreciated..!!

答:
If you just want to filter an audio stream, you are heading down a computationally expensive approach.    FFTs are great for identifying spectral signatures.  But if you want to go form time to frequency and back to time, that's a lot of number crunching (and you will most likely not like what you hear).   If you keep the currently stated path, you will need to do some form of masking in the frequency domain, then convert back to time.   When you convert back to time (a real product) it's going to sound "dirty" (you will need to implement some form of an imaginary to real merge). In your code, you form a magnitude squared to get back to a real time series (note - this will give you a rectified signal - which should sound hissy).

If you want to isolate a particular band, start with some form of a FIR band pass filter.  If you want to hear the result as you are developing, check out examples of how to use the Android AudioTrack class.

Body:
I want to separate low, mid and high frequencies from .wav file.
for that i have used FFT to convert data from time domain to frequency domain.

code for reading file and applying Fast Fourier Transform with help of NAudio is like

OpenFileDialog file = new OpenFileDialog();
        file.ShowDialog();
        WaveFileReader reader = new WaveFileReader(file.FileName);
        int samepleRate = reader.WaveFormat.SampleRate;
        double ts = 1.0 / samepleRate;
        int _fftLength = 4096;
        double time = reader.TotalTime.TotalSeconds;
        int channels = reader.WaveFormat.Channels;
        int _m = (int)Math.Log(_fftLength, 2.0);
        float fileSize = (float)reader.Length / 1048576;
        if (fileSize < 2)
            window = 8;
        else if (fileSize > 2 && fileSize < 4)
            window = 16;
        else if (fileSize > 4 && fileSize < 8)
            window = 32;
        else if (fileSize > 8 && fileSize < 12)
            window = 128;
        else if (fileSize > 12 && fileSize < 20)
            window = 256;
        else if (fileSize > 20 && fileSize < 30)
            window = 512;
        else
            window = 2048;

        byte[] readBuffer = new byte[reader.Length];

        reader.Read(readBuffer,0,readBuffer.Length);
        float[] data = ConvertByteToFloat(readBuffer,readBuffer.Length);

        Complex[] fftBuffer= new Complex[_fftLength];
        int fftPos = 0;
        for (int i = 0; i < _fftLength; i++)
        {
            fftBuffer[fftPos].X = (float)(data[i] * NAudio.Dsp.FastFourierTransform.HammingWindow(i,_fftLength));
            fftBuffer[fftPos].Y = 0;
            fftPos++;
        }
        NAudio.Dsp.FastFourierTransform.FFT(true, _m, fftBuffer);

private float[] ConvertByteToFloat(byte[] array, int length)
    {
        int samplesNeeded = length / 4;
        float[] floatArr = new float[samplesNeeded];

        for (int i = 0; i < samplesNeeded; i++)
        {
            floatArr[i] = (float)BitConverter.ToInt32(array, i * 4);
        }

        return floatArr;
    }

 //ZedGraph code
        GraphPane myPane = zedGraphControl1.GraphPane;
        myPane.Title.Text = "Frequency domain output";
        PointPairList list1 = new PointPairList();
        PointPairList list2 = new PointPairList();
        for (int i = 0; i < fftBuffer.Length; i++)
        {
            list1.Add(i, fftBuffer[i].Y);
        }
        list2.Add(0, 0);
        //list2.Add(time, 0);uncomment this and remove below to plot time domain graph
        var maxIndex = -1;
        var maxValue = 0f;
        for (var j = 0; j < _fftLength / 2; j++)
        {
            var value = fftBuffer[j].X * fftBuffer[j].X
                + fftBuffer[j].Y * fftBuffer[j].Y;

            if (value > maxValue)
            {
                maxIndex = j;
                maxValue = value;
            }
            var freq = maxIndex == -1 ? 0
           : (ushort)Math.Round((_fftLength - maxIndex) / (_fftLength * ts));
            list2.Add(freq, 0);
        }
        if (myCurve1 != null && myCurve2 != null)
        {
            myCurve1.Clear();
            myCurve2.Clear();
        }

        myCurve1 = myPane.AddCurve(null, list1, Color.Blue, SymbolType.None);
        myCurve1.IsX2Axis = true;
        myCurve2 = myPane.AddCurve(null, list2, Color.Black, SymbolType.None);
        myPane.XAxis.Scale.MaxAuto = true;
        myPane.XAxis.Scale.MinAuto = true;
        myPane.YAxis.Title.Text = "Amplitude";
        myPane.XAxis.Title.Text = "Frequency";
        zedGraphControl1.AxisChange();
        zedGraphControl1.Invalidate();

Now I got the frequency domain data and I have plotted it on ZedGraph with Amplitude on Y-axis and Frequency on X-axis.
FFT output on ZedGraph

Now I have complex data as FFT out with me, but how to separate below listed frequencies from given data and how to generate or play file of that particular frequency.

Low - 20Hz to 500Hz

Mid - 500Hz to 4KHz

High- 4KHz to 20KHz

Any advise or guidance would be greatly appreciated..!!


答:
actually its picking chef object index which is one so you getting first instead use chefs.images.map

```<code>{chefs[0].images.map((image, index) => {
          return <CarrouselItem imageUrl={image} />
        })}
</code>```

Title: How to iterate over an array that's inside an object in React JS

Body:
actually its picking chef object index which is one so you getting first instead use chefs.images.map

{chefs[0].images.map((image, index) => {
          return <CarrouselItem imageUrl={image} />
        })}


问:
Tkinter window closes during runtime
I have a python script and a text file that contains a list of times (string) like 18:59, 19:00, 19:02, etc... each in a different line. I want to change the color of a label in tkinter whenever the time in the file is the current time.

The problem is the tkinter window closes once it opens and then opens again once everything is complete. I tried using update_idletasks. But that did not change anything. Here is the required code structure:

```<code>class gui(Frame):
    def __init__(self, parent, txt2, index):
    Frame.__init__(self,parent,background="white")
    self.parent = parent
    self.txt2 = txt2
    self.index = index
    self.initUI()
    self.initChange()

def initUI(self)
    #initial window with white color label

def initChange(self)
    while(last line hasnt reached):
        if(current time = file time)
            #line for changing label color and self.index++
            self.parent.update_idletasks()
        sleep(30)

main()
    #call all the functions required and root, txt file and initial index is passed as arguments for gui functions
</code>```

Since I was requested to put up all the functions i have used, I am doing so but I am omitting out the details. The code is too long.

```<code>def dataextract(xlsheet):
    #take data from xlsheet
    #called only once in the main() function

def fileio(x, txt1)
    #Write the time list after doing some operations
    #based on data from xlsheet

def main():
    x = datextract(xlsheet)
    fileio(x, txt)
    print "File IO competed..."
    root = Tk()
    app = gui(root, txt2, 0)
    root.mainloop()

if __name__ == "__main__":
    main()
</code>```

答:
After going through many posts in stack overflow and a lot of other websites, I got my app working fine. The problem is, python was running on a single thread. The tkinter window is initially allocated a thread and when initChange is called, the thread is now taken away from tkinter. All I had to do was call initChange in a separate thread. To do so,

```<code>class gui(Frame):
    def __init__(self, parent, txt2, index):
    Frame.__init__(self,parent,background="white")
    self.parent = parent
    self.txt2 = txt2
    self.index = index
    self.initUI()
    thread.start_new_thread(self.initChange,())
</code>```

But there is a small problem here. There is a slight delay since my while loop keeps checking every second if the specified time has reached. It would be really helpful if someone can suggest some improvements.

Title: Tkinter window closes during runtime

Body:
I have a python script and a text file that contains a list of times (string) like 18:59, 19:00, 19:02, etc... each in a different line. I want to change the color of a label in tkinter whenever the time in the file is the current time.

The problem is the tkinter window closes once it opens and then opens again once everything is complete. I tried using update_idletasks. But that did not change anything. Here is the required code structure:

class gui(Frame):
    def __init__(self, parent, txt2, index):
    Frame.__init__(self,parent,background="white")
    self.parent = parent
    self.txt2 = txt2
    self.index = index
    self.initUI()
    self.initChange()

def initUI(self)
    #initial window with white color label

def initChange(self)
    while(last line hasnt reached):
        if(current time = file time)
            #line for changing label color and self.index++
            self.parent.update_idletasks()
        sleep(30)

main()
    #call all the functions required and root, txt file and initial index is passed as arguments for gui functions

Since I was requested to put up all the functions i have used, I am doing so but I am omitting out the details. The code is too long.

def dataextract(xlsheet):
    #take data from xlsheet
    #called only once in the main() function

def fileio(x, txt1)
    #Write the time list after doing some operations
    #based on data from xlsheet

def main():
    x = datextract(xlsheet)
    fileio(x, txt)
    print "File IO competed..."
    root = Tk()
    app = gui(root, txt2, 0)
    root.mainloop()

if __name__ == "__main__":
    main()

Body:
After going through many posts in stack overflow and a lot of other websites, I got my app working fine. The problem is, python was running on a single thread. The tkinter window is initially allocated a thread and when initChange is called, the thread is now taken away from tkinter. All I had to do was call initChange in a separate thread. To do so,

class gui(Frame):
    def __init__(self, parent, txt2, index):
    Frame.__init__(self,parent,background="white")
    self.parent = parent
    self.txt2 = txt2
    self.index = index
    self.initUI()
    thread.start_new_thread(self.initChange,())

But there is a small problem here. There is a slight delay since my while loop keeps checking every second if the specified time has reached. It would be really helpful if someone can suggest some improvements.


问:
Update values on UI after a method makes changes on variables (Swift 3)
I'm new to swift. On my UI I have labels which display the values of some class instances. And, I have a class method that increases the value of those instances. After I call this method, my instance values do update; but the labels on the UI remain the same. How can I make this method also update my numbers in those labels.

Here is my ViewController code:

```<code>@IBOutlet weak var displayValue: UILabel! //this is the label that displays newNumber's value

override func viewDidLoad() {
    super.viewDidLoad()
    dispValue.text = String("\(newNumber.value))")
}
</code>```

Here is my code:

```<code>class MyNumbers {
    var value = 50

    func increaseValue(by: Int){
       value += by
    }
}

var newNumber = myNumbers()
newNumber.increaseValue(by: 5) //This does increase newNumber's value to 55
//but my label on my UI remains as 50
</code>```

答:
You need to assign the updated value to the UILabel. As best practice always make sure that you are invoking the UI Changes in main thread and also update the AutoLayouts when making a UI Update.

Replace:

```<code>newNumber.increaseValue(by: 5)
</code>```

With:

```<code>DispatchQueue.main.async {
    newNumber.increaseValue(by: 5)
    self.displayValue.text = "\(newNumber.value)"
    self.view.layoutIfNeeded()
}
</code>```

Body:
I'm new to swift. On my UI I have labels which display the values of some class instances. And, I have a class method that increases the value of those instances. After I call this method, my instance values do update; but the labels on the UI remain the same. How can I make this method also update my numbers in those labels.

Here is my ViewController code:

@IBOutlet weak var displayValue: UILabel! //this is the label that displays newNumber's value

override func viewDidLoad() {
    super.viewDidLoad()
    dispValue.text = String("\(newNumber.value))")
}

Here is my code:

class MyNumbers {
    var value = 50

    func increaseValue(by: Int){
       value += by
    }
}

var newNumber = myNumbers()
newNumber.increaseValue(by: 5) //This does increase newNumber's value to 55
//but my label on my UI remains as 50

Body:
You need to assign the updated value to the UILabel. As best practice always make sure that you are invoking the UI Changes in main thread and also update the AutoLayouts when making a UI Update.

Replace:

newNumber.increaseValue(by: 5)

With:

DispatchQueue.main.async {
    newNumber.increaseValue(by: 5)
    self.displayValue.text = "\(newNumber.value)"
    self.view.layoutIfNeeded()
}


问:
GWT Upload: How to Open Browser in a specific folder
Is there some way to setup a GWT UpLoad to start browsing from a specific folder ?

To have the windows browser work from a specific folder ?

or is that impossible in which case you would have to use some other way...

Could JAVA WEB START as shown here be limited or start from a specific folder ?

http://docs.oracle.com/javase/tutorial/uiswing/examples/components/JWSFileChooserDemoProject/src/components/JWSFileChooserDemo.java

答:
You won't be able to change the default directory for uploads in a browser from a web page. That's a security issue - see commentary control the working directory for <input type=“file”>?.

Given permission to the local machine, Java applets/applications deployed JWS would have the ability - additionally, ActiveX controls could also work for you if you're focusing on Windows.


问:
Xdebug (inside Docker container) ignoring XDEBUG_CONFIG environment variable
I'm running a PHP application on Docker and I'd like to debug it using XDebug.
In my docker-compose I added the following lines in the phpfpm part:

```<code>environment:
      XDEBUG_CONFIG: "remote_enable=1 remote_host=192.168.110.29 remote_port=9000 idekey=PHPSTORM remote_autostart=1"
      PHP_IDE_CONFIG: "serverName=reports.dev"
</code>```

I configured PHPStorm in the right way, listening on port 9000 and ran the application.

The application works flawlessly but XDebug doesn't seem to be working.

If I move the lines of configuration inside the php.ini file the debugger works, except for the fact that Server Name is empty and I cannot debug (that's why I tried following the docker-compose configuration way).

If, inside the docker container, I run echo $XDEBUG_CONFIG the output is right, but XDebug seems not to read that Env variable.

答:
I had the same problem. My image was based on nimmis/alpine-apache-php7/. I found that the image was using supervisor to start processes. supervisor has no knowledge of the Docker environment variables.

The convention to tell supervisor that a process needs to be run, is to create a run script at /etc/sv/{process}/run. A script like this was used to start Apache. I needed to change the script so that it would import Docker environment variables before starting Apache.

The docs for the base image explain the convention for importing Docker environment:

If you need environment variables from the docker command line (-e,--env=[]) add

source /etc/envvars

before you use them in the script file

So I created my own custom run script for Apache — I added source /etc/envvars just before execution of httpd.

I overwrote the original run script, by adding a simple COPY to my Dockerfile:

```<code>COPY apache-run.sh /etc/sv/apache2/run
</code>```

This successfully ensured that my $XDEBUG_CONFIG was visible to httpd at the time it was launched. I was able to confirm that this affected my PHP configuration, by printing phpinfo(); in a webpage.

Body:
I'm running a PHP application on Docker and I'd like to debug it using XDebug.
In my docker-compose I added the following lines in the phpfpm part:

environment:
      XDEBUG_CONFIG: "remote_enable=1 remote_host=192.168.110.29 remote_port=9000 idekey=PHPSTORM remote_autostart=1"
      PHP_IDE_CONFIG: "serverName=reports.dev"

I configured PHPStorm in the right way, listening on port 9000 and ran the application.

The application works flawlessly but XDebug doesn't seem to be working.

If I move the lines of configuration inside the php.ini file the debugger works, except for the fact that Server Name is empty and I cannot debug (that's why I tried following the docker-compose configuration way).

If, inside the docker container, I run echo $XDEBUG_CONFIG the output is right, but XDebug seems not to read that Env variable.

Body:
I had the same problem. My image was based on nimmis/alpine-apache-php7/. I found that the image was using supervisor to start processes. supervisor has no knowledge of the Docker environment variables.

The convention to tell supervisor that a process needs to be run, is to create a run script at /etc/sv/{process}/run. A script like this was used to start Apache. I needed to change the script so that it would import Docker environment variables before starting Apache.

The docs for the base image explain the convention for importing Docker environment:

If you need environment variables from the docker command line (-e,--env=[]) add

source /etc/envvars

before you use them in the script file

So I created my own custom run script for Apache — I added source /etc/envvars just before execution of httpd.

I overwrote the original run script, by adding a simple COPY to my Dockerfile:

COPY apache-run.sh /etc/sv/apache2/run

This successfully ensured that my $XDEBUG_CONFIG was visible to httpd at the time it was launched. I was able to confirm that this affected my PHP configuration, by printing phpinfo(); in a webpage.


问:
Using 'Core Data' with Phonegap?
Does it make sense to use 'Core Data' for storage in a Phonegap-based hybrid iPhone/iPad app? Our app is mainly going to run inside a UIWebView, but the data-storage component is going to be central to the working of the app. I know Mobile Safari has offline storage capability which can be used via PhoneGap, but we already have an in-house data-storage solution build on top of Core Data that we would like to leverage.

Thanks
Kapil

答:
i think if you have already made that investment, why not just write a native application?

you are going to have to do some "interesting" things to get the PhoneGap application to integrate with your CoreData solution.

Title: Using 'Core Data' with Phonegap?


问:
Return successively-yielded values as an array when generator is done
I would like to know if it is possible to return successively-yielded values as an array when the generator is done. This is what I have tried so far, where I add a return statement at the end of the generator and attempt to destructure the output:

```<code>function ajax(url) {
  fetch(url).then(data => data.json()).then(data => dataGen.next(data))
}

function* steps() {
  const beers = yield ajax('http://api.react.beer/v2/search?q=hops&type=beer');

  const wes = yield ajax('https://api.github.com/users/wesbos');

  const fatJoe = yield ajax('https://api.discogs.com/artists/51988');

  return [beers, wes, fatJoe]
}

const dataGen = steps();
const [beers, wes, fatJoe] = dataGen.next(); // kick it off
</code>```

However, none of the values are returned:

```<code>Uncaught ReferenceError: beers is not defined
Uncaught ReferenceError: wes is not defined
Uncaught ReferenceError: fatJoe is not defined
</code>```

答:
Stop using generators as a replacement for async/await. If you want to do that, you need to use a proper asynchronous runner such as the co library or Bluebird.coroutine. But their era is the past now, async/await is readily available in recent browsers (and in transpilers anyway)!

```<code>function ajax(url) {
  return fetch(url).then(data => data.json());
//^^^^^^
}

async function steps() {
  const beers = await ajax('http://api.react.beer/v2/search?q=hops&type=beer');
  const wes = await ajax('https://api.github.com/users/wesbos');
  const fatJoe = await ajax('https://api.discogs.com/artists/51988');

  return [beers, wes, fatJoe];
}

const dataPromise = steps(); // kick it off
dataPromise.then(([beers, wes, fatJoe]) => {
  console.log(…); // use results here
});
</code>```

(or alternatively await dataPromise in another async function)

Body:
I would like to know if it is possible to return successively-yielded values as an array when the generator is done. This is what I have tried so far, where I add a return statement at the end of the generator and attempt to destructure the output:

function ajax(url) {
  fetch(url).then(data => data.json()).then(data => dataGen.next(data))
}

function* steps() {
  const beers = yield ajax('http://api.react.beer/v2/search?q=hops&type=beer');

  const wes = yield ajax('https://api.github.com/users/wesbos');

  const fatJoe = yield ajax('https://api.discogs.com/artists/51988');

  return [beers, wes, fatJoe]
}

const dataGen = steps();
const [beers, wes, fatJoe] = dataGen.next(); // kick it off

However, none of the values are returned:

Uncaught ReferenceError: beers is not defined
Uncaught ReferenceError: wes is not defined
Uncaught ReferenceError: fatJoe is not defined

Body:
Stop using generators as a replacement for async/await. If you want to do that, you need to use a proper asynchronous runner such as the co library or Bluebird.coroutine. But their era is the past now, async/await is readily available in recent browsers (and in transpilers anyway)!

function ajax(url) {
  return fetch(url).then(data => data.json());
//^^^^^^
}

async function steps() {
  const beers = await ajax('http://api.react.beer/v2/search?q=hops&type=beer');
  const wes = await ajax('https://api.github.com/users/wesbos');
  const fatJoe = await ajax('https://api.discogs.com/artists/51988');

  return [beers, wes, fatJoe];
}

const dataPromise = steps(); // kick it off
dataPromise.then(([beers, wes, fatJoe]) => {
  console.log(…); // use results here
});

(or alternatively await dataPromise in another async function)


问:
Getting data from angular components
Angular 1.5

I created component that by fact just form with few fields. Every field looks at model through ng-model

On main page user can dynamically add multiple exemplars of my component.
Is there any way to get data from all components models on page by one button pressed?

I tried to add callback function to this component that should return component model data. But it works only if I have one component on page. When user add few more nothing returns to parent controller.

Thanks for your replies.

答:
Here is the answer from other forum
https://plnkr.co/edit/0PPwLq2SjKwVJWYpldgU?p=preview

```<code>var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  this.children = [];

  this.addChild = instance => {
    console.log(instance);
    this.children.push(instance);
  }

  this.getChildValue = function() {
    console.log(this.children);
  }

});

app.component('myComponent', {
  bindings: {
    addChild: '<'
  },
  controller: function MyComponentCtrl() {

    this.name = '';
    this.surname = '';

    this.addChild(this);

  },
  template: `
    <input type='text' ng-model='$ctrl.name' placeholder='Enter name' />
    <input type='text' ng-model='$ctrl.surname' placeholder='Enter surname' />
  `
});
</code>```

Leave it here in case someone have the same problem
Sorry if my description wasn`t very clear

Title: Getting data from angular components

Body:
Here is the answer from other forum
https://plnkr.co/edit/0PPwLq2SjKwVJWYpldgU?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  this.children = [];

  this.addChild = instance => {
    console.log(instance);
    this.children.push(instance);
  }

  this.getChildValue = function() {
    console.log(this.children);
  }

});

app.component('myComponent', {
  bindings: {
    addChild: '<'
  },
  controller: function MyComponentCtrl() {

    this.name = '';
    this.surname = '';

    this.addChild(this);

  },
  template: `
    <input type='text' ng-model='$ctrl.name' placeholder='Enter name' />
    <input type='text' ng-model='$ctrl.surname' placeholder='Enter surname' />
  `
});

Leave it here in case someone have the same problem
Sorry if my description wasn`t very clear


问:
django: how to consume incoming POST data as a file-like obj for streaming processing
I'm using python + Django to handle incoming web requests that can post a large amount of JSON attached as one of the POST data fields (e.g. var1=abc&json_var=lots_of_data&other_var=xxx). I'd like to process the JSON in a streaming fashion with my own streaming json parser which takes a file-like handle as its input argument. It appears from https://docs.djangoproject.com/en/1.11/ref/request-response/ that this is feasible, using HttpRequest.__iter__(), but I can't find any examples of how to achieve this with my own code (i.e. not just importing a library like xml.etree.ElementTree).

Basically, I'd like to do the following:

POST request w/ big JSON => Django/python => create file-like handle to read POST => streaming url decoder => streaming JSON processor

I can use ijson for the streaming JSON processor. How do I fill in the two gaps for creating a file-like handle to the POST data and passing it to a streaming url decoder? Would prefer not to roll my own of either but I suppose if necessary I could.

答:
I was only able to solve this by rolling my own generators and iterators. There were a few keys to solving this:

finding how to access the file-like handle for the POST data in the case where data is sent chunked. I was able to find this at request.META.get('wsgi.input'), which I located by using this post to dump all of the request attributes

roll my own generator to read a file-like handle and yield (varname, data_chunk) pairs

roll my own generator, based on a modified version of this post, to create a file-like handle that has the normal read() operations but has three additional features:

f.varname returns the name of the current variable that is being read

data is url-unencoded before it is passed back from read()

f.next_pair() advances the handle to read the next variable. So, f.read() is called until it is finished with the first variable, then if there is another, f.next_pair() will return true and f.read() can be again called until the next variable is done being read

further stream processing can be achieved in the main loop

Putting it all together it looks something like:

```<code>f = request.META.get('wsgi.input')
ff = some_magic_adaptor(qs_from_file_to_generator(f))

while ff.next_pair():
    print 'varname:' + ff.varname
    if ff.varname == 'stream_parse_this':
        parser = stream_parser(ff)
        for event_results in parser:
            do_something

    while True:
        data = ff.read(buffer_size)
        if not data:
            break
        do_something_with_data_chunk(data)
</code>```

Body:
I was only able to solve this by rolling my own generators and iterators. There were a few keys to solving this:

finding how to access the file-like handle for the POST data in the case where data is sent chunked. I was able to find this at request.META.get('wsgi.input'), which I located by using this post to dump all of the request attributes

roll my own generator to read a file-like handle and yield (varname, data_chunk) pairs

roll my own generator, based on a modified version of this post, to create a file-like handle that has the normal read() operations but has three additional features:

f.varname returns the name of the current variable that is being read

data is url-unencoded before it is passed back from read()

f.next_pair() advances the handle to read the next variable. So, f.read() is called until it is finished with the first variable, then if there is another, f.next_pair() will return true and f.read() can be again called until the next variable is done being read

further stream processing can be achieved in the main loop

Putting it all together it looks something like:

f = request.META.get('wsgi.input')
ff = some_magic_adaptor(qs_from_file_to_generator(f))

while ff.next_pair():
    print 'varname:' + ff.varname
    if ff.varname == 'stream_parse_this':
        parser = stream_parser(ff)
        for event_results in parser:
            do_something

    while True:
        data = ff.read(buffer_size)
        if not data:
            break
        do_something_with_data_chunk(data)


问:
Undefined symbols for architecture x86_64 jsonrpc library
I have some hardtime compiling an application with QT using the jsonRpc library :

 - libjson-rpc-cpp

 - jsoncpp

When compiling, I have this error :

```<code>Undefined symbols for architecture x86_64:
Json::Value::operator=(Json::Value const&)", referenced from:
  jsonrpc::RpcProtocolServerV1::WrapException(Json::Value const&, jsonrpc::JsonRpcException const&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv1.o)
  jsonrpc::RpcProtocolServerV1::WrapResult(Json::Value const&, Json::Value&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv1.o)
  jsonrpc::RpcProtocolServerV1::WrapError(Json::Value const&, int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv1.o)
  jsonrpc::RpcProtocolServerV2::WrapException(Json::Value const&, jsonrpc::JsonRpcException const&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv2.o)
  jsonrpc::RpcProtocolServerV2::WrapResult(Json::Value const&, Json::Value&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv2.o)
  jsonrpc::RpcProtocolServerV2::WrapError(Json::Value const&, int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv2.o)
  jsonrpc::AbstractProtocolHandler::ProcessRequest(Json::Value const&, Json::Value&) in libjson-rpc-cpp.a(abstractprotocolhandler.o)
  ...
</code>```

I try to find in value.h the definition of the overload = operator and I find this :

```<code>Value& operator=(Value other);
</code>```

It's probably something to do with a linker issue, but I really don't know how to resolve it..

Can anyone please give me some help with this ?
Thank you

答:
I had the same error when compiling OSVR. The source of the problem was outdated jsoncpp headers in /usr/local/include.

What worked for me:

Remove jsoncpp from /usr/local/lib, /usr/local/include

Remove libjson-rpc-cpp from /usr/local/lib, /usr/local/include

Build and install jsoncpp, including dynamic library, from github source:

git clone --recursive https://github.com/VRPN/jsoncpp

git clone --recursive https://github.com/cinemast/libjson-rpc-cpp.git

cd jsoncpp

cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .

make

make install

cd ../libjson-rpc-cpp

cmake -DCMAKE_BUILD_TYPE=debug -DBUILD_STATIC_LIBS=ON -DBUILD_SHARED_LIBS=ON -DARCHIVE_INSTALL_DIR=. -G "Unix Makefiles" .

make

make install

Body:
I have some hardtime compiling an application with QT using the jsonRpc library :

 - libjson-rpc-cpp

 - jsoncpp

When compiling, I have this error :

Undefined symbols for architecture x86_64:
Json::Value::operator=(Json::Value const&)", referenced from:
  jsonrpc::RpcProtocolServerV1::WrapException(Json::Value const&, jsonrpc::JsonRpcException const&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv1.o)
  jsonrpc::RpcProtocolServerV1::WrapResult(Json::Value const&, Json::Value&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv1.o)
  jsonrpc::RpcProtocolServerV1::WrapError(Json::Value const&, int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv1.o)
  jsonrpc::RpcProtocolServerV2::WrapException(Json::Value const&, jsonrpc::JsonRpcException const&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv2.o)
  jsonrpc::RpcProtocolServerV2::WrapResult(Json::Value const&, Json::Value&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv2.o)
  jsonrpc::RpcProtocolServerV2::WrapError(Json::Value const&, int, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, Json::Value&) in libjson-rpc-cpp.a(rpcprotocolserverv2.o)
  jsonrpc::AbstractProtocolHandler::ProcessRequest(Json::Value const&, Json::Value&) in libjson-rpc-cpp.a(abstractprotocolhandler.o)
  ...

I try to find in value.h the definition of the overload = operator and I find this :

Value& operator=(Value other);

It's probably something to do with a linker issue, but I really don't know how to resolve it..

Can anyone please give me some help with this ?
Thank you


问:
Better way to do this ( using LINQ )?
I am comparing two lists and in one case I am removing the uncommon elements from one list ( removing from lists with more number of elements ) and in the other case (else statement) I am adding the uncommon elements to one list ( adding to list with lesser elements )

I am able to do this using the below given code but I was hoping to achieve this using LINQ in a more concise manner. Please suggest me an equivalent LINQ code

```<code>if (receivedList.Count < AuthorFacets.Count)
{
    for (int i = AuthorFacets.Count - 1; i >= 0; i--)
    {
        if (!receivedList.Contains(AuthorFacets[i]))
            AuthorFacets.RemoveAt(i);
    }
}
else
{
    for (int i = 0; i < receivedList.Count; i++)
    {
        if (!AuthorFacets.Contains(receivedList[i]))
            AuthorFacets.Add(receivedList[i]);
    }
}
</code>```

答:
Using linq you can try this </p>

```<code>if (receivedList.Count < AuthorFacets.Count)
{
  AuthorFacets.RemoveAll(a=>!receivedList.Contains(a))
}
else
{
  AuthorFactets.AddRange(receivedList.Where(r=> !AuthorFacets.Contains(r)))
}
</code>```

Title: Better way to do this ( using LINQ )?

Body:
I am comparing two lists and in one case I am removing the uncommon elements from one list ( removing from lists with more number of elements ) and in the other case (else statement) I am adding the uncommon elements to one list ( adding to list with lesser elements )

I am able to do this using the below given code but I was hoping to achieve this using LINQ in a more concise manner. Please suggest me an equivalent LINQ code

if (receivedList.Count < AuthorFacets.Count)
{
    for (int i = AuthorFacets.Count - 1; i >= 0; i--)
    {
        if (!receivedList.Contains(AuthorFacets[i]))
            AuthorFacets.RemoveAt(i);
    }
}
else
{
    for (int i = 0; i < receivedList.Count; i++)
    {
        if (!AuthorFacets.Contains(receivedList[i]))
            AuthorFacets.Add(receivedList[i]);
    }
}

Body:
Using linq you can try this

if (receivedList.Count < AuthorFacets.Count)
{
  AuthorFacets.RemoveAll(a=>!receivedList.Contains(a))
}
else
{
  AuthorFactets.AddRange(receivedList.Where(r=> !AuthorFacets.Contains(r)))
}


问:
Does it matter if we specify 'super' in an overridable method
Does it matter if we do specify the keyword "super" when overriding methods?

If yes, under what condition it does matter?

```<code>1.
@Override
public void foo() {
super.foo();
}

2.
@Override
public void foo() {
}
</code>```

答:
Depends on the method.

If you take a framework it often does "things" in the parent method too. If you know the parent method does nothing then it doesn't matter, however for future compatibility it's a good idea to always add the call to super.

The only exception when you really don't want to have what the parent method does. In that case you have no other choice.

In fact you often end up overriding methods for that reason if you use frameworks like Android or Spring.

Body:
Does it matter if we do specify the keyword "super" when overriding methods?

If yes, under what condition it does matter?

1.
@Override
public void foo() {
super.foo();
}

2.
@Override
public void foo() {
}


问:
How to compare responses of two methods in SoapUI
I am executing a SOPA method on two environments(Dev and UAT) in SopaUI free version and want to compare the responses to check data mismatch, please suggest any solution for the same.

Response Format-

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <GetAccountsResponse xmlns="http://services.multichoice.co.za/SelfCare">
         <GetAccountsResult xmlns:a="http://datacontracts.multichoice.co.za/SelfCare" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
            <a:Account>
               <a:afterDue121To150>0</a:afterDue121To150>
               <a:afterDue151To180>0</a:afterDue151To180>
               <a:afterDue180UpField>0</a:afterDue180UpField>
               <a:afterDue1To30Field>0</a:afterDue1To30Field>
               <a:afterDue31To60Field>0</a:afterDue31To60Field>
               <a:afterDue61To90Field>0</a:afterDue61To90Field>
               <a:afterDue91To120Field>0</a:afterDue91To120Field>
               <a:currency>NGN</a:currency>
               <a:currentAmount>0</a:currentAmount>
               <a:defaultCurrencytotalBalance>0</a:defaultCurrencytotalBalance>
               <a:defaultCuurencyCode>NGN</a:defaultCuurencyCode>
               <a:invoicePeriod>1</a:invoicePeriod>
               <a:isPrimary>true</a:isPrimary>
               <a:lastInvoiceAmount>0</a:lastInvoiceAmount>
               <a:lastInvoiceDate>2017-02-19T15:52:54</a:lastInvoiceDate>
               <a:methodOfPayment>Cash</a:methodOfPayment>
               <a:number>3112</a:number>
               <a:paymentDueDate>2016-11-10T00:00:00</a:paymentDueDate>
               <a:segmentation>Customer Segment N</a:segmentation>
               <a:status>Suspended</a:status>
               <a:totalBalance>0</a:totalBalance>
               <a:type>Ges</a:type>
            </a:Account>
         </GetAccountsResult>
      </GetAccountsResponse>
   </s:Body>
</s:Envelope>
</code>```

答:
//Step 1: Set DEV environment in your soap request using ReqProps = testRunner.testCase.getTestStepByName("stepname as in soapui suite"
       ReqProps.setPropertyValue("Endpoint","https://dev:endpoint")
//Step 2: Run the DEV step and save response in some variable testRunner.runTestStepByName("stepname as in soapui suite")
      DEvResponse = ReqProps.getPropertyValue("Response")

// Step 3: Repeat Same step for UAT environment and take response in variable UATResponse
// Step 4: Compare 2 responses using `DetailedDiff diffInRes = new DetailedDiff(new Diff(DEVRes, UATRes))

List differencesArray = diffInRes.getAllDifferences()`

// Step 5 . Take array size to verify if XMLs match. If XMLs does not match you can print differences and get all mismatches from array "differencesArray"

Body:
I am executing a SOPA method on two environments(Dev and UAT) in SopaUI free version and want to compare the responses to check data mismatch, please suggest any solution for the same.

Response Format-

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <GetAccountsResponse xmlns="http://services.multichoice.co.za/SelfCare">
         <GetAccountsResult xmlns:a="http://datacontracts.multichoice.co.za/SelfCare" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">

               0
               0
               0
               0
               0
               0
               0
               NGN
               0
               0
               NGN
               1
               true
               0
               2017-02-19T15:52:54
               Cash
               3112
               2016-11-10T00:00:00
               Customer Segment N
               Suspended
               0
               Ges

         </GetAccountsResult>
      </GetAccountsResponse>
   </s:Body>
</s:Envelope>


答:
It matters if the super has any work to do in their implementation of the method.

And usually, the super does have some work to do, otherwise the method would be abstract instead of overridable.

If you have written the super, then you know whether super should be invoked.  If someone else has written the super, you need to look at their documentation.

If you are using IntelliJ IDEA, then by default, IntelliJ IDEA will issue a warning if you omit calling super.  Under Settings -> Editor -> Inspections -> Java -> Inheritance issues you will find a "Method does not call super method" inspection which controls this warning.  If you want this warning to be issued on specific methods instead of all methods, then you can make use of the "Only report when supper method is annotated by:" option.  I have created the following annotation for this:

```<code>package javax.annotation;

import java.lang.annotation.*;

/**
 * Overriding-Methods-Must-Invoke-Super annotation.
 * See JSR 305: Annotations for Software Defect Detection
 *              (https://jcp.org/en/jsr/detail?id=305)
 */
@Retention( RetentionPolicy.CLASS )
@Target( ElementType.METHOD )
public @interface OverridingMethodsMustInvokeSuper
{
}
</code>```

This way, when I really want all descendants to invoke super, I annotate the super with @OverridingMethodsMustInvokeSuper.

Title: Does it matter if we specify 'super' in an overridable method

Body:
It matters if the super has any work to do in their implementation of the method.

And usually, the super does have some work to do, otherwise the method would be abstract instead of overridable.

If you have written the super, then you know whether super should be invoked.  If someone else has written the super, you need to look at their documentation.

If you are using IntelliJ IDEA, then by default, IntelliJ IDEA will issue a warning if you omit calling super.  Under Settings -> Editor -> Inspections -> Java -> Inheritance issues you will find a "Method does not call super method" inspection which controls this warning.  If you want this warning to be issued on specific methods instead of all methods, then you can make use of the "Only report when supper method is annotated by:" option.  I have created the following annotation for this:

package javax.annotation;

import java.lang.annotation.*;

/**
 * Overriding-Methods-Must-Invoke-Super annotation.
 * See JSR 305: Annotations for Software Defect Detection
 *              (https://jcp.org/en/jsr/detail?id=305)
 */
@Retention( RetentionPolicy.CLASS )
@Target( ElementType.METHOD )
public @interface OverridingMethodsMustInvokeSuper
{
}

This way, when I really want all descendants to invoke super, I annotate the super with @OverridingMethodsMustInvokeSuper.


问:
How to close java Applet through code
I am developing a java applet. I want it to be closed by the code. I have used System.Exit(0) but it is not working. Is there any other method to achieve this?

Thanks

答:
As said above,exiting applet is simple by adding System.exit(0) in if(condition) for which you want to close the applet.Though I am describing of
applet viewer.But,it certainly works fine.</p>

Title: How to close java Applet through code