问:
PHP json_encode and javascript functions
I need to encode a javascript function into a JSON object in PHP.

This:

```<code>$function = "function(){}";
$message = "Hello";

$json = array(
      'message' => $message,
      'func' => $function
);
echo json_encode($json);
</code>```

outputs:

```<code>{"message":"Hello","func":"function(){}"}
</code>```

What I want is:

```<code>{"message":"Hello","func":function(){}}
</code>```

Can I do this with json_encode?

答:
I write this simple function for all json function based help my myabe help someone:</p>

```<code>function json_encode_ex($array) {
    $var = json_encode($array);
    preg_match_all('/\"function.*?\"/', $var, $matches);
    foreach ($matches[0] as $key => $value) {
        $newval = str_replace(array('\n', '\t','\/'), array(PHP_EOL,"\t",'/'), trim($value, '"'));
        $var = str_replace($value, $newval, $var);
    }
    return $var;
}
</code>```

Body:
I need to encode a javascript function into a JSON object in PHP.

This:

$function = "function(){}";
$message = "Hello";

$json = array(
      'message' => $message,
      'func' => $function
);
echo json_encode($json);

outputs:

{"message":"Hello","func":"function(){}"}

What I want is:

{"message":"Hello","func":function(){}}

Can I do this with json_encode?

Body:
I write this simple function for all json function based help my myabe help someone:

function json_encode_ex($array) {
    $var = json_encode($array);
    preg_match_all('/\"function.*?\"/', $var, $matches);
    foreach ($matches[0] as $key => $value) {
        $newval = str_replace(array('\n', '\t','\/'), array(PHP_EOL,"\t",'/'), trim($value, '"'));
        $var = str_replace($value, $newval, $var);
    }
    return $var;
}


来源: stackexchange

问:
Using FileSystemObject or the Input # statement to read data from text files
I have to read in some data from text files formated like the example below, with e.g. 5 variables separated by a tab or space delimiter (not fixed-width columns).

```<code>Montreal 0.2 h 3 500
Otherplace 0.1 m 50 25
Thirdplace 0.05 m 62 112
[...]
</code>```

I could read these in using the Input # statement, and that's what I've mostly been doing, because it's the easiest/laziest approach. But:

The Input # statement doesn't always recognize tabs as delimiters.

The whole Input # vernacular has a very "deprecated" feel to it!

I'm thinking about modernizing and reading files using the FileSystemObject methods (already do so for writing files).

But doesn't this requires a lot of string manipulation to parse out my 5 variable values? Any suggestions on how best to do this?

Also, what's a good way of determining how many lines there are in the text file? So I can ReDim my arrays ahead of time.

答:
Have you considered using Jet to read your textfile as a recordset?

http://www.connectionstrings.com/textfile

Jet is installed with all recent versions of Windows.

ContentLicense: CC BY-SA 2.5

Body:
I have to read in some data from text files formated like the example below, with e.g. 5 variables separated by a tab or space delimiter (not fixed-width columns).

Montreal 0.2 h 3 500
Otherplace 0.1 m 50 25
Thirdplace 0.05 m 62 112
[...]

I could read these in using the Input # statement, and that's what I've mostly been doing, because it's the easiest/laziest approach. But:

The Input # statement doesn't always recognize tabs as delimiters.

The whole Input # vernacular has a very "deprecated" feel to it!

I'm thinking about modernizing and reading files using the FileSystemObject methods (already do so for writing files).

But doesn't this requires a lot of string manipulation to parse out my 5 variable values? Any suggestions on how best to do this?

Also, what's a good way of determining how many lines there are in the text file? So I can ReDim my arrays ahead of time.


问:
How to play mp3 with powershell (simple)?
How do I play mp3 with Powershell?

What I tried:

```<code>powershell -c (New-Object Media.SoundPlayer "Track.mp3").Play();
</code>```

答:
This is an old question but I just went through this so if anyone is interested in learning or knowing how to do this in a more simple manner use the following answer.

As long as you have a media player that has good command line switches such as VLC and other similar types of versatile players  (perhaps media player classic) you CAN make a one line command to run a MP3 file. Here is my example, enjoy! :)

```<code>& 'C:\Program Files\VideoLAN\VLC\vlc.exe' --qt-start-minimized --play-and-exit --qt-notification=0 "D:\SystemSettings\51Hz.mp3"
</code>```

This would run 51Hz.mp3 file with neither notifications to take place nor any other user interaction.

ContentLicense: CC BY-SA 3.0

Body:
How do I play mp3 with Powershell?

What I tried:

powershell -c (New-Object Media.SoundPlayer "Track.mp3").Play();

Body:
This is an old question but I just went through this so if anyone is interested in learning or knowing how to do this in a more simple manner use the following answer.

As long as you have a media player that has good command line switches such as VLC and other similar types of versatile players  (perhaps media player classic) you CAN make a one line command to run a MP3 file. Here is my example, enjoy! :)

& 'C:\Program Files\VideoLAN\VLC\vlc.exe' --qt-start-minimized --play-and-exit --qt-notification=0 "D:\SystemSettings\51Hz.mp3"

This would run 51Hz.mp3 file with neither notifications to take place nor any other user interaction.


问:
Android studio does not see connected devices
I use Windows 8.1 and Android Studio 1.0.1. I need to run my app on my Nexus 10, but android studio does not see it at all! Debugging mode on the device is on, Google USB driver is installed from SDK Manager and Windows file explorer recognizes it normally. What should I do?? </p>

答: Double check within Developer Options, "USB Debugging is checked".  Mine was grayed out and would not allow me to check the box.  Upon switching off Developers Options on the top and turn it back on, the USB Debugging check box area was made available to modify, but only for a split second.  Upon clicking the check box thereby allowing USB Debugging, Android Studios immediately recognized my phone again.  Hope this helps....</p>


问:
Create dynamic xml using xelement in c#
I want to create xml using XElement as you can see:

```<code>XDocument RejectedXmlList = new XDocument
(
    new XDeclaration("1.0", "utf-8", null)
);
int RejectCounter = 0;

foreach (Parameter Myparameter in Parameters)
{
    if (true)
    {
        XElement xelement = new XElement(Myparameter.ParameterName, CurrentData.ToString());
        RejectedXmlList.Add(xelement);
    }
}
</code>```

As you can see if the condition is OK the parameter should be added to RejectedXmlList but instead I get this exception:

This operation would create an incorrectly structured document.
```

<p>Of note, the first parameter is added successfully.  Only when the second one is added do I get the exception.</p>

<p>The expected result should be like this:</p>

```<co>2</co>
<o2>2</o2>
....
```

答:
You are trying to create an XDocument with multiple root elements, one for each Parameter in Parameters  You can't do that because the XML standard disallows it:

There is exactly one element, called the root, or document element, no part of which appears in the content of any other element.

The LINQ to XML API enforces this constraint, throwing the exception you see when you try to add a second root element to the document.

Instead, add a root element, e.g. <Rejectedparameters>, then add your xelement children to it:

```<code>// Allocate the XDocument and add an XML declaration.
XDocument RejectedXmlList = new XDocument(new XDeclaration("1.0", "utf-8", null));

// At this point RejectedXmlList.Root is still null, so add a unique root element.
RejectedXmlList.Add(new XElement("Rejectedparameters"));

// Add elements for each Parameter to the root element
foreach (Parameter Myparameter in Parameters)
{
    if (true)
    {
        XElement xelement = new XElement(Myparameter.ParameterName, CurrentData.ToString());
        RejectedXmlList.Root.Add(xelement);
    }
}
</code>```

Sample fiddle.

Title: Create dynamic xml using xelement in c#

Body:
I want to create xml using XElement as you can see:

XDocument RejectedXmlList = new XDocument
(
    new XDeclaration("1.0", "utf-8", null)
);
int RejectCounter = 0;

foreach (Parameter Myparameter in Parameters)
{
    if (true)
    {
        XElement xelement = new XElement(Myparameter.ParameterName, CurrentData.ToString());
        RejectedXmlList.Add(xelement);
    }
}

As you can see if the condition is OK the parameter should be added to RejectedXmlList but instead I get this exception:

This operation would create an incorrectly structured document.

Of note, the first parameter is added successfully.  Only when the second one is added do I get the exception.

The expected result should be like this:

<co>2</co>
<o2>2</o2>
....

Body:
You are trying to create an XDocument with multiple root elements, one for each Parameter in Parameters  You can't do that because the XML standard disallows it:

There is exactly one element, called the root, or document element, no part of which appears in the content of any other element.

The LINQ to XML API enforces this constraint, throwing the exception you see when you try to add a second root element to the document.

Instead, add a root element, e.g. <Rejectedparameters>, then add your xelement children to it:

// Allocate the XDocument and add an XML declaration.
XDocument RejectedXmlList = new XDocument(new XDeclaration("1.0", "utf-8", null));

// At this point RejectedXmlList.Root is still null, so add a unique root element.
RejectedXmlList.Add(new XElement("Rejectedparameters"));

// Add elements for each Parameter to the root element
foreach (Parameter Myparameter in Parameters)
{
    if (true)
    {
        XElement xelement = new XElement(Myparameter.ParameterName, CurrentData.ToString());
        RejectedXmlList.Root.Add(xelement);
    }
}

Sample fiddle.


问:
Codeigniter 3 - how to remove the function name from URL
My URL is:

```<code>example.com/controller/function/parameter
=> example.com/category/index/category_name
</code>```

I need:

```<code>example.com/category/category_name
</code>```

I have tried several solutions provided by Stackoverflow questions asked on this, but it´s not working. Either it redirects to home or a 404 page not found.

The options I have tried are:

```<code>$route['category'] = "category/index"; //1

$route['category/(:any)'] = "category/index"; //2

$route['category/(:any)'] = "category/index/$1";  //3
</code>```

Another route is:

```<code>$route['default_controller'] = 'home';
</code>```

The htaccess file:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

In config file I have:

```<code>$config['url_suffix'] = '';
</code>```

答:
I am not sure why you couldn't get it to work.

Here is some test code I created to check this out...
This is using CI 3.1.5.

.htaccess - same as what you have...

Controller - Category.php

```<code><?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Category extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index($category_name = 'None Selected') {
        echo "The Category name is " . $category_name;
    }
}
</code>```

routes.php

```<code>$route['category/(:any)'] = "category/index/$1";  //3 - this works

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

Test URLS

/category/ output: The Category name is None Selected

/category/fluffy-bunnies output:  The Category name is fluffy-bunnies

Have a play with that and see if you can find the issue.

Body:
My URL is:

example.com/controller/function/parameter
=> example.com/category/index/category_name

I need:

example.com/category/category_name

I have tried several solutions provided by Stackoverflow questions asked on this, but it´s not working. Either it redirects to home or a 404 page not found.

The options I have tried are:

$route['category'] = "category/index"; //1

$route['category/(:any)'] = "category/index"; //2

$route['category/(:any)'] = "category/index/$1";  //3

Another route is:

$route['default_controller'] = 'home';

The htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt|css)
RewriteRule ^(.*)$ index.php/$1 [L]

In config file I have:

$config['url_suffix'] = '';

Body:
I am not sure why you couldn't get it to work.

Here is some test code I created to check this out...
This is using CI 3.1.5.

.htaccess - same as what you have...

Controller - Category.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Category extends CI_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index($category_name = 'None Selected') {
        echo "The Category name is " . $category_name;
    }
}

routes.php

$route['category/(:any)'] = "category/index/$1";  //3 - this works

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

Test URLS

/category/ output: The Category name is None Selected

/category/fluffy-bunnies output:  The Category name is fluffy-bunnies

Have a play with that and see if you can find the issue.


问:
Is there any limit on how much text asp:label control can hold?
Should I use it if I wanna store really long text?</p>

答: A label is the HTML equivalent of a span in when rendered. It holds any valid string.</p>


问:
Change cell color based on value faster
I have vba code to change the color of cells based on the content of it currently I am looping through 13000 cells individually using row and column indexed for loops and a select case statement but it takes around 30 secs. Does anyone know a quicker way ?</p>

答:
this is some sample code I had from another question.  you should be able to see how easy it is to set up the autofilter and once it is filtered by your criteria just do the interior.colorindex for whatever color you want to set for the visible cells then change criteria for next color rinse and repeat. i also recommend to turn calculation to manual at beginning of sub along with screenupdating false and enable events false then at end of sub set calculation back to automatic and make other two things true again.

```<code>Private Sub CommandButton2_Click()
Dim IMBacklogSh As Worksheet, logoffSh As Worksheet, deniedsh As Worksheet

Set IMBacklogSh = ThisWorkbook.Worksheets("Backlog")
Set logoffSh = ThisWorkbook.Worksheets("Claims Logged off")
Set deniedsh = ThisWorkbook.Worksheets("Claims Denied")

With IMBacklogSh
    If .AutoFilterMode Then .AutoFilterMode = False
    With .Cells(1, 1).CurrentRegion
        .AutoFilter field:=13, Criteria1:="#N/A"
        .AutoFilter field:=14, Criteria1:="C"
        With .Resize(.Rows.Count - 1, Columns.Count).Offset(1, 0)
            If CBool(Application.Subtotal(103, .Cells)) Then
                .Copy Destination:= _
                    logoffSh.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                'optionally delete the originals
                .EntireRow.Delete
            End If
        End With
        .AutoFilter field:=14, Criteria1:="<>C"
        With .Resize(.Rows.Count - 1, Columns.Count).Offset(1, 0)
            If CBool(Application.Subtotal(103, .Cells)) Then
                .Copy Destination:= _
                    deniedsh.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                'optionally delete the originals
                .EntireRow.Delete
            End If
        End With
    End With
    If .AutoFilterMode Then .AutoFilterMode = False
End With
</code>```

End Sub

Title: Change cell color based on value faster

Body:
this is some sample code I had from another question.  you should be able to see how easy it is to set up the autofilter and once it is filtered by your criteria just do the interior.colorindex for whatever color you want to set for the visible cells then change criteria for next color rinse and repeat. i also recommend to turn calculation to manual at beginning of sub along with screenupdating false and enable events false then at end of sub set calculation back to automatic and make other two things true again.

Private Sub CommandButton2_Click()
Dim IMBacklogSh As Worksheet, logoffSh As Worksheet, deniedsh As Worksheet

Set IMBacklogSh = ThisWorkbook.Worksheets("Backlog")
Set logoffSh = ThisWorkbook.Worksheets("Claims Logged off")
Set deniedsh = ThisWorkbook.Worksheets("Claims Denied")

With IMBacklogSh
    If .AutoFilterMode Then .AutoFilterMode = False
    With .Cells(1, 1).CurrentRegion
        .AutoFilter field:=13, Criteria1:="#N/A"
        .AutoFilter field:=14, Criteria1:="C"
        With .Resize(.Rows.Count - 1, Columns.Count).Offset(1, 0)
            If CBool(Application.Subtotal(103, .Cells)) Then
                .Copy Destination:= _
                    logoffSh.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                'optionally delete the originals
                .EntireRow.Delete
            End If
        End With
        .AutoFilter field:=14, Criteria1:="<>C"
        With .Resize(.Rows.Count - 1, Columns.Count).Offset(1, 0)
            If CBool(Application.Subtotal(103, .Cells)) Then
                .Copy Destination:= _
                    deniedsh.Cells(Rows.Count, "A").End(xlUp).Offset(1, 0)
                'optionally delete the originals
                .EntireRow.Delete
            End If
        End With
    End With
    If .AutoFilterMode Then .AutoFilterMode = False
End With

End Sub


问:
Unable to access HBase Via API
I have hbase installed over three nodes. I am trying to load hbase via spark with the help of below code.

```<code>from __future__ import print_function

import sys

from pyspark import SparkContext
import json
if __name__ == "__main__":
    print ("*******************************")
    sc = SparkContext(appName="HBaseOutputFormat")
    host = sys.argv[1]
    table = "hbase_test"
    port = "2181"

    conf = {"hbase.zookeeper.quorum": host,
            "hbase.mapred.outputtable": table,
            "hbase.zookeeper.property.clientPort":port,
            "mapreduce.outputformat.class": "org.apache.hadoop.hbase.mapreduce.TableOutputFormat",
            "mapreduce.job.output.key.class": "org.apache.hadoop.hbase.io.ImmutableBytesWritable",
            "mapreduce.job.output.value.class": "org.apache.hadoop.io.Writable"}
    keyConv = "org.apache.spark.examples.pythonconverters.StringToImmutableBytesWritableConverter"
    valueConv = "org.apache.spark.examples.pythonconverters.StringListToPutConverter"
    rdd = sc.parallelize([sys.argv[2:]]).map(lambda x: (x[0], x))
    print (rdd.collect())
    rdd.saveAsNewAPIHadoopDataset(
        conf=conf,
        keyConverter=keyConv,
        valueConverter=valueConv)

    sc.stop()
</code>```

I am executing code as:

```<code> spark-submit  --driver-class-path /usr/iop/4.3.0.0-0000/hbase/lib/hbase-server.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-common.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-client.jar:/usr/iop/4.3.0.0-0000/hbase/lib/zookeeper.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-protocol.jar:/usr/iop/4.3.0.0-0000/spark2/examples/jars/scopt_2.11-3.3.0.jar:/home/tanveer/spark-examples_2.10-1.1.0.jar --conf spark.ui.port=5054  --master local[2] /data/usr/tanveer/from_home/spark/hbase_outputformat.py HBASE_MASTER_ip row1 f1 q1 value1
</code>```

But the job stucks and doesn't proceed. Below is the snapshot:

As per some previous threads I tried changing /etc/hosts to comment localhost line but it didn't worked.

Requesting your help.

答:
On further debugging I referred to below blog post from Hortononworks link for best practice:

https://community.hortonworks.com/articles/4091/hbase-client-application-best-practices.html

I have added hbase configuration file to driver class path and ran the code and it worked perfectly fine.

Modified spark-submit can be viewed as:

```<code> spark-submit  --driver-class-path /usr/iop/4.3.0.0-0000/hbase/lib/hbase-server.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-common.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-client.jar:/usr/iop/4.3.0.0-0000/hbase/lib/zookeeper.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-protocol.jar:/usr/iop/4.3.0.0-0000/spark2/examples/jars/scopt_2.11-3.3.0.jar:/home/tanveer/spark-examples_2.10-1.1.0.jar:**/etc/hbase/conf** --conf spark.ui.port=5054  --master local[2] /data/usr/tanveer/from_home/spark/hbase_outputformat.py host row1 f1 q1 value1
</code>```

Title: Unable to access HBase Via API

Body:
I have hbase installed over three nodes. I am trying to load hbase via spark with the help of below code.

from __future__ import print_function

import sys

from pyspark import SparkContext
import json
if __name__ == "__main__":
    print ("*******************************")
    sc = SparkContext(appName="HBaseOutputFormat")
    host = sys.argv[1]
    table = "hbase_test"
    port = "2181"

    conf = {"hbase.zookeeper.quorum": host,
            "hbase.mapred.outputtable": table,
            "hbase.zookeeper.property.clientPort":port,
            "mapreduce.outputformat.class": "org.apache.hadoop.hbase.mapreduce.TableOutputFormat",
            "mapreduce.job.output.key.class": "org.apache.hadoop.hbase.io.ImmutableBytesWritable",
            "mapreduce.job.output.value.class": "org.apache.hadoop.io.Writable"}
    keyConv = "org.apache.spark.examples.pythonconverters.StringToImmutableBytesWritableConverter"
    valueConv = "org.apache.spark.examples.pythonconverters.StringListToPutConverter"
    rdd = sc.parallelize([sys.argv[2:]]).map(lambda x: (x[0], x))
    print (rdd.collect())
    rdd.saveAsNewAPIHadoopDataset(
        conf=conf,
        keyConverter=keyConv,
        valueConverter=valueConv)

    sc.stop()

I am executing code as:

 spark-submit  --driver-class-path /usr/iop/4.3.0.0-0000/hbase/lib/hbase-server.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-common.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-client.jar:/usr/iop/4.3.0.0-0000/hbase/lib/zookeeper.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-protocol.jar:/usr/iop/4.3.0.0-0000/spark2/examples/jars/scopt_2.11-3.3.0.jar:/home/tanveer/spark-examples_2.10-1.1.0.jar --conf spark.ui.port=5054  --master local[2] /data/usr/tanveer/from_home/spark/hbase_outputformat.py HBASE_MASTER_ip row1 f1 q1 value1

But the job stucks and doesn't proceed. Below is the snapshot:

As per some previous threads I tried changing /etc/hosts to comment localhost line but it didn't worked.

Requesting your help.

Body:
On further debugging I referred to below blog post from Hortononworks link for best practice:

https://community.hortonworks.com/articles/4091/hbase-client-application-best-practices.html

I have added hbase configuration file to driver class path and ran the code and it worked perfectly fine.

Modified spark-submit can be viewed as:

 spark-submit  --driver-class-path /usr/iop/4.3.0.0-0000/hbase/lib/hbase-server.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-common.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-client.jar:/usr/iop/4.3.0.0-0000/hbase/lib/zookeeper.jar:/usr/iop/4.3.0.0-0000/hbase/lib/hbase-protocol.jar:/usr/iop/4.3.0.0-0000/spark2/examples/jars/scopt_2.11-3.3.0.jar:/home/tanveer/spark-examples_2.10-1.1.0.jar:**/etc/hbase/conf** --conf spark.ui.port=5054  --master local[2] /data/usr/tanveer/from_home/spark/hbase_outputformat.py host row1 f1 q1 value1


问:
unregister_netdevice: waiting for eth1 to become free？
I used vconfig to create two vlan，phy0.1 and phy0.2
and change their name,

```<code>ip link set dev phy0.1 name eth0  (for Router lan)
ip link set dev phy0.2 name eth1. (for Router wan).
</code>```

Now, for some purpose, I have to rem phy0.1.

However, when I rem eth1 by below command,

```<code>ifconfig eth1 down
vconfig rem eth1.
</code>```

It cannot work well, and get below message,

```<code>unregister_netdevice: waiting for eth1 to become free. Usage count = 1
</code>```

Now how can I find out the process that is using eth1.

Or, if there is any other way to rem eth1?

答:
That looks like what is described in "When the blue whale sinks" by Bernardo Donadio, and reported initially in 2014 in a docker context

This issue isn’t present in the Docker code itself, but rather in the Linux kernel code instead.

  It affects not only Docker, but any kind of software that uses the Linux network stack to create devices and namespaces frequently like LXC, OpenStack, Rkt, Proxmox, etc…

If you’ve already had some experience with multi-thread programming, you can instantly diagnose this as a race condition

Once the bug is triggered, the situation now is the following: you’re unable to create, delete or change any network device in the whole system.

  There’s absolutely no fix to the bug so far, except a few mitigations and the Windows-style workaround: reboot your computer. Seriously.

Worse even is the fact that reproducing this issue is far from straightforward.

  The Red Hat kernel (including CentOS) seems to be specially more prone to suffer from this problem, but all other distributions have reports of also being affected.

As of the time of this publication (July 2017), a fix has already been released (kernel 4.8) to the issue being encountered by hitting the bug in the IPv6 stack, but people are still get the annoying message and frozen behaviour, suggesting that the bug has multiple causes, spread all over the network subsystem of the kernel.

Body:
I used vconfig to create two vlan，phy0.1 and phy0.2
and change their name,

ip link set dev phy0.1 name eth0  (for Router lan)
ip link set dev phy0.2 name eth1. (for Router wan).

Now, for some purpose, I have to rem phy0.1.

However, when I rem eth1 by below command,

ifconfig eth1 down
vconfig rem eth1.

It cannot work well, and get below message,

unregister_netdevice: waiting for eth1 to become free. Usage count = 1

Now how can I find out the process that is using eth1.

Or, if there is any other way to rem eth1?


问:
Can I write an app for my android phone using VB?
I have struggled using Word for this need but it is cryptic.  If I could understand how to use Excel in the phone, it might work.  However, I am beginning to see that I should design my own app and the only programming language I know well enough is Visual BASIC.

Can this work?

答: Unfortunately, I believe that you will find quite a bit of trouble in making the app via VB. Luckily for you, if you can code it and have it work in VB, then it shouldn't be much more than a matter of learning syntax for another language to get done what you need to (java or javascript would be my choice).</p>

ContentLicense: CC BY-SA 4.0


问:
Java newbie while loop
I'm baffled, why doesn't the following code print anything? (2)

```<code>public class Testwhileloop {

public static void main(String[] args)
{
    int i = 1;
    while (i == 1);
    {
        i = i + 1;
        System.out.println(i);
    }

}
</code>```

}

答:
It's because you have the following statement

while (i == 1);

The ; at the end puts the code in an endless loop. If you remove it, the println statement will execute.

Title: Java newbie while loop

Body:
I'm baffled, why doesn't the following code print anything? (2)

public class Testwhileloop {

public static void main(String[] args)
{
    int i = 1;
    while (i == 1);
    {
        i = i + 1;
        System.out.println(i);
    }

}

}


问:
Google Cloud Engine - Issues When Mounting Storage Bucket To Use With WordPress
I searched thoroughly and could not find any info on this issue.

Currently, I am building a Word Press site, hosted on Google Cloud's Compute Engine. The goal is to build an autoscaling WP site. I am currently attempting to build the instance template, which I can then use to deploy an instance group and subsequently setup the HTTP load balancer.

I am using a base Ubuntu 16.04 image, and from there I installed the rest of the LEMP stack.

I was successfully able to use the SQL proxy to connect to Cloud SQL so that all of the ephermal instances to be deployed will share the same database. To have the proxy initiated each time a new instance is spun up, I am using a startup script:

```<code>./cloud_sql_proxy -dir=/cloudsql &
</code>```

But here's my issue right now: the Word Press files. I can't figure out a way to have all of the instances use the same WP files. I already tried to use Google Cloud Storage FUSE, but when I mount the bucket at the root directory, it deletes all of the WordPress folders (wp-content, wp-admin, wp-includes).

It's as if the instance can't "see" the folders I have in the google cloud storage. Here was my work flow:

setup LEMP with WordPress--got the site working on the front end--all systems go

copied all of the files/folders in my root directory (/var/www/html/) to google cloud bucket

gsutil -m cp -r /var/www/html/. gs://example-bucket/

Then I mounted the bucket at my directory

gcsfuse --dir-mode "777" -o allow_other example-bucket /var/www/html/

But now, when I "ls" inside of the root directory from the Linux terminal, I DON'T see any of the WP folders (wp-includes, wp-admin, wp-content).

My end goal is to have a startup script that:

initiates the DB proxy so all WP instances can share the same DC

initiates the mounting of the google cloud bucket so all instances can share the same WP files

Obviously, that isn't working right now.

What is going wrong here? I am also open to other ideas for how to make the WP files "persistent" and "shared" across all of the ephemeral instances that the instance group spins up.

答:
Try:
sudo nano /etc/rc.local

In the file after:

#By default this script does nothing...

gcsfuse -dir-mode=777 -o allow_other [bucket-name] /var/www/html/[folder-name if apply]

exit 0

Will be work to mount in every scaled instance your bucket.

Hope this help for somebody i realized that you Q has more than 6 months.

:)

Body:
I searched thoroughly and could not find any info on this issue.

Currently, I am building a Word Press site, hosted on Google Cloud's Compute Engine. The goal is to build an autoscaling WP site. I am currently attempting to build the instance template, which I can then use to deploy an instance group and subsequently setup the HTTP load balancer.

I am using a base Ubuntu 16.04 image, and from there I installed the rest of the LEMP stack.

I was successfully able to use the SQL proxy to connect to Cloud SQL so that all of the ephermal instances to be deployed will share the same database. To have the proxy initiated each time a new instance is spun up, I am using a startup script:

./cloud_sql_proxy -dir=/cloudsql &

But here's my issue right now: the Word Press files. I can't figure out a way to have all of the instances use the same WP files. I already tried to use Google Cloud Storage FUSE, but when I mount the bucket at the root directory, it deletes all of the WordPress folders (wp-content, wp-admin, wp-includes).

It's as if the instance can't "see" the folders I have in the google cloud storage. Here was my work flow:

setup LEMP with WordPress--got the site working on the front end--all systems go

copied all of the files/folders in my root directory (/var/www/html/) to google cloud bucket

gsutil -m cp -r /var/www/html/. gs://example-bucket/

Then I mounted the bucket at my directory

gcsfuse --dir-mode "777" -o allow_other example-bucket /var/www/html/

But now, when I "ls" inside of the root directory from the Linux terminal, I DON'T see any of the WP folders (wp-includes, wp-admin, wp-content).

My end goal is to have a startup script that:

initiates the DB proxy so all WP instances can share the same DC

initiates the mounting of the google cloud bucket so all instances can share the same WP files

Obviously, that isn't working right now.

What is going wrong here? I am also open to other ideas for how to make the WP files "persistent" and "shared" across all of the ephemeral instances that the instance group spins up.


问:
Maximum 20 cookie per domain - Why?
I've just come across an interesting fact, apparently a website can have up to 20 seperate cookies.

Ok - fair enough.

But why on earth would you store more than say "UserID", and why would you possibly need 20 cookies?

答:
If you offer the user a way to customize your site you need to store their settings somewhere.
You might need cookies for:

user settings

the session id

the contents of a shopping basket

the last item viewed

the user login

Title: Maximum 20 cookie per domain - Why?


问:
Using Xcode to compile -fvisibility=hidden
Anyone knows how to use Xcode to compile with -fvisibility=hidden

I am new to Xcode, Some screenshot would be better.

答:
go to your project's build settings in Xcode, use the search field to look for "Other C Flags" and then enter in "-fvisibility=hidden" like this:

More info can be seen in this very related question.


问:
laravel 5.4 Undefined property: stdClass::$id
I have two models artists and songs which have one-many relations, an Artist can have multiple songs. song belongs to one artist.

```<code>$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at')
            ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get();
 return return view('front.home', compact('videos', 'songs', 'artists', 'played', 'uploads', 'albums'));
</code>```

this is my Controller code. as u can see I added all artists songs week_hits and grouped by songs.artist_id

and this is my view.

```<code> @foreach($artists as $artist)
            <div class="artist-grid">
                <div class="art-img">
                    <a href="{{route('artist',['id' => $artist->id, 'slug' => $artist->slug])}}">
                        <img  src="image/small/{{$artist->image}}">
                    </a>
                </div>
                <div class="name">
                    <h3>{{$artist->name}}</h3>
                </div>
            </div>
             @endforeach
</code>```

but when i dd($artists) i can see all collection returned but when i send to the view iam getting this error message.

```<code>(2/2) ErrorException
Undefined property: stdClass::$id (View: C:\xampp\htdocs\laravel\resources\views\front\home.blade.php)
</code>```

but when I dd($artists) this is the output.

```<code>Collection {#293 ▼
  #items: array:4 [▼
    0 => {#307 ▼
      +"WEEKHITS": "39"
    }
    1 => {#292 ▼
      +"WEEKHITS": "9"
    }
    2 => {#278 ▼
      +"WEEKHITS": "4"
    }
    3 => {#308 ▼
      +"WEEKHITS": "1"
    }
  ]
}
</code>```

please really appreciate your help.

答:
Please have a look on your query, you have to select also id in SELECT() option in query.

```<code>$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at')
            ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS','artists.id as id'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get();
</code>```

OR

```<code>  $artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at')
                ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS','artists.*'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get();
</code>```

Body:
I have two models artists and songs which have one-many relations, an Artist can have multiple songs. song belongs to one artist.

$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at')
            ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get();
 return return view('front.home', compact('videos', 'songs', 'artists', 'played', 'uploads', 'albums'));

this is my Controller code. as u can see I added all artists songs week_hits and grouped by songs.artist_id

and this is my view.

 @foreach($artists as $artist)

                     $artist->id, 'slug' => $artist->slug])}}">
                        image}}">

{{$artist->name}}

             @endforeach

but when i dd($artists) i can see all collection returned but when i send to the view iam getting this error message.

(2/2) ErrorException
Undefined property: stdClass::$id (View: C:\xampp\htdocs\laravel\resources\views\front\home.blade.php)

but when I dd($artists) this is the output.

Collection {#293 ▼
  #items: array:4 [▼
    0 => {#307 ▼
      +"WEEKHITS": "39"
    }
    1 => {#292 ▼
      +"WEEKHITS": "9"
    }
    2 => {#278 ▼
      +"WEEKHITS": "4"
    }
    3 => {#308 ▼
      +"WEEKHITS": "1"
    }
  ]
}

please really appreciate your help.

Body:
Please have a look on your query, you have to select also id in SELECT() option in query.

$artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at')
            ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS','artists.id as id'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get();

OR

  $artists = DB::table('artists')->join('songs', 'artists.id', '=', 'songs.artist_id')->select('artists.*, songs.id, songs.title, songs.artist_id, songs.week_hits, songs.created_at')
                ->SELECT(DB::raw('sum(songs.week_hits) as WEEKHITS','artists.*'))->groupBy('songs.artist_id')->orderBy('WEEKHITS', 'DESC')->take(7)->get();


问:
Using contextlib with cython
As part of transitioning my game engine's code to cython, I am porting my Vertex Buffer Object (Vbo) class. I use this Vbo class to send 3D model data to the GPU. The code (vbo.pyx) currently looks like this:

```<code>cimport gl
from enum import Enum
import contextlib

class VboTarget(Enum):
    ARRAY = gl.GL_ARRAY_BUFFER
    INDEX = gl.GL_ELEMENT_ARRAY_BUFFER

cdef class Vbo:
    cdef readonly gl.GLuint id_
    cdef readonly double[:] data
    cdef readonly int target

    def __init__(self, data=None, target=VboTarget.ARRAY):
        gl.glewInit()
        gl.glGenBuffers(1, &self.id_)
        self.target = target.value
        if data is not None:
            self.data = data

    @contextlib.contextmanager
    def bind(self):
        gl.glBindBuffer(self.target, self.id_)
        try:
            yield
        finally:
            gl.glBindBuffer(self.target, 0)

    def set_data(self, new_data):
        self.data = new_data

    def update(self):#perform gpu update
        with self.bind():
            gl.glBufferData(self.target, self.data.nbytes, &self.data[0], gl.GL_DYNAMIC_DRAW)
</code>```

I would like to use contextlib as it would make ensuring that buffer binding and unbinding to the GPU would cleanly and automatically occur. The cython code compiles without error; however, when I import this cython module into my python code, I get the following error message:

```<code>Traceback (most recent call last):
  File "main.py", line 2, in <module>
    import vbo
  File "vbo.pyx", line 21, in init vbo (vbo.c:15766)
    @contextlib.contextmanager
  File "C:\Python27\lib\contextlib.py", line 82, in contextmanager
    @wraps(func)
  File "C:\Python27\lib\functools.py", line 33, in update_wrapper
    setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'method_descriptor' object has no attribute '__module__'
</code>```

I am not really sure how to interpret this message. Can I use contextlib decorators with a cdef class and if so, how? Is contextlib even compatible with cython?

Update:
Here is an alternative version using __enter__ and __exit__ instead:

```<code>cimport gl
from enum import Enum
from cpython cimport array
import array

class VboTarget(Enum):
    ARRAY = gl.GL_ARRAY_BUFFER
    INDEX = gl.GL_ELEMENT_ARRAY_BUFFER

cdef class Vbo:
    cdef readonly gl.GLuint id_
    cdef readonly float[:] data
    cdef readonly int target

    def __init__(self, data=None, target=VboTarget.ARRAY):
        gl.glewInit()
        gl.glGenBuffers(1, &self.id_)
        self.target = target.value
        if data is not None:
            self.data = data

    def set_data(self, float[:] new_data):
        self.data = new_data

    def update(self):#perform gpu update
        with self:
            gl.glBufferData(self.target, self.data.nbytes, &self.data[0], gl.GL_STATIC_DRAW)

    def __enter__(self):
        gl.glBindBuffer(self.target, self.id_)

    def __exit__(self, exc_type, exc_val, exc_tb):
        gl.glBindBuffer(self.target, 0)
</code>```

答: It looks like this is actually a non-issue now with the latest Cython master (Cython version 0.26b0). The simplified version of the contextlib code described in @DavidW's answer works perfectly as long as the binding=True hint is applied at the top of your source file. The discussion of this Cython issue can be found here.

Title: Using contextlib with cython

Body:
As part of transitioning my game engine's code to cython, I am porting my Vertex Buffer Object (Vbo) class. I use this Vbo class to send 3D model data to the GPU. The code (vbo.pyx) currently looks like this:

cimport gl
from enum import Enum
import contextlib

class VboTarget(Enum):
    ARRAY = gl.GL_ARRAY_BUFFER
    INDEX = gl.GL_ELEMENT_ARRAY_BUFFER

cdef class Vbo:
    cdef readonly gl.GLuint id_
    cdef readonly double[:] data
    cdef readonly int target

    def __init__(self, data=None, target=VboTarget.ARRAY):
        gl.glewInit()
        gl.glGenBuffers(1, &self.id_)
        self.target = target.value
        if data is not None:
            self.data = data

    @contextlib.contextmanager
    def bind(self):
        gl.glBindBuffer(self.target, self.id_)
        try:
            yield
        finally:
            gl.glBindBuffer(self.target, 0)

    def set_data(self, new_data):
        self.data = new_data

    def update(self):#perform gpu update
        with self.bind():
            gl.glBufferData(self.target, self.data.nbytes, &self.data[0], gl.GL_DYNAMIC_DRAW)

I would like to use contextlib as it would make ensuring that buffer binding and unbinding to the GPU would cleanly and automatically occur. The cython code compiles without error; however, when I import this cython module into my python code, I get the following error message:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    import vbo
  File "vbo.pyx", line 21, in init vbo (vbo.c:15766)
    @contextlib.contextmanager
  File "C:\Python27\lib\contextlib.py", line 82, in contextmanager
    @wraps(func)
  File "C:\Python27\lib\functools.py", line 33, in update_wrapper
    setattr(wrapper, attr, getattr(wrapped, attr))
AttributeError: 'method_descriptor' object has no attribute '__module__'

I am not really sure how to interpret this message. Can I use contextlib decorators with a cdef class and if so, how? Is contextlib even compatible with cython?

Update:
Here is an alternative version using __enter__ and __exit__ instead:

cimport gl
from enum import Enum
from cpython cimport array
import array

class VboTarget(Enum):
    ARRAY = gl.GL_ARRAY_BUFFER
    INDEX = gl.GL_ELEMENT_ARRAY_BUFFER

cdef class Vbo:
    cdef readonly gl.GLuint id_
    cdef readonly float[:] data
    cdef readonly int target

    def __init__(self, data=None, target=VboTarget.ARRAY):
        gl.glewInit()
        gl.glGenBuffers(1, &self.id_)
        self.target = target.value
        if data is not None:
            self.data = data

    def set_data(self, float[:] new_data):
        self.data = new_data

    def update(self):#perform gpu update
        with self:
            gl.glBufferData(self.target, self.data.nbytes, &self.data[0], gl.GL_STATIC_DRAW)

    def __enter__(self):
        gl.glBindBuffer(self.target, self.id_)

    def __exit__(self, exc_type, exc_val, exc_tb):
        gl.glBindBuffer(self.target, 0)


问:
angularJS cant find provider, and neither can I
I recently deployed some code to our site, and a page that was not touched got an error. I cannot reproduce the error on my local machine, and to make matters worse the error makes no sense. Here is the error

Error: $injector:unpr
Unknown Provider
Unknown provider: stationProvider <- station <- RSViewController

Here is my entire RSViewController:

```<code>(function () {
'use strict';

angular
    .module('packerapp.retail-shipment')
    .controller('RSViewController', RSViewController);

/* @ngInject */
function RSViewController(shipmentView, orderView, loggedInUser) {
    var vm = this;

    vm.shipmentView = shipmentView;
    vm.orderView = orderView;

    activate();

    function activate() {

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

The word station is not even in the page or any page near it. I couldn't find anywhere it would even want a station provider.

Any idea where to look?

答:
I found the problem!

My coworker made another controller with the same name as my controller. So there were two 'RSViewController's. So when the one was called the other one was called as well, and this broke everything for just that one page.

Body:
I recently deployed some code to our site, and a page that was not touched got an error. I cannot reproduce the error on my local machine, and to make matters worse the error makes no sense. Here is the error

Error: $injector:unpr
Unknown Provider
Unknown provider: stationProvider <- station <- RSViewController

Here is my entire RSViewController:

(function () {
'use strict';

angular
    .module('packerapp.retail-shipment')
    .controller('RSViewController', RSViewController);

/* @ngInject */
function RSViewController(shipmentView, orderView, loggedInUser) {
    var vm = this;

    vm.shipmentView = shipmentView;
    vm.orderView = orderView;

    activate();

    function activate() {

    }
}
})();

The word station is not even in the page or any page near it. I couldn't find anywhere it would even want a station provider.

Any idea where to look?


答: It's a choice. If you don't need 20 cookies, it doesn't mean somebody else won't.</p>

Title: Maximum 20 cookie per domain - Why?

Body:
I've just come across an interesting fact, apparently a website can have up to 20 seperate cookies.

Ok - fair enough.

But why on earth would you store more than say "UserID", and why would you possibly need 20 cookies?


问:
Error importing tensorflow in simple python code with import
I am trying to run sample code in tensor flow with only one line - import tensorflow as tf. But it gives this error.

```<code>Traceback (most recent call last):   File "sample.py", line 1, in <module>
    import tensorflow as tf   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 72, in <module>
    raise ImportError(msg) ImportError: Traceback (most recent call last):   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 61, in <module>
    from tensorflow.python import pywrap_tensorflow   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description) ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace above this error message when asking for help.
</code>```

CAN ANYONE HELP IN THIS?

答:
It is giving you this error because some how when you install cuda, it does not save its location in the environment.

```<code>ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory
</code>```

Export the path to cuda lib:

```<code>sudo ldconfig /usr/local/cuda/lib64
</code>```

cuda_version: 8.0

cuDNN_version: 5.1

Body:
I am trying to run sample code in tensor flow with only one line - import tensorflow as tf. But it gives this error.

Traceback (most recent call last):   File "sample.py", line 1, in <module>
    import tensorflow as tf   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 72, in <module>
    raise ImportError(msg) ImportError: Traceback (most recent call last):   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 61, in <module>
    from tensorflow.python import pywrap_tensorflow   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()   File "/home/djlimdiwala/.local/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description) ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace above this error message when asking for help.

CAN ANYONE HELP IN THIS?

Body:
It is giving you this error because some how when you install cuda, it does not save its location in the environment.

ImportError: libcudart.so.8.0: cannot open shared object file: No such file or directory

Export the path to cuda lib:

sudo ldconfig /usr/local/cuda/lib64

cuda_version: 8.0

cuDNN_version: 5.1


问:
Kafka - Producer Number of Batches
Is there a way to determine the number of batches that were created by a Kafka producer for a specific set of messages? For instance if I am sending 10K messages in a loop , is there a way to check how many batches were sent? I set the "batch.size" to a high value and my expectation was that the message will be buffered and there will be a delay in seeing the message in my consumer. However this seems to be printed almost immediately in my consumer program.

The default value if batch.size is 16384. Is this number of bytes?

```<code>import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class KafkaProducerApp {

    public static void main(String[] args){
        Properties properties = new Properties();
        properties.put("bootstrap.servers","localhost:9092,localhost:9093,localhost:9094");
        properties.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
        properties.put("acks","0");
        properties.put("batch.size",33554432);

        KafkaProducer<String,String> kafkaProducer = new KafkaProducer<String, String>(properties);
        Map<Integer,Integer> partitionCount = new HashMap<Integer,Integer>();
        partitionCount.put(0,0);
        partitionCount.put(1,0);
        partitionCount.put(2,0);

        try{
            Date from = new Date();
            for(int i=0;i<10000;i++) {
                RecordMetadata ack = kafkaProducer.send(new ProducerRecord<String, String>("test_topic", Integer.toString(i), "MyMessage" + Integer.toString(i))).get();
                //RecordMetadata ack = kafkaProducer.send(new ProducerRecord<String,String>("test_topic",0,Integer.toString(i), "MyMessage" + Integer.toString(i))).get();
                System.out.println(" Offset = " + ack.offset());
                System.out.println(" Partition = " + ack.partition());
                partitionCount.put(ack.partition(),partitionCount.get(ack.partition())+1);

            }
            Date to = new Date();
            System.out.println(" partition 0 =" + partitionCount.get(0));
            System.out.println(" partition 1 =" + partitionCount.get(1));
            System.out.println(" partition 2 =" + partitionCount.get(2));
            System.out.println(" Elapsed Time = " + (to.getTime()-from.getTime())/1000);

        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            kafkaProducer.close();
        }

    }

}
</code>```

答:
What you are asking for is the total number of produce requests.

You can see the average number of produce requests per second using the JMX Mbean kafka.producer:type=producer-metrics,client-id=([-.w]+)

Title: Kafka - Producer Number of Batches

Body:
Is there a way to determine the number of batches that were created by a Kafka producer for a specific set of messages? For instance if I am sending 10K messages in a loop , is there a way to check how many batches were sent? I set the "batch.size" to a high value and my expectation was that the message will be buffered and there will be a delay in seeing the message in my consumer. However this seems to be printed almost immediately in my consumer program.

The default value if batch.size is 16384. Is this number of bytes?

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class KafkaProducerApp {

    public static void main(String[] args){
        Properties properties = new Properties();
        properties.put("bootstrap.servers","localhost:9092,localhost:9093,localhost:9094");
        properties.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        properties.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
        properties.put("acks","0");
        properties.put("batch.size",33554432);

        KafkaProducer<String,String> kafkaProducer = new KafkaProducer<String, String>(properties);
        Map<Integer,Integer> partitionCount = new HashMap<Integer,Integer>();
        partitionCount.put(0,0);
        partitionCount.put(1,0);
        partitionCount.put(2,0);

        try{
            Date from = new Date();
            for(int i=0;i<10000;i++) {
                RecordMetadata ack = kafkaProducer.send(new ProducerRecord<String, String>("test_topic", Integer.toString(i), "MyMessage" + Integer.toString(i))).get();
                //RecordMetadata ack = kafkaProducer.send(new ProducerRecord<String,String>("test_topic",0,Integer.toString(i), "MyMessage" + Integer.toString(i))).get();
                System.out.println(" Offset = " + ack.offset());
                System.out.println(" Partition = " + ack.partition());
                partitionCount.put(ack.partition(),partitionCount.get(ack.partition())+1);

            }
            Date to = new Date();
            System.out.println(" partition 0 =" + partitionCount.get(0));
            System.out.println(" partition 1 =" + partitionCount.get(1));
            System.out.println(" partition 2 =" + partitionCount.get(2));
            System.out.println(" Elapsed Time = " + (to.getTime()-from.getTime())/1000);

        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            kafkaProducer.close();
        }

    }

}


问:
Reading notes from MIDI file using NAudio
Task is to get all notes and their time from MIDI file using NAudio library. So far I get all notes from file but I can't get their time.

```<code>            Note noteOn = new Note(); //custom class Note
            MidiFile midi = new MidiFile(open.FileName);
            List<TempoEvent> tempo = new List<TempoEvent>();

            for (int i = 0; i < midi.Events.Count(); i++)
            {
                foreach (MidiEvent note in midi.Events[i])
                {
                    TempoEvent tempoE;

                    try { tempoE = (TempoEvent)note; tempo.Add(tempoE); }
                    catch { }

                    if (note.CommandCode == MidiCommandCode.NoteOn)
                    {
                        var t_note = ( NoteOnEvent)note;

                        var noteOffEvent = t_note.OffEvent;

                        noteOn.NoteName.Add(t_note.NoteName);
                        noteOn.NoteNumber.Add(t_note.NoteNumber);
                        noteOn.NoteVelocity.Add(t_note.Velocity);
                        noteOn.NoteLenght.Add(t_note.NoteLength);

                        double d = (t_note.AbsoluteTime / midi.DeltaTicksPerQuarterNote) * tempo[tempo.Count() - 1].Tempo;

                        noteOn.StartTime.Add(TimeSpan.FromSeconds(d));
                    }

                }
            }
</code>```

Questions:

1) To get just list of notes I just look in NoteOnEvents or not? If I understand this correctly, each note has 'start' and 'end', start is defined by NoteOnEvent and 'end' is defined by NoteOffEvent. If I look in both events (NoteOn and NoteOff) I would get duplicate notes. Am I right?

2) How to get note's time? According to this post , I get some values but it seems that the first note's time is correct, but others don't. Also in this post, there is a comment which says the formula for calculating time must be:

```<code>((note.AbsTime - lastTempoEvent.AbsTime) / midi.ticksPerQuarterNote) * tempo + lastTempoEvent.RealTime.
</code>```

I don't know parameters lastTempoEvent.RealTime and tempo. It's it tempo of last tempo event or?

3) Reading MIDI file it's very slow, for a smaller files it's ok, but for a big files don't. This small files have ~150 NoteOnEvents and this bigger files have ~1250 NoteOnEvents, which isn't so 'heavy'. Why is so slow?

答:
You can take a look at other .NET libraries that provide MIDI file parsing. For example, with DryWetMIDI you can get all notes contained in a MIDI file with this code:

```<code>MidiFile file = MidiFile.Read("Great Song.mid");
IEnumerable<Note> notes = file.GetNotes();
</code>```

Note has Time and Length properties. Units of values returned by these properties defined by the time division of a MIDI file. But you can get time and length of a note in more understandable format. For hours, minutes, seconds you can write:

```<code>TempoMap tempoMap = file.GetTempoMap();
MetricTimeSpan metricTime = note.TimeAs<MetricTimeSpan>(tempoMap);
MetricTimeSpan metricLength = note.LengthAs<MetricTimeSpan>(tempoMap);
</code>```

Using TimeAs and LengthAs methods you don't need to do any calculations by yourself. Instance of MetricTimeSpan can be implicitly casted to TimeSpan.

Body:
Task is to get all notes and their time from MIDI file using NAudio library. So far I get all notes from file but I can't get their time.

            Note noteOn = new Note(); //custom class Note
            MidiFile midi = new MidiFile(open.FileName);
            List<TempoEvent> tempo = new List<TempoEvent>();

            for (int i = 0; i < midi.Events.Count(); i++)
            {
                foreach (MidiEvent note in midi.Events[i])
                {
                    TempoEvent tempoE;

                    try { tempoE = (TempoEvent)note; tempo.Add(tempoE); }
                    catch { }

                    if (note.CommandCode == MidiCommandCode.NoteOn)
                    {
                        var t_note = ( NoteOnEvent)note;

                        var noteOffEvent = t_note.OffEvent;

                        noteOn.NoteName.Add(t_note.NoteName);
                        noteOn.NoteNumber.Add(t_note.NoteNumber);
                        noteOn.NoteVelocity.Add(t_note.Velocity);
                        noteOn.NoteLenght.Add(t_note.NoteLength);

                        double d = (t_note.AbsoluteTime / midi.DeltaTicksPerQuarterNote) * tempo[tempo.Count() - 1].Tempo;

                        noteOn.StartTime.Add(TimeSpan.FromSeconds(d));
                    }

                }
            }

Questions:

1) To get just list of notes I just look in NoteOnEvents or not? If I understand this correctly, each note has 'start' and 'end', start is defined by NoteOnEvent and 'end' is defined by NoteOffEvent. If I look in both events (NoteOn and NoteOff) I would get duplicate notes. Am I right?

2) How to get note's time? According to this post , I get some values but it seems that the first note's time is correct, but others don't. Also in this post, there is a comment which says the formula for calculating time must be:

((note.AbsTime - lastTempoEvent.AbsTime) / midi.ticksPerQuarterNote) * tempo + lastTempoEvent.RealTime.

I don't know parameters lastTempoEvent.RealTime and tempo. It's it tempo of last tempo event or?

3) Reading MIDI file it's very slow, for a smaller files it's ok, but for a big files don't. This small files have ~150 NoteOnEvents and this bigger files have ~1250 NoteOnEvents, which isn't so 'heavy'. Why is so slow?

Body:
You can take a look at other .NET libraries that provide MIDI file parsing. For example, with DryWetMIDI you can get all notes contained in a MIDI file with this code:

MidiFile file = MidiFile.Read("Great Song.mid");
IEnumerable<Note> notes = file.GetNotes();

Note has Time and Length properties. Units of values returned by these properties defined by the time division of a MIDI file. But you can get time and length of a note in more understandable format. For hours, minutes, seconds you can write:

TempoMap tempoMap = file.GetTempoMap();
MetricTimeSpan metricTime = note.TimeAs<MetricTimeSpan>(tempoMap);
MetricTimeSpan metricLength = note.LengthAs<MetricTimeSpan>(tempoMap);

Using TimeAs and LengthAs methods you don't need to do any calculations by yourself. Instance of MetricTimeSpan can be implicitly casted to TimeSpan.


问:
Strange behavior with dynamic char ** in C
I used to code in C a long time ago and I seem to have lost my chops.

I am experiencing some odd behavior with a dynamic char * array. I have a curses window (implemented in another file) that is to display a list of strings of active CU and TTY devices on my local machine. I attempt to zero-initialize a char ** array with calloc, and then grow it by one appropriate size each time (dir->d_name) matches my string comparisons.

The problem is that these strings display half the time upon running the program, and the other half of the time they are garbled or blank.

I suspect this is a memory/pointer issue related to either malloc() or calloc(), but I have been unable to pinpoint my misunderstanding for several days. Here is the code:

```<code>#include <stdio.h>
#include "funcs.h"
#include <ncurses.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>

#define arraysize(ar) sizeof(ar)/sizeof(ar[0])

int main(void)
{
    char ch;
    const char tty[4] = "tty.";
    const char cu[3] = "cu.";
    const char *directory = "/dev/";
    const char **devices = calloc(0,sizeof(const char *));

    // Initial device list gen //

    DIR *d;
    struct dirent *dir;
    int count=0;
    d = opendir(directory);
    if (d != NULL)
    {
        while((dir = readdir(d)))
        {
            if(strncmp(dir->d_name,tty,4)==0 || strncmp(dir->d_name,cu,3)==0)
            {
                count++;
                devices = realloc(devices,(count+1)*sizeof(const char *));
                devices[count-1] = (dir->d_name);
            }
        }
        closedir(d);
    }
printf("\n%d\n",count);

struct display MAIN = screen_init();

// Display List //

list_devices(devices,count,MAIN.devpad);
while(ch != 'q')
{
    ch = getch();
}
endwin();
}
</code>```

Thank you for your time/attention.

答:
The biggest problem here is that you're not copying the dir d_name buffer. As the manual says:

The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream.

This means you need to explicitly copy it:

```<code>devices[count-1] = strdup(dir->d_name);
</code>```

That should eliminate a lot of the garbling.

Body:
I used to code in C a long time ago and I seem to have lost my chops.

I am experiencing some odd behavior with a dynamic char * array. I have a curses window (implemented in another file) that is to display a list of strings of active CU and TTY devices on my local machine. I attempt to zero-initialize a char ** array with calloc, and then grow it by one appropriate size each time (dir->d_name) matches my string comparisons.

The problem is that these strings display half the time upon running the program, and the other half of the time they are garbled or blank.

I suspect this is a memory/pointer issue related to either malloc() or calloc(), but I have been unable to pinpoint my misunderstanding for several days. Here is the code:

#include <stdio.h>
#include "funcs.h"
#include <ncurses.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>

#define arraysize(ar) sizeof(ar)/sizeof(ar[0])

int main(void)
{
    char ch;
    const char tty[4] = "tty.";
    const char cu[3] = "cu.";
    const char *directory = "/dev/";
    const char **devices = calloc(0,sizeof(const char *));

    // Initial device list gen //

    DIR *d;
    struct dirent *dir;
    int count=0;
    d = opendir(directory);
    if (d != NULL)
    {
        while((dir = readdir(d)))
        {
            if(strncmp(dir->d_name,tty,4)==0 || strncmp(dir->d_name,cu,3)==0)
            {
                count++;
                devices = realloc(devices,(count+1)*sizeof(const char *));
                devices[count-1] = (dir->d_name);
            }
        }
        closedir(d);
    }
printf("\n%d\n",count);

struct display MAIN = screen_init();

// Display List //

list_devices(devices,count,MAIN.devpad);
while(ch != 'q')
{
    ch = getch();
}
endwin();
}

Thank you for your time/attention.

Body:
The biggest problem here is that you're not copying the dir d_name buffer. As the manual says:

The data returned by readdir() may be overwritten by subsequent calls to readdir() for the same directory stream.

This means you need to explicitly copy it:

devices[count-1] = strdup(dir->d_name);

That should eliminate a lot of the garbling.


问:
Parse TXT file to Batch file
I am wanting to set a variable one line at a time from a text file, run a particular command using this variable, then loop back, grab the second line, process the command, and so on until the file ends.

The batch file works well and asks for user input, then processes using the input as the variable with no problems at all. The script gets the computer name first, then copies the install files to the local machine the uses WMIC to install the MSI:

```<code>@echo off
SET /P computer=Enter Computer Name
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"
</code>```

The text file will look something like this:

```<code>PC-01
PC-02
PC-27
Odd-PC
</code>```

However, when I try to introduce a "for" loop, so that I can process a hundred or more machines one at a time, nothing happens. Even if I have only one line in the file I cannot get it to work. This is what I have tried:

```<code>@echo off
For /F %%i in (c:\test.txt) do (
set computer=%%i
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"
)
</code>```

For the record I have tried the variables with %%computer%% and !computer! with no success.

I have also tried the following also with or without the /p in the "SET" command:

```<code>@echo off
SET /P computer=<"c:\test.txt"
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"
</code>```

I would appreciate any suggestions or input.

答:
You'd need to reference some of the SO articles on delayed expansion for details about how it works.

In order to use the !var! syntax (which would work in place of %var% in your first for loop) you need to have executed

```<code>setlocal enabledelayedexpansion
</code>```

earlier in the batch (as part of the mainline, not the loop - for instance, directly after the @echo off or before the for loop)

However, in your case, since computer is set to %%i, replacing %computer% with %%i should be an easier solution.

Expected resultant code:

```<code>@echo off
setlocal enabledelayedexpansion
For /F %%i in (c:\test.txt) do (
set computer=%%i
echo.
XCopy "\\server\netlogon\temp\*.*" "\\!computer!\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"!computer!" product call install true,"","c:\temp\msi_to_install.msi"
)
</code>```

or

```<code>@echo off
For /F %%i in (c:\test.txt) do (
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%%i\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%%i" product call install true,"","c:\temp\msi_to_install.msi"
)
</code>```

Title: Parse TXT file to Batch file

Body:
I am wanting to set a variable one line at a time from a text file, run a particular command using this variable, then loop back, grab the second line, process the command, and so on until the file ends.

The batch file works well and asks for user input, then processes using the input as the variable with no problems at all. The script gets the computer name first, then copies the install files to the local machine the uses WMIC to install the MSI:

@echo off
SET /P computer=Enter Computer Name
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"

The text file will look something like this:

PC-01
PC-02
PC-27
Odd-PC

However, when I try to introduce a "for" loop, so that I can process a hundred or more machines one at a time, nothing happens. Even if I have only one line in the file I cannot get it to work. This is what I have tried:

@echo off
For /F %%i in (c:\test.txt) do (
set computer=%%i
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"
)

For the record I have tried the variables with %%computer%% and !computer! with no success.

I have also tried the following also with or without the /p in the "SET" command:

@echo off
SET /P computer=<"c:\test.txt"
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%computer%\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%computer%" product call install true,"","c:\temp\msi_to_install.msi"

I would appreciate any suggestions or input.

Body:
You'd need to reference some of the SO articles on delayed expansion for details about how it works.

In order to use the !var! syntax (which would work in place of %var% in your first for loop) you need to have executed

setlocal enabledelayedexpansion

earlier in the batch (as part of the mainline, not the loop - for instance, directly after the @echo off or before the for loop)

However, in your case, since computer is set to %%i, replacing %computer% with %%i should be an easier solution.

Expected resultant code:

@echo off
setlocal enabledelayedexpansion
For /F %%i in (c:\test.txt) do (
set computer=%%i
echo.
XCopy "\\server\netlogon\temp\*.*" "\\!computer!\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"!computer!" product call install true,"","c:\temp\msi_to_install.msi"
)

or

@echo off
For /F %%i in (c:\test.txt) do (
echo.
XCopy "\\server\netlogon\temp\*.*" "\\%%i\c$\temp\*.*" /E /C /H /R /Y
WMIC /Node:"%%i" product call install true,"","c:\temp\msi_to_install.msi"
)


问:
Throttling comments
I want to make it so a user can only post 1 comment per minute at most.

I've tried simply using the throttle middleware and it is not working. I can still post comments every second.

Route code:

```<code>Route::post('comment/{id}', 'HomeController@comment')->name('comment')->middleware('throttle');
</code>```

Controller code:

```<code>public function comment($id)
{
    $this->validate(request(), [
        "body" => "required",
    ]);

    $jersey = Jersey::findOrFail($id);
    $comment = new Comment;
    $comment->user_id = auth()->user()->id;
    $comment->jersey_id = $jersey->id;
    $comment->body = request()->input('body');
    $comment->save();
    activity()->by(auth()->user())->withProperties($comment)->log('Commented');
    request()->session()->flash('status', 'Comment submitted!');

    return redirect()->route('concept', $id);
}
</code>```

How do I make it so that it will flash an error instead of saving if the user is attempting to post more than 1 comment per minute?

答: I ended up using the https://github.com/GrahamCampbell/Laravel-Throttle package.</p>

Title: Throttling comments

Body:
I want to make it so a user can only post 1 comment per minute at most.

I've tried simply using the throttle middleware and it is not working. I can still post comments every second.

Route code:

Route::post('comment/{id}', 'HomeController@comment')->name('comment')->middleware('throttle');

Controller code:

public function comment($id)
{
    $this->validate(request(), [
        "body" => "required",
    ]);

    $jersey = Jersey::findOrFail($id);
    $comment = new Comment;
    $comment->user_id = auth()->user()->id;
    $comment->jersey_id = $jersey->id;
    $comment->body = request()->input('body');
    $comment->save();
    activity()->by(auth()->user())->withProperties($comment)->log('Commented');
    request()->session()->flash('status', 'Comment submitted!');

    return redirect()->route('concept', $id);
}

How do I make it so that it will flash an error instead of saving if the user is attempting to post more than 1 comment per minute?


问:
Ecto changeset - skip nil fields
How do I add a field to a changeset only if the field is not nil? I don't want to update the value in the database if the value is nil. I need to check 3 fields and only update the ones that are not nil.

current code:

```<code>  put "/products" do
    errors = {}
    IO.inspect(conn.body_params)

    product = Api.Product |> Api.Repo.get(conn.query_params["id"])
    IO.inspect(product)

    if conn.body_params["image"] do
      changeset = Api.Product.changeset(product, %{image: conn.body_params["image"]})
    end

    if conn.body_params["description"] do
      changeset = Api.Product.changeset(product, %{description: conn.body_params["description"]})
    end

    if conn.body_params["price"] do
      changeset = Api.Product.changeset(product, %{price: conn.body_params["price"]})
    end
    case Api.Repo.update(changeset) do
      {:ok, product} ->
        errors = Tuple.append(errors, "Product updated")
      {:error, changeset} ->
        errors = Tuple.append(errors, "Product not updated")
    end

    conn
      |> put_resp_content_type("application/json")
      |> send_resp(200, Poison.encode!(%{
          successs: "success",
          errors: Tuple.to_list(errors)
      }))
  end
</code>```

答:
This is what validate_required/3 is for.
https://hexdocs.pm/ecto/Ecto.Changeset.html#validate_required/3

You pass it your changeset and a list of required fields as atoms. If any of the specified fields are not present (ie, nil), then an error will be added to your changeset and it will also be flagged as invalid.

```<code>iex> changeset |> validate_required([:field1, :field2, :field3])
%Ecto.Changeset{valid?: false, errors: %{"field1" => ["can't be blank"]}}
</code>```

PS. you don't need to manage errors yourself as you're doing above. Errors will be automatically added to your changeset at changeset.errors.

Title: Ecto changeset - skip nil fields

Body:
How do I add a field to a changeset only if the field is not nil? I don't want to update the value in the database if the value is nil. I need to check 3 fields and only update the ones that are not nil.

current code:

  put "/products" do
    errors = {}
    IO.inspect(conn.body_params)

    product = Api.Product |> Api.Repo.get(conn.query_params["id"])
    IO.inspect(product)

    if conn.body_params["image"] do
      changeset = Api.Product.changeset(product, %{image: conn.body_params["image"]})
    end

    if conn.body_params["description"] do
      changeset = Api.Product.changeset(product, %{description: conn.body_params["description"]})
    end

    if conn.body_params["price"] do
      changeset = Api.Product.changeset(product, %{price: conn.body_params["price"]})
    end
    case Api.Repo.update(changeset) do
      {:ok, product} ->
        errors = Tuple.append(errors, "Product updated")
      {:error, changeset} ->
        errors = Tuple.append(errors, "Product not updated")
    end

    conn
      |> put_resp_content_type("application/json")
      |> send_resp(200, Poison.encode!(%{
          successs: "success",
          errors: Tuple.to_list(errors)
      }))
  end

Body:
This is what validate_required/3 is for.
https://hexdocs.pm/ecto/Ecto.Changeset.html#validate_required/3

You pass it your changeset and a list of required fields as atoms. If any of the specified fields are not present (ie, nil), then an error will be added to your changeset and it will also be flagged as invalid.

iex> changeset |> validate_required([:field1, :field2, :field3])
%Ecto.Changeset{valid?: false, errors: %{"field1" => ["can't be blank"]}}

PS. you don't need to manage errors yourself as you're doing above. Errors will be automatically added to your changeset at changeset.errors.


问:
ERROR for site owner: Invalid site key
I created a reCAPTCHA key and disabled Verify the origin of reCAPTCHA solutions, yet I am still getting there error ERROR for site owner: Invalid site key.

How do I fix this?

答: Right so it appears the reCAPTCHA unverified keys simply don't work and they don't seem to give a shit about fixing it. Ended up just specifying the domains.</p>

Title: ERROR for site owner: Invalid site key


问:
Do Some Process And Download File .NET MVC
I wanna create an excel , save it and download it. But while the excel file is being created , I want the user to should do different processes. That's my controller action:

```<code>[HttpGet]
    public async Task<ActionResult> CreateExcel() {

        var path = string.Empty;

        await Task.Factory.StartNew(() => {
            path = SaveExcel();
        });

        return File(System.IO.File.ReadAllBytes($"{path}.xls"),
            System.Net.Mime.MediaTypeNames.Application.Octet,$"{Guid.NewGuid()}.xls");

    }

private string SaveExcel() {
        //this method will create an excel File and will return the file's path.
    }
</code>```

but when I jump to another URL , the download is being cancelled.

答:
You cannot parallel your application like that. If you want to allow a user to do other things, while Excel is generating, I want to suggest you this way.

Open new popup with the text "Please wait, your Excel is generating" and in this popup, you can make GET call to your controller action. Meantime, user will be able to browse website in the main window

```<code> <a id="generateExcel">Generate excel for me</a>

<script>
    $(document).ready(function(){
        $('#generateExcel').click(function() {
            var url = '{LINK_TO_YOUR_CREATE_EXCEL_URL}';
            var newWindow = window.open('', 'popUpWindow', 'height=500,width=500,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes');
            newWindow.document.write("<html><head></head><body>Please wait, your excel is generating<script>window.location='"+url+"'</script></body></html>");
            newWindow.document.close();
            return false;
        })
    })
</script>
</code>```

Body:
I wanna create an excel , save it and download it. But while the excel file is being created , I want the user to should do different processes. That's my controller action:

[HttpGet]
    public async Task<ActionResult> CreateExcel() {

        var path = string.Empty;

        await Task.Factory.StartNew(() => {
            path = SaveExcel();
        });

        return File(System.IO.File.ReadAllBytes($"{path}.xls"),
            System.Net.Mime.MediaTypeNames.Application.Octet,$"{Guid.NewGuid()}.xls");

    }

private string SaveExcel() {
        //this method will create an excel File and will return the file's path.
    }

but when I jump to another URL , the download is being cancelled.

Body:
You cannot parallel your application like that. If you want to allow a user to do other things, while Excel is generating, I want to suggest you this way.

Open new popup with the text "Please wait, your Excel is generating" and in this popup, you can make GET call to your controller action. Meantime, user will be able to browse website in the main window

 <a id="generateExcel">Generate excel for me</a>

<script>
    $(document).ready(function(){
        $('#generateExcel').click(function() {
            var url = '{LINK_TO_YOUR_CREATE_EXCEL_URL}';
            var newWindow = window.open('', 'popUpWindow', 'height=500,width=500,resizable=no,scrollbars=no,toolbar=no,menubar=no,location=no,directories=no,status=yes');
            newWindow.document.write("<html><head></head><body>Please wait, your excel is generating<script>window.location='"+url+"'</script></body></html>");
            newWindow.document.close();
            return false;
        })
    })
</script>


问:
count the number of zero group bits in a number
How do you count the number of zero group bits in a number? group bits
is any consecutive zero or one bits, for example, 2 is represented
as ....0000000000000000010 has two zero bits groups the least
significant bit and the group starts after one.
Also, I am in a bad need for algorithms on bits manipulation if any
one has a reference, please share</p>

答:
Andrew's solution is without doubt the simplest to design and implement, but I can't help but wonder if there is a quicker solution using bigger bit masks.

At a job interview I was asked to write some code to identify the most significant set bit. After spending a few minutes coming up with an ultra slim ultra fast binary search using shrinking bitmasks, which I kept suddenly realising could be optimised further, and further, resulting in large quantities of scribbles on lots of pieces of paper, the examiner looked at me blankly and asked if I knew how to use a for loop.

Maybe he should have just asked me to use a for loop to solve the problem.

Anyway it's not impossible that a similar such solution exists here.


问:
Customize Joomla 3.7 search : searchareas by default
I would like to customize Joomla 3.7 search (default area checked = SP page, Jevents pages unchecked).

See screenshot

Thanks for your help

What I would like to do

答:
You can do an override:
Copy the file "modules\mod_search\tmpl\default.php" into the folder "templates\YOUR_TEMPLATE\html\mod_search\" and modify it as you like.


问:
C++ Armadillo and OpenMp: Parallelization of summation of outer products - define reduction for Armadillo matrix
I am trying to parallelize a for loop using OpenMP which sums over Armadillo matrices. I have the following code:

```<code>#include <armadillo>
#include <omp.h>

int main()
{

        arma::mat A = arma::randu<arma::mat>(1000,700);
        arma::mat X = arma::zeros(700,700);
        arma::rowvec point = A.row(0);

        # pragma omp parallel for shared(A) reduction(+:X)
        for(unsigned int i = 0; i < A.n_rows; i++){
                arma::rowvec diff = point - A.row(i);
                X += diff.t() * diff; // Adding the matrices to X here
        }

}
</code>```

I am getting this error:

```<code>[Legendre@localhost ~]$ g++ test2.cpp -o test2 -O2 -larmadillo -fopenmp
test2.cpp: In function ‘int main()’:
test2.cpp:11:52: error: user defined reduction not found for ‘X’
</code>```

I read up on defining reductions, but I haven't found examples for working with Armadillo matrices. What is the best way to define a reduction for Armadillo matrices in my case?

答:
Those reductions are only available for built-in types (double, int, etc.).  Thus you have to do the reduction yourself, which is simple.  Just accumulate the results for each thread in a thread-local variable and add this to the global result within a critical section.

```<code>#include <armadillo>
#include <omp.h>

int main()
{

  arma::mat A = arma::randu<arma::mat>(1000,700);
  arma::mat X = arma::zeros(700,700);
  arma::rowvec point = A.row(0);

  #pragma omp parallel shared(A)
  {
    arma::mat X_local = arma::zeros(700,700);

    #pragma omp for
    for(unsigned int i = 0; i < A.n_rows; i++)
    {
      arma::rowvec diff = point - A.row(i);
      X_local += diff.t() * diff; // Adding the matrices to X here
    }

    #pragma omp critical
    X += X_local;
  }
}
</code>```

With more recent OpenMP (4.5 I think?) you can also declare a user-defined reduction for your type.

```<code>#include <armadillo>
#include <omp.h>

#pragma omp declare reduction( + : arma::mat : omp_out += omp_in ) \
  initializer( omp_priv = omp_orig )

int main()
{

  arma::mat A = arma::randu<arma::mat>(1000,700);
  arma::mat X = arma::zeros(700,700);
  arma::rowvec point = A.row(0);

  #pragma omp parallel shared(A) reduction(+:X)
  for(unsigned int i = 0; i < A.n_rows; i++)
  {
    arma::rowvec diff = point - A.row(i);
    X += diff.t() * diff; // Adding the matrices to X here
  }
}
</code>```

Body:
I am trying to parallelize a for loop using OpenMP which sums over Armadillo matrices. I have the following code:

#include <armadillo>
#include <omp.h>

int main()
{

        arma::mat A = arma::randu<arma::mat>(1000,700);
        arma::mat X = arma::zeros(700,700);
        arma::rowvec point = A.row(0);

        # pragma omp parallel for shared(A) reduction(+:X)
        for(unsigned int i = 0; i < A.n_rows; i++){
                arma::rowvec diff = point - A.row(i);
                X += diff.t() * diff; // Adding the matrices to X here
        }

}

I am getting this error:

[Legendre@localhost ~]$ g++ test2.cpp -o test2 -O2 -larmadillo -fopenmp
test2.cpp: In function ‘int main()’:
test2.cpp:11:52: error: user defined reduction not found for ‘X’

I read up on defining reductions, but I haven't found examples for working with Armadillo matrices. What is the best way to define a reduction for Armadillo matrices in my case?

Body:
Those reductions are only available for built-in types (double, int, etc.).  Thus you have to do the reduction yourself, which is simple.  Just accumulate the results for each thread in a thread-local variable and add this to the global result within a critical section.

#include <armadillo>
#include <omp.h>

int main()
{

  arma::mat A = arma::randu<arma::mat>(1000,700);
  arma::mat X = arma::zeros(700,700);
  arma::rowvec point = A.row(0);

  #pragma omp parallel shared(A)
  {
    arma::mat X_local = arma::zeros(700,700);

    #pragma omp for
    for(unsigned int i = 0; i < A.n_rows; i++)
    {
      arma::rowvec diff = point - A.row(i);
      X_local += diff.t() * diff; // Adding the matrices to X here
    }

    #pragma omp critical
    X += X_local;
  }
}

With more recent OpenMP (4.5 I think?) you can also declare a user-defined reduction for your type.

#include <armadillo>
#include <omp.h>

#pragma omp declare reduction( + : arma::mat : omp_out += omp_in ) \
  initializer( omp_priv = omp_orig )

int main()
{

  arma::mat A = arma::randu<arma::mat>(1000,700);
  arma::mat X = arma::zeros(700,700);
  arma::rowvec point = A.row(0);

  #pragma omp parallel shared(A) reduction(+:X)
  for(unsigned int i = 0; i < A.n_rows; i++)
  {
    arma::rowvec diff = point - A.row(i);
    X += diff.t() * diff; // Adding the matrices to X here
  }
}


问:
How to generically move data out of an indexable collection?
The I/O project example in the Rust book suggests cloning the command line args:

```<code>fn main() {
    let args: Vec<String> = env::args().collect();
    let config = parse_config(&args);
    // ...
}

struct Config {
    query: String,
    filename: String,
}

fn parse_config(args: &[String]) -> Config {
    let query = args[1].clone();
    let filename = args[2].clone();

    Config {
        query, filename
    }
}
</code>```

I would like to move the values into the Config struct to avoid the copy.

I tried moving the slice:

```<code>fn parse_config(args: [String]) -> Config
</code>```

But got the error:

the trait `std::marker::Sized` is not implemented for `[std::string::String]`
```

<p>Which makes sense because it's now reading as an unsized array. Next I tried generics:</p>

```fn parse_config<T: std::ops::Index<usize, Output=String> + Sized>(args: T) -> Config
```

<p>Which gives the error:</p>

<pre class="lang-none prettyprint-override"><code>cannot move out of indexed content
</code>```

This also makes sense, as it would leave the vector in an invalid state. I could move the vector:

```<code>fn parse_config(mut args: Vec<String>) -> Config {
    let query = args.remove(1);
    // ...
</code>```

But now the function is tied to the particular container Vector.

How would I write a function that consumes the vector and allows me to move out its contents, while still preserving the generic nature of the function?

答:
The answer is to use a consuming iterator:

```<code>    ...
    let config = parse_config(args.into_iter());
    ...

fn parse_config<T: Iterator<Item=String>>(mut args: T) -> Config {
    let query = args.nth(1).expect("First arg none");
    let filename = args.nth(0).expect("Second arg none");
    ...
}
</code>```

Note that the nth function is advancing and consuming the iterator, so that instead of the second argument indexing at 2, it is now one iteration later, i.e. 0.

Body:
The I/O project example in the Rust book suggests cloning the command line args:

fn main() {
    let args: Vec<String> = env::args().collect();
    let config = parse_config(&args);
    // ...
}

struct Config {
    query: String,
    filename: String,
}

fn parse_config(args: &[String]) -> Config {
    let query = args[1].clone();
    let filename = args[2].clone();

    Config {
        query, filename
    }
}

I would like to move the values into the Config struct to avoid the copy.

I tried moving the slice:

fn parse_config(args: [String]) -> Config

But got the error:

the trait `std::marker::Sized` is not implemented for `[std::string::String]`

Which makes sense because it's now reading as an unsized array. Next I tried generics:

fn parse_config<T: std::ops::Index<usize, Output=String> + Sized>(args: T) -> Config

Which gives the error:

cannot move out of indexed content

This also makes sense, as it would leave the vector in an invalid state. I could move the vector:

fn parse_config(mut args: Vec<String>) -> Config {
    let query = args.remove(1);
    // ...

But now the function is tied to the particular container Vector.

How would I write a function that consumes the vector and allows me to move out its contents, while still preserving the generic nature of the function?

Body:
The answer is to use a consuming iterator:

    ...
    let config = parse_config(args.into_iter());
    ...

fn parse_config<T: Iterator<Item=String>>(mut args: T) -> Config {
    let query = args.nth(1).expect("First arg none");
    let filename = args.nth(0).expect("Second arg none");
    ...
}

Note that the nth function is advancing and consuming the iterator, so that instead of the second argument indexing at 2, it is now one iteration later, i.e. 0.


问:
Javascript - only allow numbers in input field & a character counter
I have an input field. I want it so that only numbers can be used in the input field.

Below the input field I also want a counter that shows the number of characters currently inside the input field.

HTML:

```<code><input type="text" id="test" onkeypress="return isNumber(event)" />
<p id='demo'></p>
</code>```

Javascript:

```<code>function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
    let inputLength = inputValue.length;
    document.getElementById("demo").innerHTML = inputLength;
    return true;
    }
</code>```

jsfiddle:
http://jsfiddle.net/s831nwej/

It almost works. The problem is that the character counter below the input box is always 1 character less than the total number of characters in the input field. I think there is some quark about the keypress event that I am missing.

答:
Calculate the count within keyup event or html5 input event handler.

HTML :

```<code> <input type="text" id="test"
     oninput="calculate(this)"
     onkeypress="return isNumber(event)"/>

<p id='demo'></p>
</code>```

JavaScript :

```<code>// function for preventing certain characters
function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

// function for calculating the length where element
// reference passed as an argument
function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;
}
</code>```

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="test" oninput="calculate(this)" onkeypress="return isNumber(event)" />
<p id='demo'></p></code>```

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="test" onkeyup="calculate(this)" onkeypress="return isNumber(event)" />
<p id='demo'></p></code>```

There is a better way using a number input type in html5 which only accept the number input.

HTML :

```<code> <input type="number" id="test"
      oninput="calculate(this)"/>

<p id='demo'></p>
</code>```

JavaScript :

```<code>// function for calculating the length where element
// reference passed as an argument
function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;
}
</code>```

function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="test" oninput="calculate(this)" />

<p id='demo'></p></code>```

Body:
I have an input field. I want it so that only numbers can be used in the input field.

Below the input field I also want a counter that shows the number of characters currently inside the input field.

HTML:

<input type="text" id="test" onkeypress="return isNumber(event)" />

Javascript:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    let inputValue = document.getElementById('test').value;
    let inputLength = inputValue.length;
    document.getElementById("demo").innerHTML = inputLength;
    return true;
    }

jsfiddle:
http://jsfiddle.net/s831nwej/

It almost works. The problem is that the character counter below the input box is always 1 character less than the total number of characters in the input field. I think there is some quark about the keypress event that I am missing.

Body:
Calculate the count within keyup event or html5 input event handler.

HTML :

 <input type="text" id="test"
     oninput="calculate(this)"
     onkeypress="return isNumber(event)"/>

<p id='demo'></p>

JavaScript :

// function for preventing certain characters
function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

// function for calculating the length where element
// reference passed as an argument
function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;
}

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;

}

<input type="text" id="test" oninput="calculate(this)" onkeypress="return isNumber(event)" />
<p id='demo'></p>

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
}

function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;

}

<input type="text" id="test" onkeyup="calculate(this)" onkeypress="return isNumber(event)" />
<p id='demo'></p>

There is a better way using a number input type in html5 which only accept the number input.

HTML :

 <input type="number" id="test"
      oninput="calculate(this)"/>

<p id='demo'></p>

JavaScript :

// function for calculating the length where element
// reference passed as an argument
function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;
}

function calculate(ele) {
  let inputLength = ele.value.length;
  document.getElementById("demo").innerHTML = inputLength;
}

<input type="number" id="test" oninput="calculate(this)" />

<p id='demo'></p>