问:
Row highlighting based on due date using php
I'm relatively new to PHP, I've learned procedural PHP and I'm playing around with an app.

I've Looked around the site and found a few samples on date formatting and highlighting using PHP, HTML and CSS.

With the help found here and the PHP manual, I've put together some code to highlight 2 different rows among many others provided by a database that follow this criteria:

Anything due in 1 day (today, yesterday, last week, etc.) should color the table row red.

Anything 3 days out (between 1 day and 3 days in the future) should color the table row yellow.

Anything else should utilize the bootstrap "table-striped" styling.

Here is the code I've put together

```<code>//Today + 1 day
$oneDay = date('m/d/Y', strtotime("+1 day"));
//Today + 3 days
$threeDays = date('m/d/Y', strtotime("+3 days"));

//Database entry for comparison
$due = date_create($record['projected_delivery']);

$dueOneDay = date_create($oneDay);
$dueThreeDays = date_create($threeDays);

//Get the difference between the 2 dates
$diffOne = date_diff($due, $dueOneDay);
$diffThree = date_diff($due, $dueThreeDays);

if ($diffThree->format('%d') < 3) {
   $highlight_css = " warning";
}elseif ($diffOne->format('%d') <= 1){
   $highlight_css = " danger";
}else {
   $highlight_css = "";
}
</code>```

I then add the $highlight_css to the HTML.

So far some of the functionality is working. Proper highlighting is not added for:

Dates older than 1 day (i.e. yesterday, last week)

How can this functionality be achieved?

答:
The issue

A DateInterval (the return value of date_diff()) has the number of days (actually stored in a property d, which could be used instead of getting a string with format()), which should always be a positive number. And for dates before today's date, the first date diff (i.e. $diffOne) will be 2+ days and the second date diff (i.e. $diffThreeDays) will be 4+ (see this playground example with debugging output above the table) so days before today's date will never be associated with either 'warning' or 'danger' according to the given logic.

A Solution

One approach (perhaps simpler) to comparing the dates is to use DateTime comparison

Note:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.1

So compare the DateTime variables (i.e. $due with $dueOneDay and $dueThreeDays) instead of the date differences.

In the logic below, you will notice that the order of the comparisons has been reversed, so the check for one day difference comes before the check for three days difference, in order to avoid the danger case never happening.

```<code>if ($due < $dueOneDay){
   $highlight_css = " danger";
}else if ($due <= $dueThreeDays) {
   $highlight_css = " warning";
}else {
   $highlight_css = "";
}
</code>```

With this approach, there is no need for the date_diff variables (i.e. $diffOne, $diffThree).

See a demonstration of this in this playground example.

1http://php.net/manual/en/datetime.diff.php#example-2524

Body:
I'm relatively new to PHP, I've learned procedural PHP and I'm playing around with an app.

I've Looked around the site and found a few samples on date formatting and highlighting using PHP, HTML and CSS.

With the help found here and the PHP manual, I've put together some code to highlight 2 different rows among many others provided by a database that follow this criteria:

Anything due in 1 day (today, yesterday, last week, etc.) should color the table row red.

Anything 3 days out (between 1 day and 3 days in the future) should color the table row yellow.

Anything else should utilize the bootstrap "table-striped" styling.

Here is the code I've put together

//Today + 1 day
$oneDay = date('m/d/Y', strtotime("+1 day"));
//Today + 3 days
$threeDays = date('m/d/Y', strtotime("+3 days"));

//Database entry for comparison
$due = date_create($record['projected_delivery']);

$dueOneDay = date_create($oneDay);
$dueThreeDays = date_create($threeDays);

//Get the difference between the 2 dates
$diffOne = date_diff($due, $dueOneDay);
$diffThree = date_diff($due, $dueThreeDays);

if ($diffThree->format('%d') < 3) {
   $highlight_css = " warning";
}elseif ($diffOne->format('%d') <= 1){
   $highlight_css = " danger";
}else {
   $highlight_css = "";
}

I then add the $highlight_css to the HTML.

So far some of the functionality is working. Proper highlighting is not added for:

Dates older than 1 day (i.e. yesterday, last week)

How can this functionality be achieved?

Body:
The issue

A DateInterval (the return value of date_diff()) has the number of days (actually stored in a property d, which could be used instead of getting a string with format()), which should always be a positive number. And for dates before today's date, the first date diff (i.e. $diffOne) will be 2+ days and the second date diff (i.e. $diffThreeDays) will be 4+ (see this playground example with debugging output above the table) so days before today's date will never be associated with either 'warning' or 'danger' according to the given logic.

A Solution

One approach (perhaps simpler) to comparing the dates is to use DateTime comparison

Note:

As of PHP 5.2.2, DateTime objects can be compared using comparison operators.1

So compare the DateTime variables (i.e. $due with $dueOneDay and $dueThreeDays) instead of the date differences.

In the logic below, you will notice that the order of the comparisons has been reversed, so the check for one day difference comes before the check for three days difference, in order to avoid the danger case never happening.

if ($due < $dueOneDay){
   $highlight_css = " danger";
}else if ($due <= $dueThreeDays) {
   $highlight_css = " warning";
}else {
   $highlight_css = "";
}

With this approach, there is no need for the date_diff variables (i.e. $diffOne, $diffThree).

See a demonstration of this in this playground example.

1http://php.net/manual/en/datetime.diff.php#example-2524


来源: stackexchange

问:
Passing object containing object from model to view in ASP.NET
Usin ASP.NET I am trying to add a list of profiles to a object in a model and then enumerate over this list in the view.

```<code>     public ActionResult Index(BlogPage currentPage)
    {
        var model = new BlogPageModel(currentPage);

        var pages = new List<BlogPage>();

        var profilePages = new List<ProfilePage>();
        if (currentPage.ProfileArea != null)
        {
            foreach (LinkItem linkItem in currentPage.ProfileArea)
            {
                var page = _pageDataHelper.GetPageData(linkItem);
                var profilePage = page as ProfilePage;
                if (profilePage != null)
                {
                    profilePages.Add(profilePage);
                }
            }
            model.Profiles = profilePages;
        }
        return View(model);
    }
</code>```

Using this code in the view:

```<code>   @foreach (ProfilePage profile in Model.BlogPages)
            {
            @Html.Partial("../ProfilePage/Index", new PageViewModel<ProfilePage>(profile))
            }
</code>```

However above code returns the error:

CS0030: Cannot convert type 'Models.Pages.BlogPage' to 'Models.Pages.ProfilePage'

Can someone point me the correct way to store a list inside a model and render this nested object in a view?

Thanks!

答:
Hi Its seems that you have problem in the for each loop,but i couldn't exactly figure out the problem line, since model is not available above.

Answer to your question:

Can someone point me the correct way to store a list inside a model and render this nested object in a view?

ex:

```<code>public class somemodelname
{
    public list<anytype> somepropertyname{get;set;}

}
</code>```

accessing:

```<code>  @foreach (var singlevalueOrObj in Model.somepropertyname)
            {
            @Html.Partial("../ProfilePage/Index", new PageViewModel<singlevalueOrObj >(profile))
            }
</code>```

In the above way you can store any list object inside your model and for rendering the page as same way as you did in the above that is using the partial view.

Hope above information was helpful.

Thanks

Karthik

ContentLicense: CC BY-SA 3.0

Body:
Usin ASP.NET I am trying to add a list of profiles to a object in a model and then enumerate over this list in the view.

     public ActionResult Index(BlogPage currentPage)
    {
        var model = new BlogPageModel(currentPage);

        var pages = new List<BlogPage>();

        var profilePages = new List<ProfilePage>();
        if (currentPage.ProfileArea != null)
        {
            foreach (LinkItem linkItem in currentPage.ProfileArea)
            {
                var page = _pageDataHelper.GetPageData(linkItem);
                var profilePage = page as ProfilePage;
                if (profilePage != null)
                {
                    profilePages.Add(profilePage);
                }
            }
            model.Profiles = profilePages;
        }
        return View(model);
    }

Using this code in the view:

   @foreach (ProfilePage profile in Model.BlogPages)
            {
            @Html.Partial("../ProfilePage/Index", new PageViewModel<ProfilePage>(profile))
            }

However above code returns the error:

CS0030: Cannot convert type 'Models.Pages.BlogPage' to 'Models.Pages.ProfilePage'

Can someone point me the correct way to store a list inside a model and render this nested object in a view?

Thanks!

Body:
Hi Its seems that you have problem in the for each loop,but i couldn't exactly figure out the problem line, since model is not available above.

Answer to your question:

Can someone point me the correct way to store a list inside a model and render this nested object in a view?

ex:

public class somemodelname
{
    public list<anytype> somepropertyname{get;set;}

}

accessing:

  @foreach (var singlevalueOrObj in Model.somepropertyname)
            {
            @Html.Partial("../ProfilePage/Index", new PageViewModel<singlevalueOrObj >(profile))
            }

In the above way you can store any list object inside your model and for rendering the page as same way as you did in the above that is using the partial view.

Hope above information was helpful.

Thanks

Karthik


问:
Proper data structure for D3 stacked bar chart
I am trying to visualize this data in a stacked bar chart with D3 v4:

```<code>var data = [
   {'id': '10', 'status': 'on', 'variant': 'A', 'value': '200'},
   {'id': '10', 'status': 'on', 'variant': 'B', 'value': '500'},
   {'id': '11', 'status': 'off', 'variant': 'A', 'value': '100'},
   {'id': '12', 'status': 'on', 'variant': 'A', 'value': '600'},
   ...
]
</code>```

All elements with the same key id should stack on the x axis, where value defines the height and status defines the color.

A data set may contain multiple elements with the same id but different status or variant, like id=10 in the example.

Which  format would be suitable to stack this data? My approach was nesting it:

```<code>var nested = d3.nest()
  .key(function(d) { return d.id; })
  .entries(data);
</code>```

From here I am not sure how to generate the y0 and y1 values.
Can I use d3.stack?

答:
You could loop through the values array in each top-level object and keep a running total of value, which becomes y0 for each <rect>. y1 then is y0 + value.

Then bind each top-level object to a <g> tag representing the entire stack, translate that to the appropriate x position (assuming bars are vertical), and append <rect>s to each <g> with the values prop as data. Set the height and y position of the rect according to where in the stack it belongs. That might look like:

```<code>var groups = d3.selectAll("g")
   .data(nested)
   .enter().append("g");
groups.attr("transform","translate...");
var rects = groups.selectAll("rect")
   .data(function(d) { return d.values })
   .enter().append("rect");
rects
   .attr("width",...)
   .attr("height",...)
   .attr("y",...)
</code>```

Body:
I am trying to visualize this data in a stacked bar chart with D3 v4:

var data = [
   {'id': '10', 'status': 'on', 'variant': 'A', 'value': '200'},
   {'id': '10', 'status': 'on', 'variant': 'B', 'value': '500'},
   {'id': '11', 'status': 'off', 'variant': 'A', 'value': '100'},
   {'id': '12', 'status': 'on', 'variant': 'A', 'value': '600'},
   ...
]

All elements with the same key id should stack on the x axis, where value defines the height and status defines the color.

A data set may contain multiple elements with the same id but different status or variant, like id=10 in the example.

Which  format would be suitable to stack this data? My approach was nesting it:

var nested = d3.nest()
  .key(function(d) { return d.id; })
  .entries(data);

From here I am not sure how to generate the y0 and y1 values.
Can I use d3.stack?

Body:
You could loop through the values array in each top-level object and keep a running total of value, which becomes y0 for each <rect>. y1 then is y0 + value.

Then bind each top-level object to a <g> tag representing the entire stack, translate that to the appropriate x position (assuming bars are vertical), and append <rect>s to each <g> with the values prop as data. Set the height and y position of the rect according to where in the stack it belongs. That might look like:

var groups = d3.selectAll("g")
   .data(nested)
   .enter().append("g");
groups.attr("transform","translate...");
var rects = groups.selectAll("rect")
   .data(function(d) { return d.values })
   .enter().append("rect");
rects
   .attr("width",...)
   .attr("height",...)
   .attr("y",...)


问:
How to pass variable through ChannelExec.setCommand() method in JSch in Java?
Below is my code. Please check

```<code>ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand("sh "+ "a.sh; echo \\$No");
</code>```

a.sh is my shell script in Linux server. I need to run the script along with value of No (received as a parameter of a Java function).

However, the value of the No is not  getting passed over to my shell script.

Please help.

答:
It's a regular Java string, what you are passing to the ChannelExec.setCommand(). So use string concatenation (as you are doing already):

```<code>channelExec.setCommand("sh "+ "a.sh; echo \\" + No);
</code>```

Body:
Below is my code. Please check

ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand("sh "+ "a.sh; echo \\$No");

a.sh is my shell script in Linux server. I need to run the script along with value of No (received as a parameter of a Java function).

However, the value of the No is not  getting passed over to my shell script.

Please help.

Body:
It's a regular Java string, what you are passing to the ChannelExec.setCommand(). So use string concatenation (as you are doing already):

channelExec.setCommand("sh "+ "a.sh; echo \\" + No);


问:
Can I obtain real user ip with "iptables": false enabled?
I user "iptables": false option in docker daemon config:

```<code>/etc/docker/daemon.json:
{
  "iptables": false
}
</code>```

I run service with options --publish mode=host, --mode=global similar to this approach.

But when I get X-Real-IP header in my application its value is 172.18.0.1 but not real user ip.

When I start Docker daemon without "iptables": false in /etc/docker/daemon.json all works fine and I get real user ip.

But I need to set "iptables": false to preserve iptables changes with Docker.

Is it possible to get real user ip with "iptables": false in Docker daemon configuration?

答:
See the rules that Docker creates without "iptables": true and replicate them with "iptables": false (which is the default).

These rules in particular are needed to masquerade the IP:

iptables -t nat -A POSTROUTING -m addrtype --src-type LOCAL -o docker0 -j MASQUERADE

iptables -t nat -s 172.18.0.0/16 ! -o docker0 -j MASQUERADE

Body:
I user "iptables": false option in docker daemon config:

/etc/docker/daemon.json:
{
  "iptables": false
}

I run service with options --publish mode=host, --mode=global similar to this approach.

But when I get X-Real-IP header in my application its value is 172.18.0.1 but not real user ip.

When I start Docker daemon without "iptables": false in /etc/docker/daemon.json all works fine and I get real user ip.

But I need to set "iptables": false to preserve iptables changes with Docker.

Is it possible to get real user ip with "iptables": false in Docker daemon configuration?


问:
Broadcast data to multiple widgets in Flutter
Is there a way to broadcast data from one widget to other widgets? Similar to a BroadcastReceiver on Android or NSNotificationCenter on iOS.

Specifically, I'm trying to detect when a Navigator pops or pushes a new view. I added navigatorObservers to MaterialApp. And when a widget comes back to the foreground, I want to be able to notify it by broadcasting changes from didPush and didPop with the actual route that's in the current foreground

答:
Navigator.push returns a Future that will complete when Navigator.pop is called (and this can optionally be used to pass data back to the widget that called push). So for example suppose your login button has this onPressed handler:

```<code>onPressed: () async {
  bool isLoggedIn = await Navigator.pushNamed(context, '/login');
  if (isLoggedIn) {
    // do something
  }
}
</code>```

When your login page calls Navigator.pop(true), the Future will complete with a value of true which will be assigned to the isLoggedIn variable. (You'll get null if the user uses the back button to return to the previous screen.)

This is how showDialog works as well.

Body:
Navigator.push returns a Future that will complete when Navigator.pop is called (and this can optionally be used to pass data back to the widget that called push). So for example suppose your login button has this onPressed handler:

onPressed: () async {
  bool isLoggedIn = await Navigator.pushNamed(context, '/login');
  if (isLoggedIn) {
    // do something
  }
}

When your login page calls Navigator.pop(true), the Future will complete with a value of true which will be assigned to the isLoggedIn variable. (You'll get null if the user uses the back button to return to the previous screen.)

This is how showDialog works as well.


问:
Get Locale from session object
I am noob and want to make internationalization for a spring boot app. This is what I have tried but can not get it to work :

```<code>@SpringBootApplication
public class CarriersApplication extends WebMvcConfigurerAdapter {

@Autowired WebContextHolder webContextHolder;

public static void main(String[] args) {
    SpringApplication.run(CarriersApplication.class, args);
}

@Bean
public RestTemplate createRestTemplate() {
    return new RestTemplate();
}

@Bean
public LocaleResolver localeResolver() {

    HttpSession session = webContextHolder.getSession();
    String lang = ((Merchant) session.getAttribute( "principal" )).getLanguage();

    // the code above is an attempt to get language from session object to set the
     // default locale
    // ex: lang = en,fr

    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale( new Locale( lang) );
    return slr;

}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor( localeChangeInterceptor());
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}
}
</code>```

My question is: Is there a possibility to get the locale from 'principal' session object in this manner, when I define localeResolver() method?

答:
You can get the locale from LocaleContextHolder as folows :</p>

```<code>@Bean
public LocaleResolver localeResolver() {
    Locale locale = LocaleContextHolder.getLocale();
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(locale);
    return slr;

}
</code>```

Title: Get Locale from session object

Body:
I am noob and want to make internationalization for a spring boot app. This is what I have tried but can not get it to work :

@SpringBootApplication
public class CarriersApplication extends WebMvcConfigurerAdapter {

@Autowired WebContextHolder webContextHolder;

public static void main(String[] args) {
    SpringApplication.run(CarriersApplication.class, args);
}

@Bean
public RestTemplate createRestTemplate() {
    return new RestTemplate();
}

@Bean
public LocaleResolver localeResolver() {

    HttpSession session = webContextHolder.getSession();
    String lang = ((Merchant) session.getAttribute( "principal" )).getLanguage();

    // the code above is an attempt to get language from session object to set the
     // default locale
    // ex: lang = en,fr

    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale( new Locale( lang) );
    return slr;

}

@Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
    LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
    lci.setParamName("lang");
    return lci;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor( localeChangeInterceptor());
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}
}

My question is: Is there a possibility to get the locale from 'principal' session object in this manner, when I define localeResolver() method?

Body:
You can get the locale from LocaleContextHolder as folows :

@Bean
public LocaleResolver localeResolver() {
    Locale locale = LocaleContextHolder.getLocale();
    SessionLocaleResolver slr = new SessionLocaleResolver();
    slr.setDefaultLocale(locale);
    return slr;

}


问:
How Do I Combine Multiple SQL Queries?
I'm having some trouble figuring out any way to combine two SQL queries into a single one that expresses some greater idea.

For example, let's say that I have query A, and query B. Query A returns the total number of hours worked. Query B returns the total number of hours that were available for workers to work. Each one of these queries returns a single column with a single row.

What I really want, though, is essentially query A over query B. I want to know the percentage of capacity that was worked.

I know how to write query A and B independently, but my problem comes when I try to figure out how to use those prewritten queries to come up with a new SQL query that uses them together. I know that, on a higher level, like say in a report, I could just call both queries and then divide them, but I'd rather encompass it all into a single SQL query.

What I'm looking for is a general idea on how to combine these queries using SQL.

Thanks!

答:
You can declare variables to store the results of each query and return the difference:</p>

```<code>DECLARE @first INT
DECLARE @second INT

SET @first = SELECT val FROM Table...
SET @second = SELECT val FROM Table...

SELECT @first - @second
</code>```

ContentLicense: CC BY-SA 2.5

Title: How Do I Combine Multiple SQL Queries?

Body:
You can declare variables to store the results of each query and return the difference:

DECLARE @first INT
DECLARE @second INT

SET @first = SELECT val FROM Table...
SET @second = SELECT val FROM Table...

SELECT @first - @second


问:
How to properly put a Uri from a local file into a Intent
I want my local image file (located at res/drawable) to be converted to a Uri, so I can put it into a Intent to start an Activity.

This is what I got until now:

```<code>    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.setType("image/*");

    Uri uri = Uri.fromFile(new File("/res/drawable/photo.jpg"));
    sendIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.share)));
</code>```

Then, the activity that receives this intent, displays the image in a ImageView. Something like this:

```<code>    Uri imageUri = (Uri) getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    ImageView myImage = (ImageView) findViewById(R.id.imageView_receive);
    myImage.setImageBitmap(bitmap);
</code>```

But instead of displaying the image, it throws an java.io.FileNotFoundException

```<code>java.io.FileNotFoundException: No resource found for: android.resource://com.my.package/drawable/photo.jpg
</code>```

I searched and tried other ways to get a Uri through my file:

```<code>    Uri uri = Uri.parse("file:///res/drawable/photo.jpg");
    Uri uri = Uri.parse("android.resource://com.my.package/drawable/photo.jpg");
</code>```

But all of them returned the same error for me.

Why is my image not being recognized?

答:
I want my local image file (located at res/drawable) to be converted to a Uri, so I can put it into a Intent to start an Activity.

Resources are files on your developer machine. They are not files on the device.

This is what I got until now

That will not work, as AFAIK there are zero Android devices with a /res directory off of the filesystem root, and your drawable resources would not be there anyway.

Why is my image not being recognized?

Your third one (android.resource scheme) is the closest. Get rid of the .jpg extension.

However, many third-party apps will not recognize that scheme. And, if you are implementing the activity that is to handle this request, I have no idea why you are using ACTION_SEND. If your objective is to only work within your own app, skip the Uri, package the drawable resource ID (R.drawable.photo) as an int extra, and have your other activity use that resource ID more naturally (e.g., setImageResource() on the ImageView).

Body:
I want my local image file (located at res/drawable) to be converted to a Uri, so I can put it into a Intent to start an Activity.

This is what I got until now:

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.setType("image/*");

    Uri uri = Uri.fromFile(new File("/res/drawable/photo.jpg"));
    sendIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(sendIntent, getResources().getText(R.string.share)));

Then, the activity that receives this intent, displays the image in a ImageView. Something like this:

    Uri imageUri = (Uri) getIntent().getParcelableExtra(Intent.EXTRA_STREAM);
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
    ImageView myImage = (ImageView) findViewById(R.id.imageView_receive);
    myImage.setImageBitmap(bitmap);

But instead of displaying the image, it throws an java.io.FileNotFoundException

java.io.FileNotFoundException: No resource found for: android.resource://com.my.package/drawable/photo.jpg

I searched and tried other ways to get a Uri through my file:

    Uri uri = Uri.parse("file:///res/drawable/photo.jpg");
    Uri uri = Uri.parse("android.resource://com.my.package/drawable/photo.jpg");

But all of them returned the same error for me.

Why is my image not being recognized?


问:
MATLAB: How to count number frequency columnwise, in continuous blocks
I have a matrix a in Matlab that looks like the following:

```<code>a = zeros(10,3);
a(3:6,1)=2; a(5:9,3)=1; a(5:7,2)=3; a(8:10,1)=2;

a =
 0     0     0
 0     0     0
 2     0     0
 2     0     0
 2     3     1
 2     3     1
 0     3     1
 2     0     1
 2     0     1
 2     0     0
</code>```

I would like to obtain a cell array with the number of times that each number appears in a column. Also, it should be ordered depending on the element value, regardless of the column number. In the example above I would like to obtain the cell:

```<code>b = {[5],[4,3],[3]}
</code>```

Because the number 1 appears once for 5 times, the number 2 twice in blocks of 4 and 3, and the number 3 once for 3 times. As you can see the recurrences are ordered according to the element value and not to the number of the column where the elements appear.

答:
```<code>b = {}
for i = 1:ncolumns
    for n = 1:nnumbers
        b{i}(n) = sum(a(:,i) == n)
    end
end
</code>```

<p>(Note that this places zeros for numbers at which the count is 0, but otherwise I don't see how else you would be able to recognize which value is being counted)</p>

Body:
I have a matrix a in Matlab that looks like the following:

a = zeros(10,3);
a(3:6,1)=2; a(5:9,3)=1; a(5:7,2)=3; a(8:10,1)=2;

a =
 0     0     0
 0     0     0
 2     0     0
 2     0     0
 2     3     1
 2     3     1
 0     3     1
 2     0     1
 2     0     1
 2     0     0

I would like to obtain a cell array with the number of times that each number appears in a column. Also, it should be ordered depending on the element value, regardless of the column number. In the example above I would like to obtain the cell:

b = {[5],[4,3],[3]}

Because the number 1 appears once for 5 times, the number 2 twice in blocks of 4 and 3, and the number 3 once for 3 times. As you can see the recurrences are ordered according to the element value and not to the number of the column where the elements appear.

Body:
b = {}
for i = 1:ncolumns
    for n = 1:nnumbers
        b{i}(n) = sum(a(:,i) == n)
    end
end

(Note that this places zeros for numbers at which the count is 0, but otherwise I don't see how else you would be able to recognize which value is being counted)


问:
WinInet FTP switch Passive to Active mode while connected?
I use WinInet to connect to an FTP server.  I use FtpCommand() to send a "PASV" command to switch from Active to Passive mode.  I am now searching for the opposite command to switch from Passive to Active mode.  Does anyone know how to do this?

答:
Active mode is enabled by sending a PORT (or EPRT) command instead of sending a PASV (or EPSV) command.  PORT/EPRT tells the server which IP/port it needs to actively connect to on your system.

If you want to understand how the FTP protocol works, I suggest you read the FTP specification, RFC 959, and its various extensions, particularly RFC 2428 and RFC 3659.

In WinInet, the transfer mode is typically established at the beginning of the session when you call InternetConnect() or InternetOpenUrl(). If you specify the INTERNET_FLAG_PASSIVE flag, it forces Passive mode. If you do not specify the flag, the mode is determined by the user's default Internet Options. This mode allows the FtpGetFile()/FtpPutFile() and FtpFindFirstFile()/InternetFindNextFile() functions to operate over their own data connections.  Once the mode is established for a session, it cannot be changed, AFAIK.

However, you can use FtpCommand() to send any FTP command manually, including PASV/EPSV and PORT/EPRT.  If you set the fExpectResponse parameter to TRUE, the phFtpCommand output parameter will give you a new HINTERNET handle if a data socket is created.  You can use that handle with InternetReadFile() and InternetWriteFile() to transfer files and directory listings over that data connection.


问:
Why use spread operator in Redux store?
In this tutorial, why is there a spread operator before createStore?

```<code>const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware();
  return {
    ...createStore(rootReducer,
      applyMiddleware(sagaMiddleware)),
    runSaga: sagaMiddleware.run(rootSaga)
  };
};
</code>```

答: It appears that that example is trying to add an additional field to the store object, so that you can call store.runSaga().  To be honest, the spread/copy is totally unnecessary - you can just do store.runSaga = sagaMiddleware.run.

Title: Why use spread operator in Redux store?

Body:
In this tutorial, why is there a spread operator before createStore?

const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware();
  return {
    ...createStore(rootReducer,
      applyMiddleware(sagaMiddleware)),
    runSaga: sagaMiddleware.run(rootSaga)
  };
};


问:
Combine multiple XML files with PHP and wrap in new root element
I'm trying to combine multiple XML files that have the same structure into one file.

This is the structure of my XML files:

file1.xml:

```<code><root information="file1">
 <items>
  <item>FOO</item>
  <item>BAR</item>
 </items>
</root>
</code>```

file2.xml:

```<code><root information="file2">
 <items>
  <item>BAR</item>
  <item>FOO</item>
 </items>
</root>
</code>```

Using this code I've been able to combine them:

```<code>$files= array(
  'file1.xml',
  'file2.xml'
);

$dom = new DOMDocument();
$dom->appendChild($dom->createElement('root'));

foreach ($files as $filename) {
  $addDom = new DOMDocument();

  $addDom->load($filename);
  if ($addDom->documentElement) {
    foreach ($addDom->documentElement->childNodes as $node) {
      $dom->documentElement->appendChild(
        $dom->importNode($node, TRUE)
      );

    }

  }
}

$dom->save('output.xml');
</code>```

This works partly but removes the original root element which has the information attribute that I still need. So I would like to keep all the existing root elements but wrap them in a new root  element. This is what I would like to end up with:

```<code><files>
 <root information="file1">
  <items>
   <item>FOO</item>
   <item>BAR</item>
  </items>
 </root>
 <root information="file2">
  <items>
   <item>BAR</item>
   <item>FOO</item>
  </items>
 </root>
</files>
</code>```

But I can't figure out how to append the file. Whatever I try it only ends up at the bottom of the output file instead of appending all old root elements. I'm guessing this is simple as hell but I just can't figure it out. Help much appreciated!

答:
Actually your source only has some minor mistakes. You create a root document element in the target document, not the files element in you example. Additionally your copy of the nodes in the source documents is a level to deep, you just need to import their document elements.

I modified your code a little to make it self contained and fixed the mistakes.

```<code>$files= array(
  'file1.xml' =>
'<root information="file1">
 <items>
  <item>FOO</item>
  <item>BAR</item>
 </items>
</root>',
  'file2.xml' =>
'<root information="file2">
 <items>
  <item>BAR</item>
  <item>FOO</item>
 </items>
</root>'
);

// create a target document with a files root
$target = new DOMDocument();
$target->appendChild($target->createElement('files'));

// iterate the source files array
foreach ($files as $name => $content) {
  // load each source
  $source = new DOMDocument();
  $source->loadXml($content);
  // if it has a document element
  if ($source->documentElement) {
    // copy it to the target document
    $target->documentElement->appendChild(
      $target->importNode($source->documentElement, TRUE)
    );
  }
}

$target->formatOutput = TRUE;
echo $target->saveXml();
</code>```

Body:
I'm trying to combine multiple XML files that have the same structure into one file.

This is the structure of my XML files:

file1.xml:

<root information="file1">
 <items>
  <item>FOO</item>
  <item>BAR</item>
 </items>
</root>

file2.xml:

<root information="file2">
 <items>
  <item>BAR</item>
  <item>FOO</item>
 </items>
</root>

Using this code I've been able to combine them:

$files= array(
  'file1.xml',
  'file2.xml'
);

$dom = new DOMDocument();
$dom->appendChild($dom->createElement('root'));

foreach ($files as $filename) {
  $addDom = new DOMDocument();

  $addDom->load($filename);
  if ($addDom->documentElement) {
    foreach ($addDom->documentElement->childNodes as $node) {
      $dom->documentElement->appendChild(
        $dom->importNode($node, TRUE)
      );

    }

  }
}

$dom->save('output.xml');

This works partly but removes the original root element which has the information attribute that I still need. So I would like to keep all the existing root elements but wrap them in a new root  element. This is what I would like to end up with:

<files>
 <root information="file1">
  <items>
   <item>FOO</item>
   <item>BAR</item>
  </items>
 </root>
 <root information="file2">
  <items>
   <item>BAR</item>
   <item>FOO</item>
  </items>
 </root>
</files>

But I can't figure out how to append the file. Whatever I try it only ends up at the bottom of the output file instead of appending all old root elements. I'm guessing this is simple as hell but I just can't figure it out. Help much appreciated!

Body:
Actually your source only has some minor mistakes. You create a root document element in the target document, not the files element in you example. Additionally your copy of the nodes in the source documents is a level to deep, you just need to import their document elements.

I modified your code a little to make it self contained and fixed the mistakes.

$files= array(
  'file1.xml' =>
'<root information="file1">
 <items>
  <item>FOO</item>
  <item>BAR</item>
 </items>
</root>',
  'file2.xml' =>
'<root information="file2">
 <items>
  <item>BAR</item>
  <item>FOO</item>
 </items>
</root>'
);

// create a target document with a files root
$target = new DOMDocument();
$target->appendChild($target->createElement('files'));

// iterate the source files array
foreach ($files as $name => $content) {
  // load each source
  $source = new DOMDocument();
  $source->loadXml($content);
  // if it has a document element
  if ($source->documentElement) {
    // copy it to the target document
    $target->documentElement->appendChild(
      $target->importNode($source->documentElement, TRUE)
    );
  }
}

$target->formatOutput = TRUE;
echo $target->saveXml();


问:
TYPO3 v6.2.x Tutorials for beginners
I  decided to learning TYPO3 v6.2.x CMS,I installed CMS on local server  but I can't create some basic  template, after long searching in google and here on stackoverflow, I can't find  any useful tutorials or books for beginners.

I need only tutorials  where explained how to create basic template  with TYPO3 CMS v6.x.x or maybe in "github" is some basic start kit with basic template?.

I hope some kind  people suggest me  how  and where to start.
Please don't be lazy, it`s very important for me :).

答:
My decision is to have a look on tutorial videos.

As said before, you should start at least with 7.6 LTS, so you start learning the way typo3 goes to future.

Start a small project using the "introduction package" which you can install via extensions->distributions.

The take a look at the backend & fronted and ask you questions, as they appear.

Title: TYPO3 v6.2.x Tutorials for beginners


问:
How do i run multiple Jenkins Pipelines in parallel and send environment variables to each?
I have multiple clients, all who need the same pipeline run but with different variables. My idea would be to do this:

Have a pipeline that does everything needed to build/package/deploy/verify for a client - and that takes env variables

Have a way to call that pipeline and pass it env variables at runtime

Have a way to call that pipeline multiple times with diff env variables but with one call (maybe a pipeline that loops over an array of variables)

How would I achieve this?

答:
There are a couple of approaches - it depends on your use case which fits best. From the top of my head:

Create a pipeline job with parameters and trigger it manually/or per api for each client. A sample taken from https://jenkins.io/doc/book/pipeline/syntax/#declarative-directives :

```<code>pipeline {
    agent any
    parameters {
        string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
    }
    stages {
        stage('Example') {
            steps {
                echo "Hello ${params.PERSON}"
            }
        }
    }
}
</code>```

Have one pipeline job that triggers another pipeline job (once for each client) also using parameters. The parent job can have a stage for each client:

```<code>stage ('Build client A') {
    build job: 'common-pipeline-job-for-clients',
        parameters: [string(name: 'param1', value: 'some value')]
}
</code>```

Create a pipeline template and use the template to create a pipeline for each client - as described here: Jenkins pipeline template

Body:
There are a couple of approaches - it depends on your use case which fits best. From the top of my head:

Create a pipeline job with parameters and trigger it manually/or per api for each client. A sample taken from https://jenkins.io/doc/book/pipeline/syntax/#declarative-directives :

pipeline {
    agent any
    parameters {
        string(name: 'PERSON', defaultValue: 'Mr Jenkins', description: 'Who should I say hello to?')
    }
    stages {
        stage('Example') {
            steps {
                echo "Hello ${params.PERSON}"
            }
        }
    }
}

Have one pipeline job that triggers another pipeline job (once for each client) also using parameters. The parent job can have a stage for each client:

stage ('Build client A') {
    build job: 'common-pipeline-job-for-clients',
        parameters: [string(name: 'param1', value: 'some value')]
}

Create a pipeline template and use the template to create a pipeline for each client - as described here: Jenkins pipeline template


问:
TypeError: Value passed to parameter 'a' has DataType not in list of allowed values
I have the following code:

```<code>_X = np.arange(1, 7).reshape((2, 3))
_Y = np.arange(1, 7).reshape((3, 2))

X = tf.convert_to_tensor(_X)
Y = tf.convert_to_tensor(_Y)

# Matrix multiplication
out1 = tf.matmul(X, Y)
</code>```

For it, I am getting this error:

```<code>TypeError: Value passed to parameter 'a' has DataType int64 not in list of allowed values: float16, float32, float64, int32, complex64, complex128
</code>```

I am using the latest version of Tensorflow. What could be the issue?

答:
Inputs to tf.matmul accepts only these dtypes :

```<code>a: Tensor of type float16, float32, float64, int32, complex64, complex128 and rank > 1.
</code>```

Changing dtype of X and Y to above dtypes works.

```<code>import tensorflow as tf
import numpy as np
_X = np.arange(1, 7).reshape((2, 3))
_Y = np.arange(1, 7).reshape((3, 2))

X = tf.convert_to_tensor(_X,dtype=tf.int32)
Y = tf.convert_to_tensor(_Y,dtype=tf.int32)

# Matrix multiplication
out1 = tf.matmul(X, Y)

sess = tf.Session()
print(sess.run(out1))
</code>```

Body:
I have the following code:

_X = np.arange(1, 7).reshape((2, 3))
_Y = np.arange(1, 7).reshape((3, 2))

X = tf.convert_to_tensor(_X)
Y = tf.convert_to_tensor(_Y)

# Matrix multiplication
out1 = tf.matmul(X, Y)

For it, I am getting this error:

TypeError: Value passed to parameter 'a' has DataType int64 not in list of allowed values: float16, float32, float64, int32, complex64, complex128

I am using the latest version of Tensorflow. What could be the issue?

Body:
Inputs to tf.matmul accepts only these dtypes :

a: Tensor of type float16, float32, float64, int32, complex64, complex128 and rank > 1.

Changing dtype of X and Y to above dtypes works.

import tensorflow as tf
import numpy as np
_X = np.arange(1, 7).reshape((2, 3))
_Y = np.arange(1, 7).reshape((3, 2))

X = tf.convert_to_tensor(_X,dtype=tf.int32)
Y = tf.convert_to_tensor(_Y,dtype=tf.int32)

# Matrix multiplication
out1 = tf.matmul(X, Y)

sess = tf.Session()
print(sess.run(out1))


问:
Should I keep the Apple Developer Team ID secret?
Is it safe for me to post the Apple Team ID to a public forum (as in, for example, somebody is helping me to troubleshoot an issue and I post my .mobileprovision file, or a generated entitlements file that contains the team id, or I paste snippets of these to Stack Overflow)? Or should I obfuscate it first?</p>

答:
It probably doesn't matter. This information is generally obtainable in some cases anyway. For instance, to support certain web integrations, an app's site must host a apple-app-site-association file with all of the related apps and their bundle ids/ team ids listed.

For example, here is Facebook's:

https://www.facebook.com/apple-app-site-association


问:
Give HTTPS Proxies
OK, as admins requested it, i refine my question:

i am searching for local Proxie solutions which can tweak HTTPS / HST websites. They should be able to tweak the content and the headers of the site. Do you know such Proxies? I would prefer Python solutions because they are hackable.

Yes, there are solutions which work with Browser plugins, and i have posted an answer containing an example using Yarip, but the problem is: As soon as the Browser developers decide to remove APIs, not that anyone would do that, the Plugin stops working.

Therefore i want to have a solution which works on the protocol level. So, which Proxies can do that, tweak HTTPS / HST websites? I dont care for performance, my internet is slow anyway and im not in a hurry. Please also give a small example how to tweak the content of the website and a small example how to tweak a header, using your solution.

Hopefully my question is clear now.

答:
Ok, here is my solution to this problem. AJAX with bottle.py and the jQuery Docs were helpful.

Use Firefox (Developer Edition), version 52. Later versions of Firefox do not support Yarip, which is my approach to inject Javascript into the document and to tweak the Content-Security-Policy response header, if there is one. I am interested in solutions for later Firefoxes/Chromes/whatever.

Stop Firefox from blocking mixed content (loading http resources from https sites). Which is nonsense on localhost. According to this Discussion and this Wiki Entry, starting with Firefox 55 localhost is finally whitelisted by default. However, as i need Yarip and therefore can not use Firefox 55, i still need to manually disable this policy.
This can be done globally by setting about.config -> security.mixed_content.block_active_content to false which is lazy and veery dangerous, as it affects every website, or by doing it temporarily per-page which is not so lazy but a little bit less dangerous.

Install Python 3

pip install bottle

Create a file server.py with the following contents:

    import os, json
    from bottle import request, response, route, static_file, debug, run

    @route('/inc') # this handles the ajax calls
    def inc():
        # only needed when you pass parameters to the ajax call.
        response.set_header('Access-Control-Allow-Origin', '*')

        number = request.params.get('number', 0, type=int)
        return json.dumps({'increased_number': number + 1})

    @route('/static/<filename:path>') # this serves the two static javascript files
    def send_static(filename):
        return static_file(filename, root=os.path.dirname(__file__))

    debug(True)
    run(port=9030, reloader=True)
```

<ul>
<li><p>Run it</p></li>
<li><p>Put a copy of <em>jquery.js</em> into the same directory</p></li>
<li><p>Create a file <em>logic.js</em> in the same directory with the following contents:</p></li>
</ul>

<pre class="lang-js prettyprint-override"><code>    // http://api.jquery.com/jQuery.noConflict/
    var my = {};
    my.$ = $.noConflict(true);

    // http://api.jquery.com/ready/
    my.$(function() {
        var target = my.$(
            '<div id="my-ajax-result" style="position:absolute; padding:1em; background:'
            + 'white; cursor:pointer; border:3px solid blue; z-index:999;">0</div>'
        );
        my.$('body').prepend(target);

        function ajaxcall(){
            // http://api.jquery.com/jQuery.getJSON/
            my.$.getJSON(
                "http://localhost:9030/inc",
                {
                    number : target.text() // parameters
                },
                function(result) {
                    target.text(result.increased_number);
                }
            );
        }

        // http://api.jquery.com/click/
        target.click(function(event) {
            ajaxcall();
            return false;
        });

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

Install Yarip

Save the following xml to a file and, from Yarips manage pages dialog import it. This should create a new rule for en.wikipedia.org. Im too lazy now to explain how yarip works, but it is worth learning it. This rule will inject the jquery.js and the logic.js at the end of body and it will tweak the Content-Security-Policy response header, if there is one.

    <?xml version="1.0" encoding="UTF-8"?>
    <yarip version="0.3.5">
        <page id="{56b07a5d-e2df-41f2-9ca8-34b4ecb04af8}" name="wikipedia.org" allowScript="true" created="1496845936929">
            <page>

                    <response>
                        <item created="1496845998973">
                            <regexp flags="i"><![CDATA[.*wikipedia\.org.*]]></regexp>
                            <name><![CDATA[Content-Security-Policy]]></name>

                        </item>
                    </response>

                <stream>
                    <item created="1496845985382">
                        <regexp flags="i"><![CDATA[.*wikipedia\.org.*]]></regexp>
                        <stream_regexp flags="gim"><![CDATA[]]></stream_regexp>
                        ';
    }
    ]]></script>
                    </item>
                </stream>
            </page>
        </page>
    </yarip>
```

Make sure that yarip is enabled

Navigate to en.wikipedia.org. You should see a blue rectangle top left, with a number in it. If you click on it, an ajax call to localhost will be made and the contents of the blue rectangle will be replaced with the result result of that call – the number increased by 1. Screenshot:

Play around with this and tweak the web the way you want, including HTTPS sites. Have read/write access to your computer using the Python. Eat this, Firefox Nanny devs.

Title: Give HTTPS Proxies

Body:
Ok, here is my solution to this problem. AJAX with bottle.py and the jQuery Docs were helpful.

Use Firefox (Developer Edition), version 52. Later versions of Firefox do not support Yarip, which is my approach to inject Javascript into the document and to tweak the Content-Security-Policy response header, if there is one. I am interested in solutions for later Firefoxes/Chromes/whatever.

Stop Firefox from blocking mixed content (loading http resources from https sites). Which is nonsense on localhost. According to this Discussion and this Wiki Entry, starting with Firefox 55 localhost is finally whitelisted by default. However, as i need Yarip and therefore can not use Firefox 55, i still need to manually disable this policy.
This can be done globally by setting about.config -> security.mixed_content.block_active_content to false which is lazy and veery dangerous, as it affects every website, or by doing it temporarily per-page which is not so lazy but a little bit less dangerous.

Install Python 3

pip install bottle

Create a file server.py with the following contents:

    import os, json
    from bottle import request, response, route, static_file, debug, run

    @route('/inc') # this handles the ajax calls
    def inc():
        # only needed when you pass parameters to the ajax call.
        response.set_header('Access-Control-Allow-Origin', '*')

        number = request.params.get('number', 0, type=int)
        return json.dumps({'increased_number': number + 1})

    @route('/static/<filename:path>') # this serves the two static javascript files
    def send_static(filename):
        return static_file(filename, root=os.path.dirname(__file__))

    debug(True)
    run(port=9030, reloader=True)

Run it

Put a copy of jquery.js into the same directory

Create a file logic.js in the same directory with the following contents:

    // http://api.jquery.com/jQuery.noConflict/
    var my = {};
    my.$ = $.noConflict(true);

    // http://api.jquery.com/ready/
    my.$(function() {
        var target = my.$(
            '<div id="my-ajax-result" style="position:absolute; padding:1em; background:'
            + 'white; cursor:pointer; border:3px solid blue; z-index:999;">0</div>'
        );
        my.$('body').prepend(target);

        function ajaxcall(){
            // http://api.jquery.com/jQuery.getJSON/
            my.$.getJSON(
                "http://localhost:9030/inc",
                {
                    number : target.text() // parameters
                },
                function(result) {
                    target.text(result.increased_number);
                }
            );
        }

        // http://api.jquery.com/click/
        target.click(function(event) {
            ajaxcall();
            return false;
        });

        ajaxcall();
    });

Install Yarip

Save the following xml to a file and, from Yarips manage pages dialog import it. This should create a new rule for en.wikipedia.org. Im too lazy now to explain how yarip works, but it is worth learning it. This rule will inject the jquery.js and the logic.js at the end of body and it will tweak the Content-Security-Policy response header, if there is one.

    <?xml version="1.0" encoding="UTF-8"?>
    <yarip version="0.3.5">
        <page id="{56b07a5d-e2df-41f2-9ca8-34b4ecb04af8}" name="wikipedia.org" allowScript="true" created="1496845936929">
            <page>
                <header>
                    <response>
                        <item created="1496845998973">
                            <regexp flags="i"><![CDATA[.*wikipedia\.org.*]]></regexp>
                            <name><![CDATA[Content-Security-Policy]]></name>
                            <script><![CDATA[function (value) {
        return "Content-Security-Policy: connect-src *";
    }]]></script>
                        </item>
                    </response>
                </header>
                <stream>
                    <item created="1496845985382">
                        <regexp flags="i"><![CDATA[.*wikipedia\.org.*]]></regexp>
                        <stream_regexp flags="gim"><![CDATA[</body>]]></stream_regexp>
                        <script><![CDATA[function (match, p1, offset, string) {
        return '<script type="text/javascript" src="http://localhost:9030/static/jquery.js"></script><script type="text/javascript" src="http://localhost:9030/static/logic.js"></script></body>';
    }
    ]]></script>
                    </item>
                </stream>
            </page>
        </page>
    </yarip>

Make sure that yarip is enabled

Navigate to en.wikipedia.org. You should see a blue rectangle top left, with a number in it. If you click on it, an ajax call to localhost will be made and the contents of the blue rectangle will be replaced with the result result of that call – the number increased by 1. Screenshot:

Play around with this and tweak the web the way you want, including HTTPS sites. Have read/write access to your computer using the Python. Eat this, Firefox Nanny devs.


问:
Why does this recursive peak filter written in Java not filter the chosen frequency
So, I don't know whether I've implemented this incorrectly, or whether it's a feature of this kind of filter; but, I'd been trying to apply a peak filter to an audio signal and it wasn't working.
Some testing revealed that it wasn't filtering for the frequency I selected; but a nearby value, some of which are powers of 2, so, eg, filtering 4KHz actually filtered 4096Hz.
Here's the filter (it's from http://dspguide.com/ch19/3.htm):
SAMPLE_RATE is 88*1024

```<code>        class Coefficients {
        double a0=0;
        double a1=0;
        double a2=0;
        double twoCos2piFreq=0;
        double b1=0;
        double b2=0;
        double K=0;
        double R=0;
        double rSquared=0;

        public Coefficients(double freq, double bandwidth)
        {
            twoCos2piFreq=2*Math.cos(2*Math.PI*freq);
            R=1-(3*bandwidth);
            rSquared=R*R;
            K=(1-(R*twoCos2piFreq)+rSquared)/(2-twoCos2piFreq);
            b1=R*twoCos2piFreq;
            b2=-rSquared;
        }
        // ----------------------------------------------------------------
        // Source x, result y
        // y[i]=a0*x[i] + a1*x[i-1] + a2*x[i-2] + b1*y[i-1] + b2*y[i-2]
        private void recursiveFilter(float[] x, float[] y)
        {
        double x_2 = 0.0f;                    // delayed x, y samples
        double x_1 = 0.0f;
        double y_2 = 0.0f;
        double y_1 = 0.0f;

            for (int i = 0; i < x.length; ++i){
                double xi=x[i];
                double yi=a0*xi + a1*x_1 + a2*x_2 + b1*y_1 + b2*y_2;
                x_2 = x_1;                              // shift delayed x, y samples
                y_2 = y_1;
                x_1 = xi;
                y_1 = yi;
                y[i] = (float)yi;
            }
        }
        // ------------------------------------------------------------
        public float[] filtered(float[] signal)
        {
            float[] result=new float[signal.length];
            recursiveFilter(signal,result);
            return result;
        }
    }
        // ----------------------------------------------------------------
    class BandPassCoefficients extends Coefficients
    {
        public BandPassCoefficients(double freq, double bandwidth)
        {
            super(freq/(double)SAMPLE_RATE,bandwidth/(double)SAMPLE_RATE);
            a0=1-K;
            a1=(K-R)*twoCos2piFreq;
            a2=rSquared-K;
        }
    }
</code>```

and to test it, I fill a buffer with a sine wave of a range of frequencies, one at a time, apply the filter and measure the highest amplitude in the result.
Fairly obvious code, but here it is:

```<code>        // ----------------------------------------------------------------
    private void genTestSignal(float freq)
    {
        float[]  leftSignal=createSinWaveBuffer(freq,ONE_SECOND);
        float[] rightSignal=createSinWaveBuffer(freq,ONE_SECOND);
        denormalise( leftSignal ,inputSignal, LEFT_CHANNEL);
        denormalise(rightSignal,inputSignal,RIGHT_CHANNEL);
    }
</code>```

The denormalise and normalise functions just convert to and from interleaved signed 16-bit values to single channel floats.
This samples the start of the signal, to find the largest absolute magnitude:

```<code>        private void findOptimalFreq(float[] signal, float freq)
    {
        float maxAmplitude=0;
        int peak=0;
        for(int i=(int)freq/2; i<(int)freq*3/2; i+=2){
            BandPassCoefficients signalFilter=new BandPassCoefficients(i,10);
            float[] normalised=signalFilter.filtered(signal);
            float loudest=0;
            // only scan the first part, since it's all the same
            for(int j=1; j<10000; ++j){
                float s=Math.abs(normalised[j]);
                if(s>loudest) loudest=s;
            }
            if(loudest>maxAmplitude){
                maxAmplitude=loudest;
                peak=i;
            }
        }
        log("freq,"+freq+","+peak);
    }
</code>```

And, for completion, the code which steps through the audio range, testing each frequency.

```<code>                for(workingFreq=100; workingFreq<20000; workingFreq+=100){
                genTestSignal(workingFreq);
                inputShorts=new short[inputSignal.length/2];
                ByteBuffer.wrap(inputSignal).order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(inputShorts);
                findOptimalFreq(normalised(inputShorts,RIGHT_CHANNEL),workingFreq);
            }
</code>```

The output is logged to System.out, and copied to a spreadsheet, since it's CSV format.
Here's some of it, the left is the target frequency, the right is the actual frequency which the peak is at:

```<code>6200,6436
6300,6436
6400,6436
6500,6932
6600,6932
6700,6932
6800,6932
6900,6932
7000,7510
7100,7510
7200,7510
7300,7510
7400,7510
7500,7510
7600,8192
7700,8192
7800,8192
7900,8192
8000,8192
8100,8192
8200,9012
8300,9012
</code>```

Any thoughts?
I've gone through the filter code over and over, and I'm fairly sure it's right; but there's no mention anywhere I've seen of this kind of "feature", so I don't know what to do next.

答:
Didn't solve the problem; but was able to replace it with a BiQuadratic filter from this site: BiQuadDesigner

There is a link to java source:

HTH anyone else struggling with this.

Body:
So, I don't know whether I've implemented this incorrectly, or whether it's a feature of this kind of filter; but, I'd been trying to apply a peak filter to an audio signal and it wasn't working.
Some testing revealed that it wasn't filtering for the frequency I selected; but a nearby value, some of which are powers of 2, so, eg, filtering 4KHz actually filtered 4096Hz.
Here's the filter (it's from http://dspguide.com/ch19/3.htm):
SAMPLE_RATE is 88*1024

        class Coefficients {
        double a0=0;
        double a1=0;
        double a2=0;
        double twoCos2piFreq=0;
        double b1=0;
        double b2=0;
        double K=0;
        double R=0;
        double rSquared=0;

        public Coefficients(double freq, double bandwidth)
        {
            twoCos2piFreq=2*Math.cos(2*Math.PI*freq);
            R=1-(3*bandwidth);
            rSquared=R*R;
            K=(1-(R*twoCos2piFreq)+rSquared)/(2-twoCos2piFreq);
            b1=R*twoCos2piFreq;
            b2=-rSquared;
        }
        // ----------------------------------------------------------------
        // Source x, result y
        // y[i]=a0*x[i] + a1*x[i-1] + a2*x[i-2] + b1*y[i-1] + b2*y[i-2]
        private void recursiveFilter(float[] x, float[] y)
        {
        double x_2 = 0.0f;                    // delayed x, y samples
        double x_1 = 0.0f;
        double y_2 = 0.0f;
        double y_1 = 0.0f;

            for (int i = 0; i < x.length; ++i){
                double xi=x[i];
                double yi=a0*xi + a1*x_1 + a2*x_2 + b1*y_1 + b2*y_2;
                x_2 = x_1;                              // shift delayed x, y samples
                y_2 = y_1;
                x_1 = xi;
                y_1 = yi;
                y[i] = (float)yi;
            }
        }
        // ------------------------------------------------------------
        public float[] filtered(float[] signal)
        {
            float[] result=new float[signal.length];
            recursiveFilter(signal,result);
            return result;
        }
    }
        // ----------------------------------------------------------------
    class BandPassCoefficients extends Coefficients
    {
        public BandPassCoefficients(double freq, double bandwidth)
        {
            super(freq/(double)SAMPLE_RATE,bandwidth/(double)SAMPLE_RATE);
            a0=1-K;
            a1=(K-R)*twoCos2piFreq;
            a2=rSquared-K;
        }
    }

and to test it, I fill a buffer with a sine wave of a range of frequencies, one at a time, apply the filter and measure the highest amplitude in the result.
Fairly obvious code, but here it is:

        // ----------------------------------------------------------------
    private void genTestSignal(float freq)
    {
        float[]  leftSignal=createSinWaveBuffer(freq,ONE_SECOND);
        float[] rightSignal=createSinWaveBuffer(freq,ONE_SECOND);
        denormalise( leftSignal ,inputSignal, LEFT_CHANNEL);
        denormalise(rightSignal,inputSignal,RIGHT_CHANNEL);
    }

The denormalise and normalise functions just convert to and from interleaved signed 16-bit values to single channel floats.
This samples the start of the signal, to find the largest absolute magnitude:

        private void findOptimalFreq(float[] signal, float freq)
    {
        float maxAmplitude=0;
        int peak=0;
        for(int i=(int)freq/2; i<(int)freq*3/2; i+=2){
            BandPassCoefficients signalFilter=new BandPassCoefficients(i,10);
            float[] normalised=signalFilter.filtered(signal);
            float loudest=0;
            // only scan the first part, since it's all the same
            for(int j=1; j<10000; ++j){
                float s=Math.abs(normalised[j]);
                if(s>loudest) loudest=s;
            }
            if(loudest>maxAmplitude){
                maxAmplitude=loudest;
                peak=i;
            }
        }
        log("freq,"+freq+","+peak);
    }

And, for completion, the code which steps through the audio range, testing each frequency.

                for(workingFreq=100; workingFreq<20000; workingFreq+=100){
                genTestSignal(workingFreq);
                inputShorts=new short[inputSignal.length/2];
                ByteBuffer.wrap(inputSignal).order(bigEndian ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(inputShorts);
                findOptimalFreq(normalised(inputShorts,RIGHT_CHANNEL),workingFreq);
            }

The output is logged to System.out, and copied to a spreadsheet, since it's CSV format.
Here's some of it, the left is the target frequency, the right is the actual frequency which the peak is at:

6200,6436
6300,6436
6400,6436
6500,6932
6600,6932
6700,6932
6800,6932
6900,6932
7000,7510
7100,7510
7200,7510
7300,7510
7400,7510
7500,7510
7600,8192
7700,8192
7800,8192
7900,8192
8000,8192
8100,8192
8200,9012
8300,9012

Any thoughts?
I've gone through the filter code over and over, and I'm fairly sure it's right; but there's no mention anywhere I've seen of this kind of "feature", so I don't know what to do next.


问:
problems with closure in JS
I have a problem with understanding closure when I have 3 level of scopes

https://jsfiddle.net/Ar2zee/wLy8rkyL/1/

How I can get access to parameter "g" in level3 function,

var a = 10;

function level1(b) {
  var c = 1;

  function level2(f) {
    var d = 2;

    function level3(g) {
      return a + b + c + d + f + g;
    }
    return level3()
  }
  return level2;
}
var temp = level1(10);
var temp2 = temp(10);
var temp3 = temp2(10);
console.log(temp3(10)); // or level(10)();  without variable```

Thank you !

答:
Just replace

```<code>Return level3()
</code>```

With

```<code>Return level3
</code>```

Title: problems with closure in JS

Body:
I have a problem with understanding closure when I have 3 level of scopes

https://jsfiddle.net/Ar2zee/wLy8rkyL/1/

How I can get access to parameter "g" in level3 function,

var a = 10;

function level1(b) {
  var c = 1;

  function level2(f) {
    var d = 2;

    function level3(g) {
      return a + b + c + d + f + g;
    }
    return level3()
  }
  return level2;
}
var temp = level1(10);
var temp2 = temp(10);
var temp3 = temp2(10);
console.log(temp3(10)); // or level(10)();  without variable

Thank you !

Body:
Just replace

Return level3()

With

Return level3


问:
Reduced size of dictionary elements when two lists combined into a dictionary
I have 2 lists that I combined their elements into a dictionary. Both lists have size of 20, and the created dictionary is almost always 13-15. The code is:

```<code>nodes = []
for x in range(1,21):
    nodes.append(str(random.randint(1,20)))
print(nodes)
</code>```

Output:

```<code>['3', '6', '10', '12', '12', '10', '11', '17', '6', '19', '20', '19', '7', '16', '9', '13', '15', '9', '12', '5']
</code>```

The rest of the code:

```<code>lines=[]

fp = open("work.txt") # open file on read mode
lines = fp.read().split("\n") # create a list containing all lines
fp.close() # close file
print(lines)
</code>```

Output:

```<code>['5', '1', '7', '1', '1', '3', '12', '1', '1', '8', '7', '5', '12', '5', '5', '3', '7', '7', '13', '1', '']
</code>```

To make a dictionary:

```<code>dictionary = dict(zip(nodes,lines))
print(dictionary)

{'3': '1', '6': '5', '10': '12', '12': '13', '10': '12', '11': '7', '17': '7', '6': '5', '19': '3', '20': '1', '19': '1', '17': '3', '16': '5', '9': '7'}
</code>```

As you see, the size is got smaller to 14 when zipped. Do you know what is the reason and how can I fix it?

NOTE: I have to keep all the keys. The duplicates in the lists are on purpose.
NOTE2: The output should have the format above, the pairs of two numbers. (1,3) or (1:3) but not (1:3,4).

答:
The problem is that you don't want a dictionary to begin with you want a list of tuples. Your code should instead be:

```<code>nodes = []
for x in range(1,21):
    nodes.append(str(random.randint(1,20)))
lines = []
fp = open("work.txt")
lines = fp.read().split("\n")
fp.close()
zipped = list(zip(nodes, lines))
</code>```

This will give you a list of tuples with the first being the random number and the second being the read number and will not eliminate duplicates. It will instead print out in the format of [(3,5), (6,1), ...] rather than what it originally looked like though but should accomplish what I think you originally intended.

Body:
I have 2 lists that I combined their elements into a dictionary. Both lists have size of 20, and the created dictionary is almost always 13-15. The code is:

nodes = []
for x in range(1,21):
    nodes.append(str(random.randint(1,20)))
print(nodes)

Output:

['3', '6', '10', '12', '12', '10', '11', '17', '6', '19', '20', '19', '7', '16', '9', '13', '15', '9', '12', '5']

The rest of the code:

lines=[]

fp = open("work.txt") # open file on read mode
lines = fp.read().split("\n") # create a list containing all lines
fp.close() # close file
print(lines)

Output:

['5', '1', '7', '1', '1', '3', '12', '1', '1', '8', '7', '5', '12', '5', '5', '3', '7', '7', '13', '1', '']

To make a dictionary:

dictionary = dict(zip(nodes,lines))
print(dictionary)

{'3': '1', '6': '5', '10': '12', '12': '13', '10': '12', '11': '7', '17': '7', '6': '5', '19': '3', '20': '1', '19': '1', '17': '3', '16': '5', '9': '7'}

As you see, the size is got smaller to 14 when zipped. Do you know what is the reason and how can I fix it?

NOTE: I have to keep all the keys. The duplicates in the lists are on purpose.
NOTE2: The output should have the format above, the pairs of two numbers. (1,3) or (1:3) but not (1:3,4).

Body:
The problem is that you don't want a dictionary to begin with you want a list of tuples. Your code should instead be:

nodes = []
for x in range(1,21):
    nodes.append(str(random.randint(1,20)))
lines = []
fp = open("work.txt")
lines = fp.read().split("\n")
fp.close()
zipped = list(zip(nodes, lines))

This will give you a list of tuples with the first being the random number and the second being the read number and will not eliminate duplicates. It will instead print out in the format of [(3,5), (6,1), ...] rather than what it originally looked like though but should accomplish what I think you originally intended.


问:
Turn PHP MySQL query output into variable
I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.

The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.

This part of the code works just fine.

```<code>$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
            $result =  mysqli_query($conn, $sql);
            if (mysqli_num_rows($result) > 0){
                while($row = mysqli_fetch_assoc($result)){
                    echo "Nome: "."<span style='color: red;'>".$row["nome"].
                    "</span>".
                    "<br>"."Preço: "."<span style='color: red;'>".
                    "R$".$row["preco"]."</span>"."<br><br>".$row["status"];
                }
            }
</code>```

What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.

```<code><form method="post" action="?p=venda">
        <input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
        <input type="text" name="preco" value="<?php echo $row["preco"]; ?>">

        <input type="submit" name="change" value="Efetuar">
    </form>
</code>```

I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).

Thanks in advance.

答:
OK  I'll tell you this, its actually unnecessary to sanitize every post. Its only necessary if your authenticated users are web users and there is a blank that they type code in.

In closed production environments, where your users are, you can safe guard the environment in several ways, but this is off topic here.

anyways, you have a DB chart that has a an Id column, the item name, and I am guessing stock or production status.

your display, I don't use spans, but I'll show you how I do it with tables.
 So lets make your query for your colums: nome, preco, status
Here are the two methods, the first one is called looped result method which is mostly used for more than one row in the db table:

```<code>     <?php
   //load it in a variable and trim the outside spaces away if you are entering this from a blank form
    $id=trim($_POST[id]);

   ///this should look familiar to you
 $sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
    ///but I use the shorthand method here to get my results.
      $result = $conn->query($sql);
     ///Now we loop and shift colum information into variables
     /// in a incremental loop, the colums are numbered starting with 0

   echo "<table align=center bgcolor=fff2e2 border=1>\n";
     while ($data = $result->fetch_row()) {
    ////I print my table header, and start the data row, if I want it as several ids I will reset here too (which I will do here if you want to play with this)

   echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
   echo '<tr>';
      for ($m=0; $m<$result->field_count; $m++) {
        if ($m==0){
        $nome='';
        $nome=$data[$m];
        echo '<td bgcolor="#ff0000">'.$nome.'</td>';
         } else if ($m==1){
        $preco='';
         $preco=$data[$m];
        echo '<td bgcolor="#ff0000">'.$preco.'</td>';
          }else if ($m==2){
         $status='';
         $status=$data[$m];
        echo '<td bgcolor="#ffffff">'.$status.'</td>';
           }
        }
     //////now if I was building a query chart with submit to another I would put my form and my hidden inputs here before i close the table row with /tr, and my submit button would be my first cell value
        echo  "</tr>";

          }
          echo "</table>";
</code>```

You could do the regular colum /row method since it is one ID, which would look like this I used the span format here so you can get the idea of how html is typically expressed in php:

```<code>               $id=trim($_POST[id]);
         $sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
        $result =  mysqli_query($conn, $sql);
        $row = mysqli_fetch_assoc($result);
        $nome=stripslashes($row['nome']);
        $preco=stripslashes($row['preco']);
        $status=stripslashes($row['status']);

         echo 'Nome: <span style="color: red;">'.$nome.'</span><br>Preço: <span style="color: red;">'.$preco.'</span><br><br>'.$status;
</code>```

///notice my quote usage above

Body:
I have a problem that is giving me a headache. I'm fairly new to PHP and MySQL interacting, and coding in general (about 3 months since I first dived into it), so I'm still learning the ropes, so to speak.

The thing is, I have a page that receives data through $_POST from another. All is fine for well. The page receives the data, which is an ID number, and echoes the item's characteristics available in the database corresponding to that ID.

This part of the code works just fine.

$sql = "SELECT nome, preco, `status` FROM produtos WHERE id = $_POST[id]";
            $result =  mysqli_query($conn, $sql);
            if (mysqli_num_rows($result) > 0){
                while($row = mysqli_fetch_assoc($result)){
                    echo "Nome: "."".$row["nome"].
                    "".
                    "
"."Preço: "."".
                    "R$".$row["preco"].""."

".$row["status"];
                }
            }

What I want, is to turn the values echoed into variables, so that I can set them as default value in another form and send that one to another page. Apparently, $row['nome'], for example, isn't available for re-use outside of the instance above.

<form method="post" action="?p=venda">
        <input type="text" name="nome" value="<?php echo $row["nome"]; ?>">
        <input type="text" name="preco" value="<?php echo $row["preco"]; ?>">

        <input type="submit" name="change" value="Efetuar">
    </form>

I know this code is prone to SQL injection, but I'm not looking into it right now. This will be a sort of offline program to help me with organizing some of my stuff, so, for now, I don't have to worry about security (not that I'll keep ignoring these issues).

Thanks in advance.

Body:
OK  I'll tell you this, its actually unnecessary to sanitize every post. Its only necessary if your authenticated users are web users and there is a blank that they type code in.

In closed production environments, where your users are, you can safe guard the environment in several ways, but this is off topic here.

anyways, you have a DB chart that has a an Id column, the item name, and I am guessing stock or production status.

your display, I don't use spans, but I'll show you how I do it with tables.
 So lets make your query for your colums: nome, preco, status
Here are the two methods, the first one is called looped result method which is mostly used for more than one row in the db table:

     <?php
   //load it in a variable and trim the outside spaces away if you are entering this from a blank form
    $id=trim($_POST[id]);

   ///this should look familiar to you
 $sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
    ///but I use the shorthand method here to get my results.
      $result = $conn->query($sql);
     ///Now we loop and shift colum information into variables
     /// in a incremental loop, the colums are numbered starting with 0

   echo "<table align=center bgcolor=fff2e2 border=1>\n";
     while ($data = $result->fetch_row()) {
    ////I print my table header, and start the data row, if I want it as several ids I will reset here too (which I will do here if you want to play with this)

   echo '<tr><th>Nome</th><th>Preco</th><th>Status</th></tr>';
   echo '<tr>';
      for ($m=0; $m<$result->field_count; $m++) {
        if ($m==0){
        $nome='';
        $nome=$data[$m];
        echo '<td bgcolor="#ff0000">'.$nome.'</td>';
         } else if ($m==1){
        $preco='';
         $preco=$data[$m];
        echo '<td bgcolor="#ff0000">'.$preco.'</td>';
          }else if ($m==2){
         $status='';
         $status=$data[$m];
        echo '<td bgcolor="#ffffff">'.$status.'</td>';
           }
        }
     //////now if I was building a query chart with submit to another I would put my form and my hidden inputs here before i close the table row with /tr, and my submit button would be my first cell value
        echo  "</tr>";

          }
          echo "</table>";

You could do the regular colum /row method since it is one ID, which would look like this I used the span format here so you can get the idea of how html is typically expressed in php:

               $id=trim($_POST[id]);
         $sql = "SELECT nome, preco, status FROM produtos WHERE id ='".$id."'";
        $result =  mysqli_query($conn, $sql);
        $row = mysqli_fetch_assoc($result);
        $nome=stripslashes($row['nome']);
        $preco=stripslashes($row['preco']);
        $status=stripslashes($row['status']);

         echo 'Nome: <span style="color: red;">'.$nome.'</span><br>Preço: <span style="color: red;">'.$preco.'</span><br><br>'.$status;

///notice my quote usage above


问:
HttpWebRequest Cookie weirdness
I'm sure I must be doing something wrong. But can't for the life of me figure out what is going on.

I have a problem where it seems that the HttpWebRequest class in the framework is not correctly parsing the cookies from a web response.

I'm using Fiddler to see what is going on and after making a request, the headers of the response look as such:

```<code>HTTP/1.1 200 Ok
Connection: close
Date: Wed, 14 Jan 2009 18:20:31 GMT
Server: Microsoft-IIS/6.0
P3P: policyref="/w3c/p3p.xml", CP="CAO DSP IND COR ADM CONo CUR CUSi DEV PSA PSD DELi OUR COM NAV PHY ONL PUR UNI"
Set-Cookie: user=v.5,0,EX01E508801E$97$2E401000t$1BV6$A1$EC$104$A1$EC$104$A1$EC$104$21O001000$1E31!90$7CP$AE$3F$F3$D8$19o$BC$1Cd$23; Domain=.thedomain.com; path=/
Set-Cookie: minfo=v.4,EX019ECD28D6k$A3$CA$0C$CE$A2$D6$AD$D4!2$8A$EF$E8n$91$96$E1$D7$C8$0F$98$AA$ED$DC$40V$AB$9C$C1$9CF$C9$C1zIF$3A$93$C6$A7$DF$A1$7E$A7$A1$A8$BD$A6$94c$D5$E8$2F$F4$AF$A2$DF$80$89$BA$BBd$F6$2C$B6$A8; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: accttype=v.2,3,1,EX017E651B09k$A3$CA$0C$DB$A2$CB$AD$D9$8A$8C$EF$E8t$91$90$E1$DC$C89$98$AA$E0$DC$40O$A8$A4$C1$9C; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: tpid=v.1,20001; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: MC1=GUID=541977e04a341a2a4f4cdaaf49615487; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: linfo=v.4,EQC|0|0|255|1|0||||||||0|0|0||0|0|0|-1|-1; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: group=v.1,0; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Content-Type: text/html
</code>```

But when I look at the response.Cookies, I see far more cookies that I am expecting, with values of different cookies being split up into different cookies.

Manually getting the headers seems to result in more wierdness

eg: the code

```<code>foreach(string cookie in response.Headers.GetValues("Set-Cookie"))
{
    Console.WriteLine("Cookie found: " + cookie);
}
</code>```

produces the output:

```<code>Cookie found: user=v.5
Cookie found: 0
Cookie found: EX01E508801E$97$2E401000t$1BV6$A1$EC$104$A1$EC$104$A1$EC$104$21O00
1000$1E31!90$7CP$AE$3F$F3$D8$19o$BC$1Cd$23; Domain=.thedomain.com; path=/
Cookie found: minfo=v.4
Cookie found: EX019ECD28D6k$A3$CA$0C$CE$A2$D6$AD$D4!2$8A$EF$E8n$91$96$E1$D7$C8$0
F$98$AA$ED$DC$40V$AB$9C$C1$9CF$C9$C1zIF$3A$93$C6$A7$DF$A1$7E$A7$A1$A8$BD$A6$94c$
D5$E8$2F$F4$AF$A2$DF$80$89$BA$BBd$F6$2C$B6$A8; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: accttype=v.2
Cookie found: 3
Cookie found: 1
Cookie found: EX017E651B09k$A3$CA$0C$DB$A2$CB$AD$D9$8A$8C$EF$E8t$91$90$E1$DC$C89
$98$AA$E0$DC$40O$A8$A4$C1$9C; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: tpid=v.1
Cookie found: 20001; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: MC1=GUID=541977e04a341a2a4f4cdaaf49615487; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: linfo=v.4
Cookie found: EQC|0|0|255|1|0||||||||0|0|0||0|0|0|-1|-1; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: group=v.1
Cookie found: 0; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
</code>```

as you can see - the first cookie in the list raw response:

Set-Cookie: user=v.5,0,EX01E508801

is getting split into:

Cookie found: user=v.5

Cookie found: 0

Cookie found: EX01E508801E$..........

So - what's going on here?

Am I wrong?

Is the HttpWebRequest class incorrectly parsing the http headers?

Is the webserver that it spitting out the requests producing invalid http headers?

答: It seems that the server sends incorrect cookie values. IMHO commas are not allowed in cookie values. They need to be encoded with %2C.</p>

OwnerDisplayName: Lachman

Title: HttpWebRequest Cookie weirdness

Body:
I'm sure I must be doing something wrong. But can't for the life of me figure out what is going on.

I have a problem where it seems that the HttpWebRequest class in the framework is not correctly parsing the cookies from a web response.

I'm using Fiddler to see what is going on and after making a request, the headers of the response look as such:

HTTP/1.1 200 Ok
Connection: close
Date: Wed, 14 Jan 2009 18:20:31 GMT
Server: Microsoft-IIS/6.0
P3P: policyref="/w3c/p3p.xml", CP="CAO DSP IND COR ADM CONo CUR CUSi DEV PSA PSD DELi OUR COM NAV PHY ONL PUR UNI"
Set-Cookie: user=v.5,0,EX01E508801E$97$2E401000t$1BV6$A1$EC$104$A1$EC$104$A1$EC$104$21O001000$1E31!90$7CP$AE$3F$F3$D8$19o$BC$1Cd$23; Domain=.thedomain.com; path=/
Set-Cookie: minfo=v.4,EX019ECD28D6k$A3$CA$0C$CE$A2$D6$AD$D4!2$8A$EF$E8n$91$96$E1$D7$C8$0F$98$AA$ED$DC$40V$AB$9C$C1$9CF$C9$C1zIF$3A$93$C6$A7$DF$A1$7E$A7$A1$A8$BD$A6$94c$D5$E8$2F$F4$AF$A2$DF$80$89$BA$BBd$F6$2C$B6$A8; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: accttype=v.2,3,1,EX017E651B09k$A3$CA$0C$DB$A2$CB$AD$D9$8A$8C$EF$E8t$91$90$E1$DC$C89$98$AA$E0$DC$40O$A8$A4$C1$9C; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: tpid=v.1,20001; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: MC1=GUID=541977e04a341a2a4f4cdaaf49615487; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: linfo=v.4,EQC|0|0|255|1|0||||||||0|0|0||0|0|0|-1|-1; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Set-Cookie: group=v.1,0; expires=Sunday, 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Content-Type: text/html

But when I look at the response.Cookies, I see far more cookies that I am expecting, with values of different cookies being split up into different cookies.

Manually getting the headers seems to result in more wierdness

eg: the code

foreach(string cookie in response.Headers.GetValues("Set-Cookie"))
{
    Console.WriteLine("Cookie found: " + cookie);
}

produces the output:

Cookie found: user=v.5
Cookie found: 0
Cookie found: EX01E508801E$97$2E401000t$1BV6$A1$EC$104$A1$EC$104$A1$EC$104$21O00
1000$1E31!90$7CP$AE$3F$F3$D8$19o$BC$1Cd$23; Domain=.thedomain.com; path=/
Cookie found: minfo=v.4
Cookie found: EX019ECD28D6k$A3$CA$0C$CE$A2$D6$AD$D4!2$8A$EF$E8n$91$96$E1$D7$C8$0
F$98$AA$ED$DC$40V$AB$9C$C1$9CF$C9$C1zIF$3A$93$C6$A7$DF$A1$7E$A7$A1$A8$BD$A6$94c$
D5$E8$2F$F4$AF$A2$DF$80$89$BA$BBd$F6$2C$B6$A8; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: accttype=v.2
Cookie found: 3
Cookie found: 1
Cookie found: EX017E651B09k$A3$CA$0C$DB$A2$CB$AD$D9$8A$8C$EF$E8t$91$90$E1$DC$C89
$98$AA$E0$DC$40O$A8$A4$C1$9C; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: tpid=v.1
Cookie found: 20001; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: MC1=GUID=541977e04a341a2a4f4cdaaf49615487; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: linfo=v.4
Cookie found: EQC|0|0|255|1|0||||||||0|0|0||0|0|0|-1|-1; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/
Cookie found: group=v.1
Cookie found: 0; expires=Sunday
Cookie found: 31-Dec-2014 23:59:59 GMT; Domain=.thedomain.com; path=/

as you can see - the first cookie in the list raw response:

Set-Cookie: user=v.5,0,EX01E508801

is getting split into:

Cookie found: user=v.5

Cookie found: 0

Cookie found: EX01E508801E$..........

So - what's going on here?

Am I wrong?

Is the HttpWebRequest class incorrectly parsing the http headers?

Is the webserver that it spitting out the requests producing invalid http headers?

LastEditorDisplayName: Paul Dixon

OwnerDisplayName: darin


问:
Plugin to generate call case
Is there any easy and good plugin for Eclipse to generate UML and plugin to get call diagram from code Java?</p>

答:
MaintainJ will generate UML sequence diagrams.

So will OMONDO.

You can find other plugins that will do it using Google and a little poking around.  The key is that "sequence diagram" is the name of the UML diagram that illustrates how objects call each other.

Title: Plugin to generate call case