问:
Make sure Java will not close OutputStream before PrinWriter.print() finishes
I'm developing a distributed system that receives requests via Socket and writes the results back using OutputStream.

I'm facing problems because I have to return a very large string, but Java just keeps the execution of the code after I call the method print() without it finished printing:

```<code>public void attendRequisition(Socket clientSocket) {
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());

    pw.print(getResults());

    pw.close()
}
</code>```

Some information:

I need to close the connection after sending the results.

Without the close() instruction, the whole printing process takes about 3~5 seconds to finishes

I'm using telnet to test this method, and I can see the message coming and being cut becase of Java running the close() instruction

I can't count with receiving client's feedback

I believe this is happening because Java thinks the method print() finished executing, but what might be happening is that Java sends the message to the JVM, and JVM send it to the network adapter, and since the message is very large, close() method is called before the network adapter is able to send the entire message.

What I need is a way to make sure Java will only run the instruction close() after the printing process finished and the client received the entire message.

UPDATE: I was able to get it working properly by adding a Thread.sleep(). By doing this, the SO has enough time to send the message before Java closes the connection. But I don't want to use this solution, it implicates on too many problems.

答: I was able to solve the problem using DataOutputStream.writeBytes(). This way, the execution only continues when the method finishes sending the data. It is slower, but works.

Body:
I'm developing a distributed system that receives requests via Socket and writes the results back using OutputStream.

I'm facing problems because I have to return a very large string, but Java just keeps the execution of the code after I call the method print() without it finished printing:

public void attendRequisition(Socket clientSocket) {
    PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());

    pw.print(getResults());

    pw.close()
}

Some information:

I need to close the connection after sending the results.

Without the close() instruction, the whole printing process takes about 3~5 seconds to finishes

I'm using telnet to test this method, and I can see the message coming and being cut becase of Java running the close() instruction

I can't count with receiving client's feedback

I believe this is happening because Java thinks the method print() finished executing, but what might be happening is that Java sends the message to the JVM, and JVM send it to the network adapter, and since the message is very large, close() method is called before the network adapter is able to send the entire message.

What I need is a way to make sure Java will only run the instruction close() after the printing process finished and the client received the entire message.

UPDATE: I was able to get it working properly by adding a Thread.sleep(). By doing this, the SO has enough time to send the message before Java closes the connection. But I don't want to use this solution, it implicates on too many problems.


来源: stackexchange

问:
MySQL to PostgreSQL: How to modify this SQL query?
I have this MySQL query that makes use of MONTH() and YEAR():

```<code>SELECT
  MONTH(created_at) AS month,
  YEAR(created_at) AS year
FROM users
GROUP BY MONTH(created_at), YEAR(created_at)
ORDER BY YEAR(created_at), MONTH(created_at)
</code>```

How would I modify that query to work with PostgreSQL?

答:
http://www.postgresql.org/docs/9.0/static/functions-datetime.html

```<code>SELECT
  EXTRACT(MONTH FROM created_at) AS month,
  EXTRACT(YEAR FROM created_at) AS year
FROM users
GROUP BY EXTRACT(MONTH FROM created_at), EXTRACT(YEAR FROM created_at)
ORDER BY EXTRACT(YEAR FROM created_at), EXTRACT(MONTH FROM created_at)
</code>```

This syntax should work on PostgreSQL, Oracle and Teradata

ContentLicense: CC BY-SA 2.5

Body:
I have this MySQL query that makes use of MONTH() and YEAR():

SELECT
  MONTH(created_at) AS month,
  YEAR(created_at) AS year
FROM users
GROUP BY MONTH(created_at), YEAR(created_at)
ORDER BY YEAR(created_at), MONTH(created_at)

How would I modify that query to work with PostgreSQL?

Body:
http://www.postgresql.org/docs/9.0/static/functions-datetime.html

SELECT
  EXTRACT(MONTH FROM created_at) AS month,
  EXTRACT(YEAR FROM created_at) AS year
FROM users
GROUP BY EXTRACT(MONTH FROM created_at), EXTRACT(YEAR FROM created_at)
ORDER BY EXTRACT(YEAR FROM created_at), EXTRACT(MONTH FROM created_at)

This syntax should work on PostgreSQL, Oracle and Teradata


问:
Turning an array into a multidimensional array? Javascript
I am struggling to create a simple function that will taking an array such as

```<code>["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]
</code>```

and turn it into a multidimensional array that looks like this

```<code>[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]
</code>```

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!

答:
Another option is to take in a second argument that dictates how many items you would like in each subarray. For instance:</p>

```<code>function squash(arr, num) {
 let results = [];
 let start, end;

 for (let i = 1; i < arr.length; i++) {
  start = (i - 1) * num;
  end = i * num;

  let sliced = arr.slice(start, end);

  if (start >= arr.length) { // need to make sure we don't go passed the end
   break;
  }

  results.push(sliced);
 }
 return results;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am struggling to create a simple function that will taking an array such as

["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]

and turn it into a multidimensional array that looks like this

[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!

Body:
Another option is to take in a second argument that dictates how many items you would like in each subarray. For instance:

function squash(arr, num) {
 let results = [];
 let start, end;

 for (let i = 1; i < arr.length; i++) {
  start = (i - 1) * num;
  end = i * num;

  let sliced = arr.slice(start, end);

  if (start >= arr.length) { // need to make sure we don't go passed the end
   break;
  }

  results.push(sliced);
 }
 return results;
}


答:
Your data has irregular columns, and pandas is trying to figure out the correct number by reading the first few lines and making the wrong inference.

This works:

```<code>psz2_2017 = pd.read_csv('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat',header = None, delim_whitespace=True, error_bad_lines=False )
</code>```

The key argument here is error_bad_lines=False

Title: How to configure Pandas to read .dat file

Body:
Can't seem to load this file with pd.read_csv or pd.read_table:

http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat

I've tried:

psz2_2017 = pd.read_csv('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat', sep=';', header=None)

Also tried pd.read_table with/wo sep='\t' (same result) and sep='\s+' (gets Error tokenizing data).

Results in:

0
0   1 PSZ2 G000.04+45.13 0.0405432 45.135175...
1   2 PSZ2 G000.13+78.04 0.1380577 78.042113...
2   3 PSZ2 G000.40-41.86 0.4029953 -41.860792...

Any suggestions?

The first line looks like this:

1 PSZ2 G000.04+45.13   0.0405432  45.1351750 229.1905120  -1.0172220  4.107310  6.75319 2 111 0     1 0 0.938825   5.481591  1.899500  20 RXC J1516.5-0056           0.119800  3.962411 0.393290 0.370242 J1516.5-0056 RMJ151653.9-010506.3

Body:
Your data has irregular columns, and pandas is trying to figure out the correct number by reading the first few lines and making the wrong inference.

This works:

psz2_2017 = pd.read_csv('http://cdsarc.u-strasbg.fr/ftp/cats/J/A+A/594/A27/psz2.dat',header = None, delim_whitespace=True, error_bad_lines=False )

The key argument here is error_bad_lines=False


问:
PowerShell: Remove duplicated items from array
I am trying to locate discrepancies in BIND DNS records.  I would like to output a CSV file that only has those discrepancies.  I have a CSV file that has all records from all locations in BIND (ns.prvt, ns.pub, common, includes).  What I'm trying to figure out is how to output a CSV that only shows the discrepancies.  For 2 records to be considered a discrepancy, they must meet the following criteria:

Both records have the same RecordName and RecordType.

Both records have different Data or TTL.

Both records come from different locations.

I am almost there with the following script but it keeps showing me a couple of rows that don't necessarily meet the above criteria.

```<code>$Records = Import-Csv C:\Temp\Domain_ALL.csv | Select * | Sort Data,Location
$RecordsRev = @()
$Records | % {
    $Record = $_
    $Records | % {
        $DataFE = $_
        If (
        ([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).RecordName -eq $DataFE.RecordName) -and
        ([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).RecordType -eq $DataFE.RecordType) -and
        ([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).Location -ne $DataFE.Location) -and
        (([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).Data -ne $DataFE.Data) -or
        ([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).TTL -ne $DataFE.TTL))
        ) {
            $RecordsRev += $_
        }
    }
}
$RecordsRev | Export-Csv C:\Temp\Domain_Discrepancies.csv -NoType
</code>```

The results that I get are:

```<code>RecordName RecordType Data                           TTL Location
---------- ---------- ----                           --- --------
domain.com TXT        "MS=abc1234566"                600 Includes
domain.com TXT        "MS=abc1234566"                600 Common
domain.com TXT        "site-verification=abcd1234"   600 Includes
domain.com TXT        "site-verification=abcd1234"   600 Common
www        CNAME      somedomain.com.test.           600 Includes
www        CNAME      somedomain.com.                600 Common
</code>```

The results that I expect are:

```<code>RecordName RecordType Data                           TTL Location
---------- ---------- ----                           --- --------
www        CNAME      somedomain.com.test.           600 Includes
www        CNAME      somedomain.com.                600 Common
</code>```

How do I delete all duplicated rows in the array?  This is different from "Select * -unique" as I don't want to keep any row that contains the duplicated information.

EDIT:  I think the main problem is that, since the script checks each record against every record in the CSV, it technically is a discrepancy.  For example, in the below table, record 1 meets the criteria to be a discrepancy because it differs from record 4.  However, since record 1 is the same as record 2, it should actually be omitted from the results.

```<code>RecordNumber RecordName RecordType Data                           TTL Location
------------ ---------- ---------- ----                           --- --------
1            domain.com TXT        "MS=abc1234566"                600 Includes
2            domain.com TXT        "MS=abc1234566"                600 Common
3            domain.com TXT        "site-verification=abcd1234"   600 Includes
4            domain.com TXT        "site-verification=abcd1234"   600 Common
5            www        CNAME      somedomain.com.test.           600 Includes
6            www        CNAME      somedomain.com.                600 Common
</code>```

Any help would be greatly appreciated.

Kyle

答:
I was able to figure this out with the help of someone who deleted their post...  Here is the script that I am using now to find all records that meet ALL of the following criteria:

Both records have the same RecordName and RecordType.  -AND

Both records have different Data or TTL.  -AND

Both records come from different locations.

```<code>$Records = Import-Csv C:\Temp\Domain_ALL.csv | Select * | Sort Data,Location
$Discrepancies = @()
$GoodRecords = @()
$BadRecords = @()

$Records | ForEach-Object {

    # for each record $_, compare it against every other record..
    foreach ($R in $Records) {

        # if Both records have the same RecordName and RecordType..
        if (($_.RecordName -eq $R.RecordName) -and ($_.RecordType -eq $R.RecordType)) {

            # and if Both records come from different locations..
            if ($_.Location -ne $R.Location) {

                # if Both records have the same Data and TTL then they are considered good:
                if (($_.Data -eq $R.Data) -and ($_.TTL -eq $R.TTL)) {
                    $GoodRecords += $_
                }
                Else{
                    # if Both records have different Data or TTL then they are considered bad:
                    $BadRecords += $_
                }
            }
        }
    }

}

ForEach ($BadRecord in $BadRecords){
    If (($GoodRecords -notcontains $BadRecord)){
        $Discrepancies += $BadRecord
    }
}
$Discrepancies | Select * -Unique | Sort RecordName,Location,Data | ft
</code>```

Body:
I am trying to locate discrepancies in BIND DNS records.  I would like to output a CSV file that only has those discrepancies.  I have a CSV file that has all records from all locations in BIND (ns.prvt, ns.pub, common, includes).  What I'm trying to figure out is how to output a CSV that only shows the discrepancies.  For 2 records to be considered a discrepancy, they must meet the following criteria:

Both records have the same RecordName and RecordType.

Both records have different Data or TTL.

Both records come from different locations.

I am almost there with the following script but it keeps showing me a couple of rows that don't necessarily meet the above criteria.

$Records = Import-Csv C:\Temp\Domain_ALL.csv | Select * | Sort Data,Location
$RecordsRev = @()
$Records | % {
    $Record = $_
    $Records | % {
        $DataFE = $_
        If (
        ([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).RecordName -eq $DataFE.RecordName) -and
        ([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).RecordType -eq $DataFE.RecordType) -and
        ([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).Location -ne $DataFE.Location) -and
        (([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).Data -ne $DataFE.Data) -or
        ([string]($Record | ? {($_.RecordName -eq $DataFE.RecordName)}).TTL -ne $DataFE.TTL))
        ) {
            $RecordsRev += $_
        }
    }
}
$RecordsRev | Export-Csv C:\Temp\Domain_Discrepancies.csv -NoType

The results that I get are:

RecordName RecordType Data                           TTL Location
---------- ---------- ----                           --- --------
domain.com TXT        "MS=abc1234566"                600 Includes
domain.com TXT        "MS=abc1234566"                600 Common
domain.com TXT        "site-verification=abcd1234"   600 Includes
domain.com TXT        "site-verification=abcd1234"   600 Common
www        CNAME      somedomain.com.test.           600 Includes
www        CNAME      somedomain.com.                600 Common

The results that I expect are:

RecordName RecordType Data                           TTL Location
---------- ---------- ----                           --- --------
www        CNAME      somedomain.com.test.           600 Includes
www        CNAME      somedomain.com.                600 Common

How do I delete all duplicated rows in the array?  This is different from "Select * -unique" as I don't want to keep any row that contains the duplicated information.

EDIT:  I think the main problem is that, since the script checks each record against every record in the CSV, it technically is a discrepancy.  For example, in the below table, record 1 meets the criteria to be a discrepancy because it differs from record 4.  However, since record 1 is the same as record 2, it should actually be omitted from the results.

RecordNumber RecordName RecordType Data                           TTL Location
------------ ---------- ---------- ----                           --- --------
1            domain.com TXT        "MS=abc1234566"                600 Includes
2            domain.com TXT        "MS=abc1234566"                600 Common
3            domain.com TXT        "site-verification=abcd1234"   600 Includes
4            domain.com TXT        "site-verification=abcd1234"   600 Common
5            www        CNAME      somedomain.com.test.           600 Includes
6            www        CNAME      somedomain.com.                600 Common

Any help would be greatly appreciated.

Kyle

Body:
I was able to figure this out with the help of someone who deleted their post...  Here is the script that I am using now to find all records that meet ALL of the following criteria:

Both records have the same RecordName and RecordType.  -AND

Both records have different Data or TTL.  -AND

Both records come from different locations.

$Records = Import-Csv C:\Temp\Domain_ALL.csv | Select * | Sort Data,Location
$Discrepancies = @()
$GoodRecords = @()
$BadRecords = @()

$Records | ForEach-Object {

    # for each record $_, compare it against every other record..
    foreach ($R in $Records) {

        # if Both records have the same RecordName and RecordType..
        if (($_.RecordName -eq $R.RecordName) -and ($_.RecordType -eq $R.RecordType)) {

            # and if Both records come from different locations..
            if ($_.Location -ne $R.Location) {

                # if Both records have the same Data and TTL then they are considered good:
                if (($_.Data -eq $R.Data) -and ($_.TTL -eq $R.TTL)) {
                    $GoodRecords += $_
                }
                Else{
                    # if Both records have different Data or TTL then they are considered bad:
                    $BadRecords += $_
                }
            }
        }
    }

}

ForEach ($BadRecord in $BadRecords){
    If (($GoodRecords -notcontains $BadRecord)){
        $Discrepancies += $BadRecord
    }
}
$Discrepancies | Select * -Unique | Sort RecordName,Location,Data | ft


问:
how to incorporate an array in an CLI command in ruby
I am having an hard time, implementing an array in an AWS cli command in ruby.
I have a set of accounts, I want to get the policy version details of a specific policy from an specific account number. I want to loop through the account numbers and get the specific policy details for the account numbers.

HERE IS MY CURRENT CODE, it works when I hard code the account number

```<code>require 'aws-sdk'
require 'json'
require 'rest-client'

puts "Here is the current version of the CloudHealth Policy"

accnt  = [899163431116, 2382308203823, 8989089089080]
puts "here is the zero index"
puts accnt [0]
j = `aws iam get-policy-version --policy-arn arn:aws:iam::899163431116:policy/cloudhealth-access-policy --version-id v2 --profile jo`
my_hash = JSON.parse(j)
puts JSON.pretty_generate my_hash["PolicyVersion"]
</code>```

I WANT TO INCORPORATE THE ARRAY accnt, SO I CAN LOOP Through the accnt numbers with an hard coding in the cli command

```<code> require 'aws-sdk'
require 'json'
require 'rest-client'

puts "Here is the current version of the CloudHealth Policy"

accnt = [899163431116, 2382308203823, 8989089089080]
puts "here is the zero index"
puts accnt[0]
j = `aws iam get-policy-version --policy-arn arn:aws:iam::accnt[0]:policy/cloudhealth-access-policy --version-id v2 --profile jo`
my_hash = JSON.parse(j)
puts JSON.pretty_generate my_hash["PolicyVersion"]
</code>```

答:
If you want to interpolate you'll need to request interpolation:

```<code>j = `aws ... arn:aws:iam::#{accnt[0]}:policy...`
</code>```

Strings are only interpolated if you use the #{...} notation to indicate you want that part to be expanded. In your acase accnt[0] is just plain text that's part of the string.

You'll probably want to expand your code to be more like this:

```<code>accnt.each do |id|
  j = `aws ... arn:aws:iam::#{id}:policy...`
  # ...Other code relating to parsing/printing for this round
end
</code>```

Don't forget that the AWS Ruby library can do everything the command-line aws tool can do and more, so engaging the shell here is probably not necessary. The Aws::IAM::Policy class should be able to get what you need.

Body:
I am having an hard time, implementing an array in an AWS cli command in ruby.
I have a set of accounts, I want to get the policy version details of a specific policy from an specific account number. I want to loop through the account numbers and get the specific policy details for the account numbers.

HERE IS MY CURRENT CODE, it works when I hard code the account number

require 'aws-sdk'
require 'json'
require 'rest-client'

puts "Here is the current version of the CloudHealth Policy"

accnt  = [899163431116, 2382308203823, 8989089089080]
puts "here is the zero index"
puts accnt [0]
j = `aws iam get-policy-version --policy-arn arn:aws:iam::899163431116:policy/cloudhealth-access-policy --version-id v2 --profile jo`
my_hash = JSON.parse(j)
puts JSON.pretty_generate my_hash["PolicyVersion"]

I WANT TO INCORPORATE THE ARRAY accnt, SO I CAN LOOP Through the accnt numbers with an hard coding in the cli command

 require 'aws-sdk'
require 'json'
require 'rest-client'

puts "Here is the current version of the CloudHealth Policy"

accnt = [899163431116, 2382308203823, 8989089089080]
puts "here is the zero index"
puts accnt[0]
j = `aws iam get-policy-version --policy-arn arn:aws:iam::accnt[0]:policy/cloudhealth-access-policy --version-id v2 --profile jo`
my_hash = JSON.parse(j)
puts JSON.pretty_generate my_hash["PolicyVersion"]

Body:
If you want to interpolate you'll need to request interpolation:

j = `aws ... arn:aws:iam::#{accnt[0]}:policy...`

Strings are only interpolated if you use the #{...} notation to indicate you want that part to be expanded. In your acase accnt[0] is just plain text that's part of the string.

You'll probably want to expand your code to be more like this:

accnt.each do |id|
  j = `aws ... arn:aws:iam::#{id}:policy...`
  # ...Other code relating to parsing/printing for this round
end

Don't forget that the AWS Ruby library can do everything the command-line aws tool can do and more, so engaging the shell here is probably not necessary. The Aws::IAM::Policy class should be able to get what you need.


问:
Foundation 6.4 app.js Handpick components with import
Using the new Panini Zurb template with webpack.
It is not clear yet how to handpick modules/components following the one line of instructions they provide in app.js:

```<code>import $ from 'jquery';
// import whatInput from 'what-input';
window.$ = $;

// import Foundation from 'foundation-sites';
// If you want to pick and choose which modules to include, comment out
 the above and uncomment
// the line below
// import './lib/foundation-explicit-pieces';
import {Tabs} from './lib/foundation-explicit-pieces';

$(document).foundation();
// if($('#about-tabs').length) {var _tabs = new Foundation.Tabs($('#about-tabs'));}
</code>```

link to the section:
github repo

And at this point it's working, but it seems like everything in foundation is packaged resulting in a ~270KB file.

I'm definitely not aware of all the aspects of import/export, any suggestion on a comprehensive source will be very appreciated.

答:
Apparently it was intuitive enough, in the support file it's enough to comment out the single imports.

With all out but 1 component the filesize becomes still ~160KB after build.

Any way to tree shake more? It's basically the same as the previous version without webpack

Body:
Using the new Panini Zurb template with webpack.
It is not clear yet how to handpick modules/components following the one line of instructions they provide in app.js:

import $ from 'jquery';
// import whatInput from 'what-input';
window.$ = $;

// import Foundation from 'foundation-sites';
// If you want to pick and choose which modules to include, comment out
 the above and uncomment
// the line below
// import './lib/foundation-explicit-pieces';
import {Tabs} from './lib/foundation-explicit-pieces';

$(document).foundation();
// if($('#about-tabs').length) {var _tabs = new Foundation.Tabs($('#about-tabs'));}

link to the section:
github repo

And at this point it's working, but it seems like everything in foundation is packaged resulting in a ~270KB file.

I'm definitely not aware of all the aspects of import/export, any suggestion on a comprehensive source will be very appreciated.


问:
VHDL-2008 continuously force an external name
I'd like to be able to continuously force a signal down in my testbench hierarchy. Here is a simple example illustrating how I've been doing this in my test benches.

```<code>library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity double_inverter is
port(
  a : in std_logic;
  z : out std_logic
);
end double_inverter;

architecture x of double_inverter is
 signal b : std_logic;
begin

  b <= not a;
  z <= not b;

end architecture x;

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity inverter_tb is
end inverter_tb;

architecture y of inverter_tb is
  signal z : std_logic;
  signal clk : std_logic := '0';
begin

  clk <= not clk after 5 ns;

  dut : entity work.double_inverter
  port map(
    a => '0',
    z => z
  );

  continuous_stim : process(clk)
  begin

    << signal dut.b : std_logic >> <= force clk;

  end process;

end architecture y;
</code>```

This works in Modelsim 10.4b i.e. signal b in the double_inverter instance will be set by clk and not signal a, but is there a better way to control external name signals?

Thanks for your help.

答:
In some situations you can use is an alias to the external name:

```<code>alias dut_b is <<signal dut.b : std_logic >> ;
</code>```

Since we think of signals being declared in an architecture, our instinct is to put the alias in the architecture.   However, in this situation, it is not allowed because the DUT has not been elaborated yet.

You may be allowed to put it in the process - I would have to do some research to check if the language allows this.  My concern is that processes do not allow signal declarations, so I am not confident that it will allow aliases to signals in a process - no harm in trying it and letting us know if it worked.

Generally when I am using something like this, I put it in a architecture declarative region of a component that creates the test cases and is instanced by the testbench.   To avoid issues with elaboration order, I make sure to instance my DUT first in the testbench and typically the component that generates the test cases last (with the transaction based models in the middle) - VHDL elaborates designs in the order they are instantiated.

Body:
I'd like to be able to continuously force a signal down in my testbench hierarchy. Here is a simple example illustrating how I've been doing this in my test benches.

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity double_inverter is
port(
  a : in std_logic;
  z : out std_logic
);
end double_inverter;

architecture x of double_inverter is
 signal b : std_logic;
begin

  b <= not a;
  z <= not b;

end architecture x;

library ieee;
use ieee.std_logic_1164.all;
use ieee.numeric_std.all;

entity inverter_tb is
end inverter_tb;

architecture y of inverter_tb is
  signal z : std_logic;
  signal clk : std_logic := '0';
begin

  clk <= not clk after 5 ns;

  dut : entity work.double_inverter
  port map(
    a => '0',
    z => z
  );

  continuous_stim : process(clk)
  begin

    << signal dut.b : std_logic >> <= force clk;

  end process;

end architecture y;

This works in Modelsim 10.4b i.e. signal b in the double_inverter instance will be set by clk and not signal a, but is there a better way to control external name signals?

Thanks for your help.

Body:
In some situations you can use is an alias to the external name:

alias dut_b is <<signal dut.b : std_logic >> ;

Since we think of signals being declared in an architecture, our instinct is to put the alias in the architecture.   However, in this situation, it is not allowed because the DUT has not been elaborated yet.

You may be allowed to put it in the process - I would have to do some research to check if the language allows this.  My concern is that processes do not allow signal declarations, so I am not confident that it will allow aliases to signals in a process - no harm in trying it and letting us know if it worked.

Generally when I am using something like this, I put it in a architecture declarative region of a component that creates the test cases and is instanced by the testbench.   To avoid issues with elaboration order, I make sure to instance my DUT first in the testbench and typically the component that generates the test cases last (with the transaction based models in the middle) - VHDL elaborates designs in the order they are instantiated.


问:
Getting the full file path when using a file upload control
I wrote some code to upload files to amazon S3, if I put a full file path manually It successfully uploads the file from my computer. What I'm trying to do is use a file upload control and store the full path in a variable so that I can use it for my amazon method. Ive read everywhere it seems that the browser won't let you get the full file path for security reasons.

How can I get the full file path? Should I just store the files on my webserver and point my amazon method to the server path, and then use the file upload control to tell it what the filename is? I wish I could just do a straight shot to amazon...

答: I came across this link which has a great tutorial and even gives you a working sample project. (this is different from the code that the .net SDK includes...) http://aws.amazon.com/articles/774?_encoding=UTF8&jiveRedirect=1</p>


问:
Change the color of the noUiSlider
I can't really grasp what class should I use to change the color of the slider in noUiSlider? I want the slider to have blue color to the left of the slider on the bar, and white to the right; how its demonstrated in this example. How can I do this?

Here is the part of creation of the slider:

```<code>$('#slider-range').noUiSlider({
        start: [ start ],
        step: 1,
        range: {
            'min': [ 1 ],
            'max': [ 10 ]
        }
    });
</code>```

and in html:

```<code><div id="slider-range" type="range"/></div>
</code>```

I tried all possible classes described here, but the most I got was to have all bar blue or white, but not blue to the left and white ti the right. So, my question is how can I get this styling?

答:
I'm using Materialize Css version 1.0.0 and it includes noUiSlider as part of the library.

I was trying to style up this control with my own colors and here it is what I got after changing some classes:

All you have to do is to override this classes:

.noUi-connect {
    background: purple;
}
.noUi-horizontal .noUi-handle, .noUi-vertical .noUi-handle {
    background: purple;
}
.noUi-target.noUi-horizontal .noUi-tooltip {
    background-color: purple;
}
```

Here it is my pen for reference.
I hope it helps some how.

Title: Change the color of the noUiSlider

Body:
I can't really grasp what class should I use to change the color of the slider in noUiSlider? I want the slider to have blue color to the left of the slider on the bar, and white to the right; how its demonstrated in this example. How can I do this?

Here is the part of creation of the slider:

$('#slider-range').noUiSlider({
        start: [ start ],
        step: 1,
        range: {
            'min': [ 1 ],
            'max': [ 10 ]
        }
    });

and in html:

I tried all possible classes described here, but the most I got was to have all bar blue or white, but not blue to the left and white ti the right. So, my question is how can I get this styling?

Body:
I'm using Materialize Css version 1.0.0 and it includes noUiSlider as part of the library.

I was trying to style up this control with my own colors and here it is what I got after changing some classes:

All you have to do is to override this classes:

.noUi-connect {
    background: purple;
}
.noUi-horizontal .noUi-handle, .noUi-vertical .noUi-handle {
    background: purple;
}
.noUi-target.noUi-horizontal .noUi-tooltip {
    background-color: purple;
}

Here it is my pen for reference.
I hope it helps some how.

ContentLicense: CC BY-SA 4.0


问:
TensorFlow extracting columns
I have a tensor of shape (10, 100, 20, 3). Basically, it can be thought of as a batch of images. So the image height is 100 and width is 20 and channel depth is 3.

I have run some computations to generate a set of 10*50 indices corresponding to 50 columns I would like to keep per image in the batch. The indices are stored in a tensor of shape (10, 50). I would like to end up with a tensor of shape (10, 50, 20, 3).

I have looked into tf.batch_nd() but I can't figure out the semantics for how indices are actually used.

Any thoughts?

答:
I can't comment on the question because of low rep, so using an answer instead.

Can you clarify your question a bit, maybe with a small concrete example using very small tensors?

What are the "columns" you are referring to? You say that you want to keep 50 columns (presumably 50 numbers) per image. If so, the (10, 50) shape seems like what you want - it has 50 numbers for each image in the batch. The (10, 50, 20, 3) shape you mention would allocate 50 numbers to each "image_column x channel". That is 20*3*50 = 3000 numbers per image. How do you want to construct them from the 50 that you have?

Also, can you give a link to tf.batch_nd(). I did not find anything similar and relevant.

Title: TensorFlow extracting columns


问:
Creating beans when Autowiring with Spring
I am trying to write a test for my controller. When the web service is running everything works fine. However, when I run the test I get:

Error creating bean with name 'Controller': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.prov.Service' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

As you can see below, I believe have everything correctly Autowired and my project structure is correctly set up so that the component scanner can find the annotations properly, yet I still get this error.

Controller:

```<code>@RestController
@RequestMapping("/api")
public class Controller {

    @Autowired
    private Service service;

    @JsonView(Views.All.class)
    @RequestMapping(value = "/prov/users", method = RequestMethod.POST)
    @ResponseBody
    public CommonWebResponse<String> handleRequest(@RequestBody UserData userData) {
        return service.prov(userData);
    }
}
</code>```

Service:

```<code>@Service
public class Service {

    @Autowired
    private Repo repo;

    @Autowired
    private OtherService otherService;

    public CommonWebResponse<String> prov(UserData userData) {
        // do stuff here
        return new SuccessWebResponse<>("Status");
    }
}
</code>```

Controller Test:

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(
        controllers = Controller.class,
        excludeFilters = {
                @ComponentScan.Filter(
                        type = FilterType.ASSIGNABLE_TYPE,
                        value = {CorsFilter.class, AuthenticationFilter.class}
                )
        }
)
@AutoConfigureMockMvc(secure = false)
public class ControllerTest {

    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    @Autowired
    private MockMvc mvc;

    @Test
    public void connectToEndpoint_shouldReturnTrue() {
        UserData userData = new UserData("a", "bunch", "of", "fields");
        try {
            mvc.perform(post("/api/prov/users").contentType(APPLICATION_JSON_UTF8)
                    .content(asJsonString(userData))
                    .accept(MediaType.ALL))
                    .andExpect(status().isOk());
        } catch (Exception e) {
            Assert.fail();
        }
    }

}
</code>```

答:
The Controller class autowires your Service class. Therefore, testing the Controller class requires existence of your Service class because Controller depends on creating a bean of type Service. This means you either have to @Autowired your service class into your test, or (preferably) mock it using something like Mockito.

(edit with code example):

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
public class ControllerTest {
    @MockBean
    private Service service

    @Autowired
    private MockMvc mvc;

    @Test
    public void foo() {
        String somePayload = "Hello, World";
        String myParams = "foo";
        when(service.method(myParams)).thenReturn(somePayload);
        mvc.perform(get("my/url/to/test").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", is(equalTo("Hello, World"))));
    }
}
</code>```

Do note that this example uses Hamcrest for things like is() and equalTo()

Body:
I am trying to write a test for my controller. When the web service is running everything works fine. However, when I run the test I get:

Error creating bean with name 'Controller': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.prov.Service' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

As you can see below, I believe have everything correctly Autowired and my project structure is correctly set up so that the component scanner can find the annotations properly, yet I still get this error.

Controller:

@RestController
@RequestMapping("/api")
public class Controller {

    @Autowired
    private Service service;

    @JsonView(Views.All.class)
    @RequestMapping(value = "/prov/users", method = RequestMethod.POST)
    @ResponseBody
    public CommonWebResponse<String> handleRequest(@RequestBody UserData userData) {
        return service.prov(userData);
    }
}

Service:

@Service
public class Service {

    @Autowired
    private Repo repo;

    @Autowired
    private OtherService otherService;

    public CommonWebResponse<String> prov(UserData userData) {
        // do stuff here
        return new SuccessWebResponse<>("Status");
    }
}

Controller Test:

@RunWith(SpringRunner.class)
@WebMvcTest(
        controllers = Controller.class,
        excludeFilters = {
                @ComponentScan.Filter(
                        type = FilterType.ASSIGNABLE_TYPE,
                        value = {CorsFilter.class, AuthenticationFilter.class}
                )
        }
)
@AutoConfigureMockMvc(secure = false)
public class ControllerTest {

    public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(MediaType.APPLICATION_JSON.getType(), MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));

    @Autowired
    private MockMvc mvc;

    @Test
    public void connectToEndpoint_shouldReturnTrue() {
        UserData userData = new UserData("a", "bunch", "of", "fields");
        try {
            mvc.perform(post("/api/prov/users").contentType(APPLICATION_JSON_UTF8)
                    .content(asJsonString(userData))
                    .accept(MediaType.ALL))
                    .andExpect(status().isOk());
        } catch (Exception e) {
            Assert.fail();
        }
    }

}

Body:
The Controller class autowires your Service class. Therefore, testing the Controller class requires existence of your Service class because Controller depends on creating a bean of type Service. This means you either have to @Autowired your service class into your test, or (preferably) mock it using something like Mockito.

(edit with code example):

@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
public class ControllerTest {
    @MockBean
    private Service service

    @Autowired
    private MockMvc mvc;

    @Test
    public void foo() {
        String somePayload = "Hello, World";
        String myParams = "foo";
        when(service.method(myParams)).thenReturn(somePayload);
        mvc.perform(get("my/url/to/test").accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", is(equalTo("Hello, World"))));
    }
}

Do note that this example uses Hamcrest for things like is() and equalTo()


问:
I want to convert a double array to one element of a cell array in matlab
I want to convert a double array to one element of a cell array in matlab. How can I do this?
for example a double array like
 [5 3 4 2 1]
must be converted to
{[5 3 4 2 1]}</p>

答:
You question is not very clear. I guess this is what you want:</p>

```<code>a = 5:-1:1; % your double array
myCell = {a}; % put an array into a cell

myCell{1}

ans =

     5     4     3     2     1
</code>```

Body:
You question is not very clear. I guess this is what you want:

a = 5:-1:1; % your double array
myCell = {a}; % put an array into a cell

myCell{1}

ans =

     5     4     3     2     1


问:
What's the proper way to subclass a delegate?
I'm trying to learn the delegation process for Swift in Xcode 8.

I can get it working just fine, but have a question about the subclass in my delegate.  Normally, in Objective-C, the subclass for this would be NSObject.  I'm able to get it working with NSObject and AnyObject.  I read a article about not crossing Objective-C because of performance.  Does this really matter?  If it's not a view or any other type of controller, what's the subclass in Swift for an object?

Is AnyObject the same as NSObject?

ViewController

```<code>import UIKit

class ViewController: UIViewController, TestDelegate {
    // init the delegate
    let theDelegate = TheDelegate ()

    @IBOutlet weak var label1: UILabel!

    @IBAction func button1(_ sender: Any) {
        // tell the delegate what to do
        theDelegate.run(add: 1)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        theDelegate.delegate = self
    }

    // the protocol
    func didTest(int: Int) {
        label1.text = "\(int)"
        print ("Got back from delegate \(int)")
    }
}
</code>```

Object TestProtocol.swift

```<code>import Foundation

protocol TestDelegate: class {
    func didTest(int: Int)
}

class TheDelegate: AnyObject{
    weak var delegate: TestDelegate?
    func run(add: Int){
        let test = add + 1
        delegate?.didTest(int: test)
    }
}
</code>```

答:
There is no reason to subclass AnyObject, since everything is an AnyObject just by existing (like object in Java).

NSObject is the old base class in Obj-C, so if you are wanting to have your protocol or class be seen in Obj-C code it must either be marked @objc or it must subclass NSObject.

So unless you are also using Obj-C in your program, then you don't need to subclass NSObject.

Look at
Swift 3: subclassing NSObject or not?
https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html

Body:
I'm trying to learn the delegation process for Swift in Xcode 8.

I can get it working just fine, but have a question about the subclass in my delegate.  Normally, in Objective-C, the subclass for this would be NSObject.  I'm able to get it working with NSObject and AnyObject.  I read a article about not crossing Objective-C because of performance.  Does this really matter?  If it's not a view or any other type of controller, what's the subclass in Swift for an object?

Is AnyObject the same as NSObject?

ViewController

import UIKit

class ViewController: UIViewController, TestDelegate {
    // init the delegate
    let theDelegate = TheDelegate ()

    @IBOutlet weak var label1: UILabel!

    @IBAction func button1(_ sender: Any) {
        // tell the delegate what to do
        theDelegate.run(add: 1)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        theDelegate.delegate = self
    }

    // the protocol
    func didTest(int: Int) {
        label1.text = "\(int)"
        print ("Got back from delegate \(int)")
    }
}

Object TestProtocol.swift

import Foundation

protocol TestDelegate: class {
    func didTest(int: Int)
}

class TheDelegate: AnyObject{
    weak var delegate: TestDelegate?
    func run(add: Int){
        let test = add + 1
        delegate?.didTest(int: test)
    }
}


问:
What is the Ruby equivalent of Awk's FNR==NR?
Awk has the built in variables FNR and NR for the number of records (lines usually) read from the current file and in total.

In awk, it is common to have:

```<code>$ awk 'FNR==NR {first file lines; next } {process remaining lines } f1 f2
</code>```

Commonly, f1 contains values that determine how to process the remaining files. (key words, line numbers, etc.)

Ruby has the makings of a fabulous text processing language. Ruby has $. as the equivalent of awk's NR What is equivalent of FNR?

答:
Given:

```<code>$ head f?.txt
==> f1.txt <==
line 1
line 2

==> f2.txt <==
line 3
line 4
</code>```

Ruby has the ARGF stream (aliased as $< if you want to feel Perly) that either reads STDIN or opens a file from the command line. Same behavior as awk:

```<code>$ awk '{
    printf("FILENAME: %s, FNR: %s, NR: %s, %s\n", FILENAME, FNR,NR,$0)}
' f?.txt
FILENAME: f1.txt, FNR: 1, NR: 1, line 1
FILENAME: f1.txt, FNR: 2, NR: 2, line 2
FILENAME: f2.txt, FNR: 1, NR: 3, line 3
FILENAME: f2.txt, FNR: 2, NR: 4, line 4

$ ruby -lne '
    printf("FILENAME: %s, FNR: %s, NR: %s, %s\n", $<.file.path, $<.file.lineno, $., $_)
' f?.txt
FILENAME: f1.txt, FNR: 1, NR: 1, line 1
FILENAME: f1.txt, FNR: 2, NR: 2, line 2
FILENAME: f2.txt, FNR: 1, NR: 3, line 3
FILENAME: f2.txt, FNR: 2, NR: 4, line 4
</code>```

If you want to read both STDIN and a file, you would use a - for a file placeholder:

```<code>$ echo '123' | awk '1' - <(echo 456)
123
456
$ echo '123' | awk '1' <(echo 456) -
456
123

$ echo '123' | ruby -lne 'puts $_' - <(echo 456)
123
456
$ echo '123' | ruby -lne 'puts $_' <(echo 456) -
456
123
</code>```

Some more corresponding variables:

╔══════════╦═══════════════════╦═════════════════════════════════════════╗
║   awk    ║       ruby        ║                 comment                 ║
╠══════════╬═══════════════════╬═════════════════════════════════════════╣
║ $0       ║ $_                ║ unsplit record (line usually)           ║
║ NF       ║ $F.length         ║ Number of fields from autosplit         ║
║ FNR      ║ ARGF.file.lineno  ║ Number records read from current source ║
║ NR       ║ ARGF.lineno or $. ║ Total number of records so far          ║
║ (magic)  ║ ARGF or $<        ║ stream from either STDIN or a file      ║
║ $1..$NF  ║ $F[0]..$F[-1]     ║ First to last field from autosplit      ║
║ FS       ║ $;                ║ Input field separator                   ║
║ RS       ║ $/                ║ Input record separator                  ║
║ FILENAME ║ $<.file.path      ║ Filename of file being processed        ║
╚══════════╩═══════════════════╩═════════════════════════════════════════╝
```
<p>So if you has a list of line numbers in <code>f1</code> and a text file that you wanted to index with those line numbers (something you would use <code>awk</code> or <code>sed</code> to do) it is possible to use Ruby.</p>
<p>Given:</p>
```$ echo "1
2
44
2017" >f1
$ seq 10000 | awk '{print "Line", $1}' >f2
```
<p>In <code>awk</code> you would do:</p>
```$ awk 'FNR==NR{ln[$1]; next}
       FNR in ln'    f1 f2
```
<p>In Ruby you could do:</p>
```$ ruby -lane 'BEGIN{h=Hash.new}
              if $<.file.lineno == $<.lineno
                 h[$F[0].to_i]=true
                 next
              end
              puts $_ if h[$<.file.lineno]' f1 f2
```
<p>Both print:</p>
```Line 1
Line 2
Line 44
Line 2017
```

The awk version of this example is roughly 5x faster (go awk) but the Ruby version would easily support inputs that awk couldn't, such as JSON, XML, complex csv, etc

Body:
Awk has the built in variables FNR and NR for the number of records (lines usually) read from the current file and in total.

In awk, it is common to have:

$ awk 'FNR==NR {first file lines; next } {process remaining lines } f1 f2

Commonly, f1 contains values that determine how to process the remaining files. (key words, line numbers, etc.)

Ruby has the makings of a fabulous text processing language. Ruby has $. as the equivalent of awk's NR What is equivalent of FNR?

Body:
Given:

$ head f?.txt
==> f1.txt <==
line 1
line 2

==> f2.txt <==
line 3
line 4

Ruby has the ARGF stream (aliased as $< if you want to feel Perly) that either reads STDIN or opens a file from the command line. Same behavior as awk:

$ awk '{
    printf("FILENAME: %s, FNR: %s, NR: %s, %s\n", FILENAME, FNR,NR,$0)}
' f?.txt
FILENAME: f1.txt, FNR: 1, NR: 1, line 1
FILENAME: f1.txt, FNR: 2, NR: 2, line 2
FILENAME: f2.txt, FNR: 1, NR: 3, line 3
FILENAME: f2.txt, FNR: 2, NR: 4, line 4

$ ruby -lne '
    printf("FILENAME: %s, FNR: %s, NR: %s, %s\n", $<.file.path, $<.file.lineno, $., $_)
' f?.txt
FILENAME: f1.txt, FNR: 1, NR: 1, line 1
FILENAME: f1.txt, FNR: 2, NR: 2, line 2
FILENAME: f2.txt, FNR: 1, NR: 3, line 3
FILENAME: f2.txt, FNR: 2, NR: 4, line 4

If you want to read both STDIN and a file, you would use a - for a file placeholder:

$ echo '123' | awk '1' - <(echo 456)
123
456
$ echo '123' | awk '1' <(echo 456) -
456
123

$ echo '123' | ruby -lne 'puts $_' - <(echo 456)
123
456
$ echo '123' | ruby -lne 'puts $_' <(echo 456) -
456
123

Some more corresponding variables:

╔══════════╦═══════════════════╦═════════════════════════════════════════╗
║   awk    ║       ruby        ║                 comment                 ║
╠══════════╬═══════════════════╬═════════════════════════════════════════╣
║ $0       ║ $_                ║ unsplit record (line usually)           ║
║ NF       ║ $F.length         ║ Number of fields from autosplit         ║
║ FNR      ║ ARGF.file.lineno  ║ Number records read from current source ║
║ NR       ║ ARGF.lineno or $. ║ Total number of records so far          ║
║ (magic)  ║ ARGF or $<        ║ stream from either STDIN or a file      ║
║ $1..$NF  ║ $F[0]..$F[-1]     ║ First to last field from autosplit      ║
║ FS       ║ $;                ║ Input field separator                   ║
║ RS       ║ $/                ║ Input record separator                  ║
║ FILENAME ║ $<.file.path      ║ Filename of file being processed        ║
╚══════════╩═══════════════════╩═════════════════════════════════════════╝

So if you has a list of line numbers in f1 and a text file that you wanted to index with those line numbers (something you would use awk or sed to do) it is possible to use Ruby.

Given:

$ echo "1
2
44
2017" >f1
$ seq 10000 | awk '{print "Line", $1}' >f2

In awk you would do:

$ awk 'FNR==NR{ln[$1]; next}
       FNR in ln'    f1 f2

In Ruby you could do:

$ ruby -lane 'BEGIN{h=Hash.new}
              if $<.file.lineno == $<.lineno
                 h[$F[0].to_i]=true
                 next
              end
              puts $_ if h[$<.file.lineno]' f1 f2

Both print:

Line 1
Line 2
Line 44
Line 2017

The awk version of this example is roughly 5x faster (go awk) but the Ruby version would easily support inputs that awk couldn't, such as JSON, XML, complex csv, etc


问:
jQuery UI - Adding a class to all selectmenus within div
I am trying to add a class to multiple Jquery UI selectmenu elements within a specific div. This seems to work fine on
 elements but not on the jQuery UI elements.

In my example I'm trying to set the background color of the top 3 select menus to#FF9999 but not the 4th. However, only the top select menu gets changed.

I use the same method for changing the color of the top 3 paragraphs to blue which does works.

I am using the widget() method to access the select menus that have been added through jQuery.

Here is my JSFiddle: https://jsfiddle.net/m8dnczLu/

HTML

```<code><div id="someID" class="someClass">
  <div class="someOtherClass">
    <p id="p1">Paragraph 1</p>
    <select>
      <option value="0">Hello 1</option>
    </select>
  </div>
  <div class="someOtherClass">
    <p id="p2">Paragraph 2</p>
    <select>
      <option value="0">Hello 2</option>
    </select>
  </div>
  <div class="someOtherClass">
    <p id="p3">Paragraph 3</p>
    <select>
      <option value="0">Hello 3</option>
    </select>
  </div>
</div>
<div id="someID2">
  <p id="p4">Paragraph 4</p>
  <select>
    <option value="0">Hello 4</option>
  </select>
</div>
</code>```

CSS

```<code>.bClass {
  color: blue;
}
.rClass {
  background: #FF9999;
}
</code>```

Javascript

```<code>$('select').selectmenu();
$('#someID select').selectmenu('widget').addClass('rClass');
$('#someID p').addClass('bClass');
</code>```

答:
The problem is that the widget method only returns the button from the first menu. You need to loop over all the menus to do this.

```<code>$("#someID select").each(function() {
    $(this).selectmenu("widget").addClass('rClass');
});
</code>```

Updated fiddle

Body:
I am trying to add a class to multiple Jquery UI selectmenu elements within a specific div. This seems to work fine on
 elements but not on the jQuery UI elements.

In my example I'm trying to set the background color of the top 3 select menus to#FF9999 but not the 4th. However, only the top select menu gets changed.

I use the same method for changing the color of the top 3 paragraphs to blue which does works.

I am using the widget() method to access the select menus that have been added through jQuery.

Here is my JSFiddle: https://jsfiddle.net/m8dnczLu/

HTML

Paragraph 1

    <select>
      <option value="0">Hello 1</option>
    </select>

Paragraph 2

    <select>
      <option value="0">Hello 2</option>
    </select>

Paragraph 3

    <select>
      <option value="0">Hello 3</option>
    </select>

Paragraph 4

  <select>
    <option value="0">Hello 4</option>
  </select>

CSS

.bClass {
  color: blue;
}
.rClass {
  background: #FF9999;
}

Javascript

$('select').selectmenu();
$('#someID select').selectmenu('widget').addClass('rClass');
$('#someID p').addClass('bClass');

Body:
The problem is that the widget method only returns the button from the first menu. You need to loop over all the menus to do this.

$("#someID select").each(function() {
    $(this).selectmenu("widget").addClass('rClass');
});

Updated fiddle


问:
Parallelize a network bound for-loop in Java
I have a list of 1 million filenames that I have to download from S3. Currently I am downloading each file one-by-one (for-loop below) and it takes around 4 days for the download to complete.

```<code>    for (String fileName : Files) {
        InputStream is = null;
        try {
            is = m_S3.downloadFile(fileName); // m_s3 is a wrapper around AmazonS3 client
            m_localDisk.createFile(fileName, is); // m_localDisk is an interface for local disk storage.
        }
        catch (Exception e) {
            System.out.println("Exception happened");
        }
        finally {
            is.close();
        }
    }
</code>```

As S3 allows parallel connections, I am planning to paralleize the downloads. How can I do that in Java? I have done similar thing in C using Pthread where I just divided the input and delegated threads with different parts of inputs in their context. I can do that in Java, but I am sure there are better, more high level, ways of doing this.

I have considered things like using parallelStreams, but as that just uses a pipeline mechanism, I do not think it would give me much improvement -- only one network connection to S3 will be open at a time.

答:
Using parallelStream is probably the simplest way to approach this.

The default AmazonS3Client handles up to 50 concurrent connections, but you can configure it differently.

By default, parallelStream() uses a shared system thread pool, with numOfProcessors -1 threads, the below approach creates your own thread pool which you can adjust the size of to your own desires, plus the long running blocking tasks wont interfere with other things running on the system pool.

```<code>List<String> fileNames = ...
ForkJoinPool forkJoinPool = new ForkJoinPool(4);
forkJoinPool.submit(()-> {
    fileNames.parallelStream().forEach(fileName -> {
        try(InputStream is = m_S3.downloadFile(fileName)) {
            m_localDisk.createFile(fileName, is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}).get();
</code>```

Body:
I have a list of 1 million filenames that I have to download from S3. Currently I am downloading each file one-by-one (for-loop below) and it takes around 4 days for the download to complete.

    for (String fileName : Files) {
        InputStream is = null;
        try {
            is = m_S3.downloadFile(fileName); // m_s3 is a wrapper around AmazonS3 client
            m_localDisk.createFile(fileName, is); // m_localDisk is an interface for local disk storage.
        }
        catch (Exception e) {
            System.out.println("Exception happened");
        }
        finally {
            is.close();
        }
    }

As S3 allows parallel connections, I am planning to paralleize the downloads. How can I do that in Java? I have done similar thing in C using Pthread where I just divided the input and delegated threads with different parts of inputs in their context. I can do that in Java, but I am sure there are better, more high level, ways of doing this.

I have considered things like using parallelStreams, but as that just uses a pipeline mechanism, I do not think it would give me much improvement -- only one network connection to S3 will be open at a time.

Body:
Using parallelStream is probably the simplest way to approach this.

The default AmazonS3Client handles up to 50 concurrent connections, but you can configure it differently.

By default, parallelStream() uses a shared system thread pool, with numOfProcessors -1 threads, the below approach creates your own thread pool which you can adjust the size of to your own desires, plus the long running blocking tasks wont interfere with other things running on the system pool.

List<String> fileNames = ...
ForkJoinPool forkJoinPool = new ForkJoinPool(4);
forkJoinPool.submit(()-> {
    fileNames.parallelStream().forEach(fileName -> {
        try(InputStream is = m_S3.downloadFile(fileName)) {
            m_localDisk.createFile(fileName, is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}).get();


问:
How can I call ActivateKeyboardLayout from 64bit Windows Vista using VBA
Running VBA under XP I was able to call ActivateKeyboardLayout to switch my input language from English to another language. However, this no longer works under Vista64.

Any suggestions or workarounds?

The code that used to work under XP was similar to the following:

```<code>Private Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal HKL As Long, ByVal flags As Integer) As Integer
Const aklPUNJABI As Long = &H4460446
ActivateKeyboardLayout aklPUNJABI, 0
</code>```

There was a suggestion to try

```<code>Public Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal nkl As IntPtr, ByVal Flags As uint) As Integer
</code>```

When I try this I get the error message:

Variable uses an Automation type not supported in Visual Basic

答: This is just a blind guess, but have you tried running your app as elevated administrator to see if it makes a difference? What's the error code / value of GetLastError?</p>

OwnerDisplayName: Noah

Body:
Running VBA under XP I was able to call ActivateKeyboardLayout to switch my input language from English to another language. However, this no longer works under Vista64.

Any suggestions or workarounds?

The code that used to work under XP was similar to the following:

Private Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal HKL As Long, ByVal flags As Integer) As Integer
Const aklPUNJABI As Long = &H4460446
ActivateKeyboardLayout aklPUNJABI, 0

There was a suggestion to try

Public Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal nkl As IntPtr, ByVal Flags As uint) As Integer

When I try this I get the error message:

Variable uses an Automation type not supported in Visual Basic

LastEditorDisplayName: Noah

OwnerDisplayName: Paul Betts


答:
```
SELECT
  extract(MONTH from created_at) AS month,
  extract(YEAR from created_at) AS year
FROM users
GROUP BY extract(MONTH from created_at), extract(YEAR from created_at)
ORDER BY extract(MONTH from created_at), extract(YEAR from created_at)
```

Here is the up-to-date manual

http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT

Btw: This is standard (ANSI) SQL that works on MySQL as well.

Title: MySQL to PostgreSQL: How to modify this SQL query?

Body:
I have this MySQL query that makes use of MONTH() and YEAR():

SELECT
  MONTH(created_at) AS month,
  YEAR(created_at) AS year
FROM users
GROUP BY MONTH(created_at), YEAR(created_at)
ORDER BY YEAR(created_at), MONTH(created_at)

How would I modify that query to work with PostgreSQL?

Body:
SELECT
  extract(MONTH from created_at) AS month,
  extract(YEAR from created_at) AS year
FROM users
GROUP BY extract(MONTH from created_at), extract(YEAR from created_at)
ORDER BY extract(MONTH from created_at), extract(YEAR from created_at)

Here is the up-to-date manual

http://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT

Btw: This is standard (ANSI) SQL that works on MySQL as well.


问:
rspec: test if a method is called from a method
I want to test if the method foo1 is called from foo. Here is my code

```<code>class C

    def foo1
        puts "called"
    end

    def foo
        puts foo1
    end

end

describe C
    it "called"
            expect(C.new.foo).to receive(:foo1)
    end
end
</code>```

But i am getting below error on line expect(foo_).to receive(:foo1):

```<code>syntax error, unexpected keyword_end, expecting end-of-input
</code>```

答:
Here is a fixed version of your code:

```<code>class C
  def foo1
    puts "called"
  end

  def foo
    puts foo1
  end
end

describe C do
  it "called" do
    c = C.new
    expect(c).to receive(:foo1)
    c.foo
  end
end
</code>```

The describe and it blocks need complete do ... end syntax in order to be valid language.

Fixed your expectation. Reading the code is fairly self-explanatory, but basically you need to define your expectation against the correct object.

(Style-guide compliance) Use two spaces per indentation level (aka soft tabs). No hard tabs.

Body:
I want to test if the method foo1 is called from foo. Here is my code

class C

    def foo1
        puts "called"
    end

    def foo
        puts foo1
    end

end

describe C
    it "called"
            expect(C.new.foo).to receive(:foo1)
    end
end

But i am getting below error on line expect(foo_).to receive(:foo1):

syntax error, unexpected keyword_end, expecting end-of-input

Body:
Here is a fixed version of your code:

class C
  def foo1
    puts "called"
  end

  def foo
    puts foo1
  end
end

describe C do
  it "called" do
    c = C.new
    expect(c).to receive(:foo1)
    c.foo
  end
end

The describe and it blocks need complete do ... end syntax in order to be valid language.

Fixed your expectation. Reading the code is fairly self-explanatory, but basically you need to define your expectation against the correct object.

(Style-guide compliance) Use two spaces per indentation level (aka soft tabs). No hard tabs.


问:
Not reading records in correctly from TFRecord file?

I'm new to Tensorflow and have used the build_image_data.py file and tutorial found here.

I've built a small convolutional neural network to classify my own data set with 2 classes. When I ran my code I was getting errors related to a reshape op, basically my images are 72x72 RGB pixels. So the shape I defined was [72, 72, 3]. I was then getting InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 14040 values, but the requested shape has 15552. Now it should be 15552 values I thought as 72*72*3 = 15552. If there was only 14040 then perhaps there's something wrong with my image?

I took the images myself or got them from Google, and used a java program to resize them all to 72x72 pixels.

I've tried to eval() the image as they come into the model but there is no output and the whole thing just hangs for like a minute until I shut it off.

sess = tf.InteractiveSession()

filename = "../../dataset/traffic_sign/train-00000-of-00001"

# convert filename to a queue for an input pipeline.
filenameQ = tf.train.string_input_producer([filename], num_epochs=None)

# OUTPUT = AttributeError: 'FIFOQueue' object has no attribute 'eval'
print(filenameQ.eval())

# object to read records
recordReader = tf.TFRecordReader()

# read the full set of features for a single example
key, fullExample = recordReader.read(filenameQ)

# NO OUTPUT: program hangs
print(fullExample.eval())

# parse the full example into its' component features.
features = tf.parse_single_example(
fullExample,
features={
    'image/height': tf.FixedLenFeature([], tf.int64),
    'image/width': tf.FixedLenFeature([], tf.int64),
    'image/colorspace': tf.FixedLenFeature([], dtype=tf.string, default_value=''),
    'image/channels': tf.FixedLenFeature([], tf.int64),
    'image/class/label': tf.FixedLenFeature([], tf.int64),
    'image/class/text': tf.FixedLenFeature([], dtype=tf.string, default_value=''),
    'image/format': tf.FixedLenFeature([], dtype=tf.string, default_value=''),
    'image/filename': tf.FixedLenFeature([], dtype=tf.string, default_value=''),
    'image/encoded': tf.FixedLenFeature([], dtype=tf.string, default_value='')
})

# now we are going to manipulate the label and image features

label = features['image/class/label']
image_buffer = features['image/encoded']

# Decode the jpeg
with tf.name_scope('decode_jpeg', [image_buffer], None):
# decode turns tensor of type string. 0-D the JPEG encoded image
# to tensor of type uint8. 3-D with shape [height, width, channels]
    image = tf.image.decode_jpeg(image_buffer, channels=3)

image = tf.reshape(image, [HEIGHT, WIDTH, NUM_CHANNELS])
image = tf.to_float(image, "ToFloat")

# re-define label as a "one-hot" vector
# it will be [0,1] or [1,0] here.
# This approach can easily be extended to more classes
label = tf.one_hot(label - 1, NUM_CLASSES, dtype=tf.int64)

init = tf.global_variables_initializer()
sess.run(init)
# NO OUTPUT: program hangs
print(label.eval())
```

<p>When I created the TFRecord file I followed the example here with a label file <code>mylabels.txt</code> containing <code>go</code> and <code>stop</code> and my directory structure is as follows:</p>

<pre class="lang-py prettyprint-override"><code>traffic_sign/train/go/go*.jpeg
traffic_sign/train/stop/stop*.jpeg
traffic_sign/validation/go/go*.jpeg
traffic_sign/validation/stop/stop*.jpeg
</code>```

I used the command:

python build_image_data.py --train_directory=./train --output_directory=./  \
--validation_directory=./validation --labels_file=mylabels.txt   \
--train_shards=1 --validation_shards=1 --num_threads=1
```

The records file was created and just contains lots of bytes.

I have no clue how to solve this, I don't know whether I've made a mistake creating the dataset. But the image should be 72x72x3 so I don't know why there's a tensor in my model with 14040 values. And the fact I can't seem to evaluate a tensor and the program just hangs isn't allowing me to debug.

Help MUCH appreciated

答: It turns out there was a rogue image in my data set which was 72x65... hence the 14040 result. I replaced with a 72x72 image and its working now

Body:
I'm new to Tensorflow and have used the build_image_data.py file and tutorial found here.

I've built a small convolutional neural network to classify my own data set with 2 classes. When I ran my code I was getting errors related to a reshape op, basically my images are 72x72 RGB pixels. So the shape I defined was [72, 72, 3]. I was then getting InvalidArgumentError (see above for traceback): Input to reshape is a tensor with 14040 values, but the requested shape has 15552. Now it should be 15552 values I thought as 72*72*3 = 15552. If there was only 14040 then perhaps there's something wrong with my image?

I took the images myself or got them from Google, and used a java program to resize them all to 72x72 pixels.

I've tried to eval() the image as they come into the model but there is no output and the whole thing just hangs for like a minute until I shut it off.

sess = tf.InteractiveSession()

filename = "../../dataset/traffic_sign/train-00000-of-00001"

# convert filename to a queue for an input pipeline.
filenameQ = tf.train.string_input_producer([filename], num_epochs=None)

# OUTPUT = AttributeError: 'FIFOQueue' object has no attribute 'eval'
print(filenameQ.eval())

# object to read records
recordReader = tf.TFRecordReader()

# read the full set of features for a single example
key, fullExample = recordReader.read(filenameQ)

# NO OUTPUT: program hangs
print(fullExample.eval())

# parse the full example into its' component features.
features = tf.parse_single_example(
fullExample,
features={
    'image/height': tf.FixedLenFeature([], tf.int64),
    'image/width': tf.FixedLenFeature([], tf.int64),
    'image/colorspace': tf.FixedLenFeature([], dtype=tf.string, default_value=''),
    'image/channels': tf.FixedLenFeature([], tf.int64),
    'image/class/label': tf.FixedLenFeature([], tf.int64),
    'image/class/text': tf.FixedLenFeature([], dtype=tf.string, default_value=''),
    'image/format': tf.FixedLenFeature([], dtype=tf.string, default_value=''),
    'image/filename': tf.FixedLenFeature([], dtype=tf.string, default_value=''),
    'image/encoded': tf.FixedLenFeature([], dtype=tf.string, default_value='')
})

# now we are going to manipulate the label and image features

label = features['image/class/label']
image_buffer = features['image/encoded']

# Decode the jpeg
with tf.name_scope('decode_jpeg', [image_buffer], None):
# decode turns tensor of type string. 0-D the JPEG encoded image
# to tensor of type uint8. 3-D with shape [height, width, channels]
    image = tf.image.decode_jpeg(image_buffer, channels=3)

image = tf.reshape(image, [HEIGHT, WIDTH, NUM_CHANNELS])
image = tf.to_float(image, "ToFloat")

# re-define label as a "one-hot" vector
# it will be [0,1] or [1,0] here.
# This approach can easily be extended to more classes
label = tf.one_hot(label - 1, NUM_CLASSES, dtype=tf.int64)

init = tf.global_variables_initializer()
sess.run(init)
# NO OUTPUT: program hangs
print(label.eval())

When I created the TFRecord file I followed the example here with a label file mylabels.txt containing go and stop and my directory structure is as follows:

traffic_sign/train/go/go*.jpeg
traffic_sign/train/stop/stop*.jpeg
traffic_sign/validation/go/go*.jpeg
traffic_sign/validation/stop/stop*.jpeg

I used the command:

python build_image_data.py --train_directory=./train --output_directory=./  \
--validation_directory=./validation --labels_file=mylabels.txt   \
--train_shards=1 --validation_shards=1 --num_threads=1

The records file was created and just contains lots of bytes.

I have no clue how to solve this, I don't know whether I've made a mistake creating the dataset. But the image should be 72x72x3 so I don't know why there's a tensor in my model with 14040 values. And the fact I can't seem to evaluate a tensor and the program just hangs isn't allowing me to debug.

Help MUCH appreciated


问:
Turning an array into a multidimensional array? Javascript
I am struggling to create a simple function that will taking an array such as

```<code>["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]
</code>```

and turn it into a multidimensional array that looks like this

```<code>[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]
</code>```

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!

答:
most intuitive for me, just keep yanking items off the original array until it is empty:</p>

```<code>    let array = ["chicken", "10 lbs", "hot sauce", "4 cups", "celery", "1 stalk"],
        newArray = [];
    while (array.length) {
        newArray.push([array.shift(), array.shift()]);
    }
    console.log(newArray);
</code>```

Body:
I am struggling to create a simple function that will taking an array such as

["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]

and turn it into a multidimensional array that looks like this

[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!

Body:
most intuitive for me, just keep yanking items off the original array until it is empty:

    let array = ["chicken", "10 lbs", "hot sauce", "4 cups", "celery", "1 stalk"],
        newArray = [];
    while (array.length) {
        newArray.push([array.shift(), array.shift()]);
    }
    console.log(newArray);


问:
how can I get my ids products with foreach?
i want to valid one the sale is processed , but my last stock is equal to  x stock then it will be added to notification table , but how can I get my products ids only ids foreach , to after that send them hashed to my get_product

functions to get cart

```<code> $this->session->carrito = $this->sale->checar_existe_carrito();
 $array  = $this->sale->get_all_cart($this->session->carrito);
</code>```

json

```<code>[{"id":"4165","qty":"1.00","price":"77.00","name":"hammer"},{"id":"4168","qty":"3.00","price":"7.00","name":"whey protein"},{"id":"4169","qty":"3.00","price":"500.00","name":"papas"}]
</code>```

function to valid then stock product is equal to x stock

```<code>public function concretar_venta(){
        if($this->sale->checa_carrito_vacio($this->session->carrito)){
            $total = $this->input->post("total", TRUE);
            $cantidad_pagada = $this->input->post("cantidad_pagada", TRUE);
            $cambio = $cantidad_pagada - $total;
            $producto = $this->products->get_product('861578d797aeb0634f77aff3f488cca2');
            if($this->sale->concretar_venta($this->session->carrito, $total, $cantidad_pagada, $cambio)){
                if($producto->stock <= 2){
                   $this->notification->addNotification('low stock', $product_id[$output], $user_id[$output_u], 'low stock',now());
                }else{
                    echo 'bien';
                }
            }
            else{
                echo "Ocurrio un error al concretar la venta, por favor intentelo de nuevo";
            }
        }
        else{
            "El carrito está vacío";
        }
    }
</code>```

retrieve function tests

```<code>  public function FunctionName() {
    $json = '[{"id":"4165","qty":"1.00","price":"77.00","name":"hammer"},{"id":"4168","qty":"3.00","price":"7.00","name":"whey protein"},{"id":"4169","qty":"3.00","price":"500.00","name":"papas"}]';

    $jsonArray = json_decode($json, true);

    $ids = array();

    foreach ($jsonArray as $value) {
      $ids[] = md5($value['id']);
    }
      print_r($ids);
      $producto = $this->products->get_product($ids);
    }
</code>```

答:
This solution based on your provided JSON

```<code>$json = '[{"id":"4165","qty":"1.00","price":"77.00","name":"hammer"},{"id":"4168","qty":"3.00","price":"7.00","name":"whey protein"},{"id":"4169","qty":"3.00","price":"500.00","name":"papas"}]';

$jsonArray = json_decode($json, true);
// echo '```'; print_r($jsonArray); die; // check what is coming in array

$ids = array();
// extract ids using loop
foreach ($jsonArray as $value) {
  $ids[] = md5($value['id']);
}
// print_r($ids); die;

foreach ($ids as $id) {
  $producto = $this->products->get_product($id);
}
```

You can experience live here Link

Body:
i want to valid one the sale is processed , but my last stock is equal to  x stock then it will be added to notification table , but how can I get my products ids only ids foreach , to after that send them hashed to my get_product

functions to get cart

 $this->session->carrito = $this->sale->checar_existe_carrito();
 $array  = $this->sale->get_all_cart($this->session->carrito);

json

[{"id":"4165","qty":"1.00","price":"77.00","name":"hammer"},{"id":"4168","qty":"3.00","price":"7.00","name":"whey protein"},{"id":"4169","qty":"3.00","price":"500.00","name":"papas"}]

function to valid then stock product is equal to x stock

public function concretar_venta(){
        if($this->sale->checa_carrito_vacio($this->session->carrito)){
            $total = $this->input->post("total", TRUE);
            $cantidad_pagada = $this->input->post("cantidad_pagada", TRUE);
            $cambio = $cantidad_pagada - $total;
            $producto = $this->products->get_product('861578d797aeb0634f77aff3f488cca2');
            if($this->sale->concretar_venta($this->session->carrito, $total, $cantidad_pagada, $cambio)){
                if($producto->stock <= 2){
                   $this->notification->addNotification('low stock', $product_id[$output], $user_id[$output_u], 'low stock',now());
                }else{
                    echo 'bien';
                }
            }
            else{
                echo "Ocurrio un error al concretar la venta, por favor intentelo de nuevo";
            }
        }
        else{
            "El carrito está vacío";
        }
    }

retrieve function tests

  public function FunctionName() {
    $json = '[{"id":"4165","qty":"1.00","price":"77.00","name":"hammer"},{"id":"4168","qty":"3.00","price":"7.00","name":"whey protein"},{"id":"4169","qty":"3.00","price":"500.00","name":"papas"}]';

    $jsonArray = json_decode($json, true);

    $ids = array();

    foreach ($jsonArray as $value) {
      $ids[] = md5($value['id']);
    }
      print_r($ids);
      $producto = $this->products->get_product($ids);
    }

Body:
This solution based on your provided JSON

$json = '[{"id":"4165","qty":"1.00","price":"77.00","name":"hammer"},{"id":"4168","qty":"3.00","price":"7.00","name":"whey protein"},{"id":"4169","qty":"3.00","price":"500.00","name":"papas"}]';

$jsonArray = json_decode($json, true);
// echo '<pre>'; print_r($jsonArray); die; // check what is coming in array

$ids = array();
// extract ids using loop
foreach ($jsonArray as $value) {
  $ids[] = md5($value['id']);
}
// print_r($ids); die;

foreach ($ids as $id) {
  $producto = $this->products->get_product($id);
}

You can experience live here Link


问:
Runtime error but project compiles fine - Imports/using missing
I am very confused right now. I have VS2008 at my job right now and I have a weird behavior that I have been searching for a while now.

When I compile the project, it works fine, but in runtime I have an error saying object not defined or something like that. The problem is that the imports/using is missing in my class but why does it compile?

In fact, I want to be able to see that error when compiling not when running the webapp.

REEDITED: Here is an example. Lets say i want to use a typed list, I am declaring my object list(of int) for example without having added my imports (system.collection.generic) in the class. then I compile, it works and then I run it, it fails because of the imports missing. is this normal behavior or not?

REREEDITED: I just noticed that the DLL of all my references were not copied in my bin folders even though all of them are set to "Copy local = true". Is it possible that it has to do with our shared directory (all external dlls) being on a network drive (\server\shared). I am really out of ideas on this issue....

答: problem was because we were having the classes in the app_data folder</p>


问:
Docker Toolbox port mapping not working
I have installed docker toolbox on a windows machine, after running a container with the following  command, I didn't see anything listening on my host machine's specified port (82).

```<code>docker run -ti -p 82:80 --name=container_alias someprovider/image:some_tag
</code>```

I did attach to this contianer and did a simple check inside the container using:

```<code>curl localhost:80
</code>```

it did return html source content, which means the container is running properly.
What could be the reason of this unexpected behavior?

答:
My guess is you have another server set-up on localhost but I can't be sure. Docker Machine doesn't map to localhost. Unless you've somehow set-up localhost to redirect to the IP address of your docker machine.

You may want to read Get started with Docker Machine and a local VM
.

Also -p 82:80 exposes the container's port 80 to the machine's port 82. So you would need to curl someipaddress:82

Title: Docker Toolbox port mapping not working

Body:
I have installed docker toolbox on a windows machine, after running a container with the following  command, I didn't see anything listening on my host machine's specified port (82).

docker run -ti -p 82:80 --name=container_alias someprovider/image:some_tag

I did attach to this contianer and did a simple check inside the container using:

curl localhost:80

it did return html source content, which means the container is running properly.
What could be the reason of this unexpected behavior?


问:
Appending jquery to website by chrome extension
I made some chrome extension, it works but I want to use jquery because it is easier.

My extension javascript file contains:

```<code>$('body').append('<script src="/someFreeHost/jquery.js"></script><script src="/someFreeHost/file.js"></script>');
</code>```

And when I try to use jquery code inside file.js, I get error like jquery wasn't inserted. But when I use regular js code everything works.

json file contains:

```<code>"content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["jquery.js","main.js"]
        },
</code>```

答:
Your manifest content script tries loading a local jquery.js first, then main.js. If you're not providing a local copy of jquery.js, then calling $('body') will pop an error

You can either append script tags using vanilla JS, or you can provide a local copy of jquery.js with your extensions

Edited from original because I thought dynamically appending script tags wouldn't cause them to load

Body:
I made some chrome extension, it works but I want to use jquery because it is easier.

My extension javascript file contains:

$('body').append('');

And when I try to use jquery code inside file.js, I get error like jquery wasn't inserted. But when I use regular js code everything works.

json file contains:

"content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["jquery.js","main.js"]
        },


问:
What are use cases for *not* resetting a groupby index in pandas
When working with groupby on a pandas DataFrame instance, I have never not used either as_index=False or reset_index(). I cannot actually think of any reason why I wouldn't do so. Because my behavior is not the pandas default (indeed, because the groupby index exists at all), I suspect that there is some functionality of pandas that I am not taking advantage of.

Can anyone describe cases where it would be advantageous to not reset the index?

答:
When you perform a groupby/agg operation, it is natural to think of the result as a mapping from the groupby keys to the aggregated scalar values. If we were using plain Python, a dict would be the natural data structure to hold such a mapping from keys to values. Since we are using Pandas, a Series is the natural data structure. Its index would hold the keys, and the Series values would be the aggregrated scalars. If there is more than one aggregated value for each key, then the natural data structure to use would be a DataFrame.

The advantage of holding the keys in an index rather than a column is that looking up values based on index labels is an O(1) operation, whereas looking up values based on a value in a column is an O(n) operation.

Since the result of a groupby/agg operation fits naturally into a Series or DataFrame with groupby keys as the index, and since indexes have this special fast lookup property, it is better to return the result in this form by default.


问:
r - dedupe the rows with value in dataframe
How to subset only the rows with values in a particular column among the duplicates based on another column.

Example:

```<code>df

A B  C D
1 NA 8 7
1 5  8 9
2 6  5 8
2 NA 5 6
3 NA  8 5
</code>```

So in the above dataset, first 4 rows are duplicate based on column A and C, so among them, I want to choose only the rows which has value in column B.

Desired output,

```<code>A B C D
1 5 8 9
2 6 5 8
3 NA 8 5
</code>```

Thanks.

答:
Duplicates back or forwards and not missing on B; or not a duplicate:

```<code>anydup <- duplicated(df[c("A","C")]) | duplicated(df[c("A","C")], fromLast=TRUE)
df[(anydup & (!is.na(df$B))) | (!anydup),]

#  A  B C D
#2 1  5 8 9
#3 2  6 5 8
#5 3 NA 8 5
</code>```

Or use ave to check the length per group as per @HubertL's dplyr answer:

```<code>df[!is.na(df$B) | ave(df$B, df[c("A","C")], FUN=length)==1,]
#  A  B C D
#2 1  5 8 9
#3 2  6 5 8
#5 3 NA 8 5
</code>```

Body:
How to subset only the rows with values in a particular column among the duplicates based on another column.

Example:

df

A B  C D
1 NA 8 7
1 5  8 9
2 6  5 8
2 NA 5 6
3 NA  8 5

So in the above dataset, first 4 rows are duplicate based on column A and C, so among them, I want to choose only the rows which has value in column B.

Desired output,

A B C D
1 5 8 9
2 6 5 8
3 NA 8 5

Thanks.

Body:
Duplicates back or forwards and not missing on B; or not a duplicate:

anydup <- duplicated(df[c("A","C")]) | duplicated(df[c("A","C")], fromLast=TRUE)
df[(anydup & (!is.na(df$B))) | (!anydup),]

#  A  B C D
#2 1  5 8 9
#3 2  6 5 8
#5 3 NA 8 5

Or use ave to check the length per group as per @HubertL's dplyr answer:

df[!is.na(df$B) | ave(df$B, df[c("A","C")], FUN=length)==1,]
#  A  B C D
#2 1  5 8 9
#3 2  6 5 8
#5 3 NA 8 5


问:
Batch file copy & paste
I'm using a batch file to copy my Facebook username and password.
It automatically copies my username and it waits 10 seconds, then it copies my Password.

My question is:

Is it possible to create a batch file that copies my username and waits until I paste it, and after I paste it in Facebook it automatically copies my password?

Here is my batch file:

```<code>@echo off
cls
start "" "https://www.facebook.com/"
echo|set /p="username@hotmail.com"|clip
timeout /t 10
echo|set /p=Password|clip
exit
</code>```

Thank you.

答: It's not possible or secure. However you might be able to type automatically with a vbscript, perhaps you should post a second question being open to all script types. Still not secure though and I would not recommend it.</p>

Title: Batch file copy & paste

Body:
I'm using a batch file to copy my Facebook username and password.
It automatically copies my username and it waits 10 seconds, then it copies my Password.

My question is:

Is it possible to create a batch file that copies my username and waits until I paste it, and after I paste it in Facebook it automatically copies my password?

Here is my batch file:

@echo off
cls
start "" "https://www.facebook.com/"
echo|set /p="username@hotmail.com"|clip
timeout /t 10
echo|set /p=Password|clip
exit

Thank you.


问:
Recommended word order of names?
From my perspective there can be (at least) two aproaches how to create a name for a variable, function, class etc.

Structured:

```<code>history_clear()
history_save_to_file()
cache_remove_entry()
cache_find()
browser_window_url_trim()
</code>```

Readable for humans:

```<code>clear_history()
save_history_to_file()
remove_entry_from_cache()
find_in_cache()
check_for_updates()
</code>```

What is the preferred word order? Is there any?
I'm quite new to the programming but I'd like to acquire the good coding habits from the beginning. I've briefly read the PEP 8 Style Guide but I didn't find the answer there.

答:
For this one issue, the approach I learned has served me well as abstract data types evolved to OOP, in designs from projects of 250K lines down to student exercises.

Objects are nouns or noun phrases

Functions are verbs or verb phrases

When I'm programming, each line of code is a command, a verb.  I want to write it as a verb.  Thus, I prefer your option 2: clear_history is more easily understood than history_clear.

Beyond this, if you name your variables (objects) well, then your organizational wants will follow, since the object will imply the way you're using the variable.  For instance, you'll write something like

```<code>symbiont_browser.trim_window(x_size, y_size)
</code>```

Title: Recommended word order of names?

Body:
From my perspective there can be (at least) two aproaches how to create a name for a variable, function, class etc.

Structured:

history_clear()
history_save_to_file()
cache_remove_entry()
cache_find()
browser_window_url_trim()

Readable for humans:

clear_history()
save_history_to_file()
remove_entry_from_cache()
find_in_cache()
check_for_updates()

What is the preferred word order? Is there any?
I'm quite new to the programming but I'd like to acquire the good coding habits from the beginning. I've briefly read the PEP 8 Style Guide but I didn't find the answer there.

Body:
For this one issue, the approach I learned has served me well as abstract data types evolved to OOP, in designs from projects of 250K lines down to student exercises.

Objects are nouns or noun phrases

Functions are verbs or verb phrases

When I'm programming, each line of code is a command, a verb.  I want to write it as a verb.  Thus, I prefer your option 2: clear_history is more easily understood than history_clear.

Beyond this, if you name your variables (objects) well, then your organizational wants will follow, since the object will imply the way you're using the variable.  For instance, you'll write something like

symbiont_browser.trim_window(x_size, y_size)


答:
Using dplyr:</p>

```<code>df <- read.table(text="A B  C D
1 NA 8 7
1 5  8 9
2 6  5 8
2 NA 5 6
3 NA  8 5", header=T)

df %>%
  group_by(A,C) %>%
  filter(n()==1|!is.na(B))

      A     B     C     D
  <int> <int> <int> <int>
1     1     5     8     9
2     2     6     5     8
3     3    NA     8     5
</code>```

Title: r - dedupe the rows with value in dataframe

Body:
Using dplyr:

df <- read.table(text="A B  C D
1 NA 8 7
1 5  8 9
2 6  5 8
2 NA 5 6
3 NA  8 5", header=T)

df %>%
  group_by(A,C) %>%
  filter(n()==1|!is.na(B))

      A     B     C     D
  <int> <int> <int> <int>
1     1     5     8     9
2     2     6     5     8
3     3    NA     8     5


问:
How can I force Firebase Realtime Database to use WebSockets?
I know the Firebase Realtime Database web SDK can use either WebSockets or long-polling to talk to the backend servers. Is there a way to force it to only use WebSockets?</p>

答:
In general, you don't want to do this since the Firebase SDK automatically detects whether the client supports WebSockets and will use them if possible. Since WebSockets don't work reliably in all browsers and in all environments (e.g. proxies occasionally don't reliably support WebSocket traffic), forcing WebSocket usage may cause your app to not work reliably in some situations.

As a diagnostic tool or to work around very specific issues, you can force the client to use WebSockets by changing your databaseURL to wss://<app>.firebaseio.com/ instead of https://<app>.firebaseio.com/ but if you find yourself needing to do this, it's probably worth reaching out to support to see if there's a better solution.


问:
Visual Studio BeforeBuild using xcopy command
I am using the following beforebuild target and this works fine:

```<code><Target Name="BeforeBuild" Condition=" $(Configuration) == 'Debug' ">
    <Exec Command="xcopy ..\mycomponent\mylateboundassembly\bin\debug\*.* bin /q /r /y">
  </Target>
</code>```

however when the folder mycomponent has a space in it (my component) which i cannot remove(legacy code), I cannot get xcopy to work

Anyone know a way use xcopy in beforebuild where paths have a space?
Thanks

答:
Put quotes around the file path.</p>

```<code><Target Name="BeforeBuild" Condition=" $(Configuration) == 'Debug' ">
    <Exec Command="xcopy \"..\mycomponent\mylateboundassembly\bin\debug\*.*\" bin /q /r /y">
</Target>
</code>```

Body:
I am using the following beforebuild target and this works fine:

<Target Name="BeforeBuild" Condition=" $(Configuration) == 'Debug' ">
    <Exec Command="xcopy ..\mycomponent\mylateboundassembly\bin\debug\*.* bin /q /r /y">
  </Target>

however when the folder mycomponent has a space in it (my component) which i cannot remove(legacy code), I cannot get xcopy to work

Anyone know a way use xcopy in beforebuild where paths have a space?
Thanks

Body:
Put quotes around the file path.

<Target Name="BeforeBuild" Condition=" $(Configuration) == 'Debug' ">
    <Exec Command="xcopy \"..\mycomponent\mylateboundassembly\bin\debug\*.*\" bin /q /r /y">
</Target>


问:
Can I import and bind python-2.7's function to another function in python-3.x?
Some python-2.7 and python-3.x functions have the same name, but perform differently. Can I import use a py2.7 function in python-3.x one, by changing its name?

The motivating example is python-2.7's "print", i.e. print "TEXT" which does not use without parenthesis, compared to print("TEXT") in python 3. Can I keep the python 2 "print" by binding it to something like pr?

(By the way, the issue for me is typing and escaping the brackets. The keys ( and ) are harder to press than a space bar. Also, because my IDE puts them in automatically, I then need to move my cursor out of it.)

Note: I asked this previously, yet has been wrongly marked as a duplicate.
   Again, to be clear, I'm specifically asking if I can bind a python 2 function to a new name in order to use its functionality in python-3.x.

Can I bind python-2.7's `print` in python-3.x, allowing me to use `print` without parenthesis in python-3.x?

I do not know how to contact moderators via internal message or correct this wrongful flag.

答:
If your real problem is with the parentheses in print() for python 3, then no, as far as I know there's not really a solution. If it's a different function, you could always do

```<code>def funcName(arg):
    return anotherFunc(arg)
</code>```

or as chepner comments

```<code>funcName = anotherFunc
</code>```

effectively renaming anotherFunc().

As for your IDE specific issues, there's probably a way to turn off the automatic parentheses (or you could just use the arrow keys  on your keyboard) and the more you use the parentheses, the faster you'll get using them, which is probably a good thing, as they're used in basically every function you'll ever use.

Finally, it's best not to force a language to do a specific thing that it doesn't really provide for. You don't use GOTOs in Python - they're not built in for a reason. You can write them using other methods. You use parentheses in python 3 - don't try to change that! There's another reason not to alter a language in the way you're describing - it decreases the readability of your code. Everyone will know what you mean when you write

```<code>''.join(something)
</code>```

but not when you write

```<code>randomFuncName(something)
</code>```

and then in some obscure spot you have a function like the one described above that renames ''.join.

Body:
If your real problem is with the parentheses in print() for python 3, then no, as far as I know there's not really a solution. If it's a different function, you could always do

def funcName(arg):
    return anotherFunc(arg)

or as chepner comments

funcName = anotherFunc

effectively renaming anotherFunc().

As for your IDE specific issues, there's probably a way to turn off the automatic parentheses (or you could just use the arrow keys  on your keyboard) and the more you use the parentheses, the faster you'll get using them, which is probably a good thing, as they're used in basically every function you'll ever use.

Finally, it's best not to force a language to do a specific thing that it doesn't really provide for. You don't use GOTOs in Python - they're not built in for a reason. You can write them using other methods. You use parentheses in python 3 - don't try to change that! There's another reason not to alter a language in the way you're describing - it decreases the readability of your code. Everyone will know what you mean when you write

''.join(something)

but not when you write

randomFuncName(something)

and then in some obscure spot you have a function like the one described above that renames ''.join.