问:
Cannot construct KafkaProducer on brokers

```<code>Produce(String broker,String topic,int count){
        this.topic=topic;
        props.put("bootstrap.servers",broker);
        props.put("buffer.memory",67108864);
        props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
    }
    public void run(){
        InetAddress ia=null;
        try {
            ia = InetAddress.getLocalHost();
        }catch (Exception e){
            logger.error(e);
        }
        List<KafkaProducer<String,String>> producers=new ArrayList<KafkaProducer<String,String>>();
        System.out.println(6);
        for(int i=0;i<10;i++){
            try {
                KafkaProducer<String, String> pro = new KafkaProducer<String, String>(props);
                System.out.println(6.5);
                producers.add(pro);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        System.out.println(7);
        ...
    }
</code>```

I'm working on produce some sample data to Kafka.

The cluster is CDH 5.5.0 and kafka version is 0.10.2.

Once I was able to run this to produce data to topicpartitions.
For producing to topics from remote I set the advertised.host.name to the hostname of each broker and then I can produce to topics from clients outside the cluster.

But I can't run the same code on any brokers from then on,even if I remove the advertised.host.name as it used to be.

As I try to run this as Jar on any server in hadoop cluster(7 servers,3 as Kafka broker) except the one runs zookeeper, System.out won't reach "6.5",means the construction of KafkaProducer is blocked and no exceptions thrown.

Have someone met something like this before?

答:
This is embarrassing because it's caused by java version difference.
I build it with jdk1.8 while it's jdk1.6 on cluster.</p>

Body:
Produce(String broker,String topic,int count){
        this.topic=topic;
        props.put("bootstrap.servers",broker);
        props.put("buffer.memory",67108864);
        props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
    }
    public void run(){
        InetAddress ia=null;
        try {
            ia = InetAddress.getLocalHost();
        }catch (Exception e){
            logger.error(e);
        }
        List<KafkaProducer<String,String>> producers=new ArrayList<KafkaProducer<String,String>>();
        System.out.println(6);
        for(int i=0;i<10;i++){
            try {
                KafkaProducer<String, String> pro = new KafkaProducer<String, String>(props);
                System.out.println(6.5);
                producers.add(pro);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        System.out.println(7);
        ...
    }

I'm working on produce some sample data to Kafka.

The cluster is CDH 5.5.0 and kafka version is 0.10.2.

Once I was able to run this to produce data to topicpartitions.
For producing to topics from remote I set the advertised.host.name to the hostname of each broker and then I can produce to topics from clients outside the cluster.

But I can't run the same code on any brokers from then on,even if I remove the advertised.host.name as it used to be.

As I try to run this as Jar on any server in hadoop cluster(7 servers,3 as Kafka broker) except the one runs zookeeper, System.out won't reach "6.5",means the construction of KafkaProducer is blocked and no exceptions thrown.

Have someone met something like this before?


来源: stackexchange

问:
Excel - checking for duplicates from a list of values within two columns of different groups of IDs
I am trying to find a way to remove duplicates from a list of values between a column of "have and not have" and includes everything from the original list. I need this to repeat for each set of IDs.

This list would be: A1, B1, C1, D1, E1.

An example of the raw data would be:

```<code>UniqueID | Have | Not Have
---------------------------
Z12345   | A1   | B1
Z12345   | A1   | C1
Z12345   | A1   | D1
Z12345   | A1   | E1
Y12345   | A1   | D1
Y12345   | B1   | E1
Y12345   | C1   | D1
</code>```

The output I'm trying to get is:

```<code>UniqueID | Have | Not Have
---------------------------
Z12345   | A1   | B1
Z12345   |      | C1
Z12345   |      | D1
Z12345   |      | E1
Y12345   | A1   | D1
Y12345   | B1   | E1
Y12345   | C1   |
</code>```

I can't think of any way to approach this. I thought maybe running If statements to check if the IDs are matching and then run an if statement to remove the duplicates, but I couldn't figure out how to run it separately for each set of IDs. Any help or direction on how to approach this would be really appreciated!

答:
Here's my attempt using formulas. I would consider this just a starting point to spark ideas or improve on. Basically I use the offset function to create a dynamic range for each UniqueID set. Can't guarantee that this totally works and with all the lookups I would imagine it might be really slow with a large data set.

I would not consider this robust as I made quite a few assumptions:

Data is sorted by UniqueID

There are no duplicates across columns

The spreadsheet is setup exactly like this

First enter the following formulas:

```<code>D2: IF(A2<>A1,IFERROR(VALUE(D1),0)+COUNTA(A:A),D1)
E2: MATCH(B2,OFFSET($A$1,MATCH(A2,A:A,0)-1,1,COUNTIF(A:A,A2),1),0)+D2
F2: MATCH(C2,OFFSET($A$1,MATCH(A2,A:A,0)-1,2,COUNTIF(A:A,A2),1),0)+D2
G2: IF(E2>IFERROR(VALUE(E1),0),B2,"")
H2: IF(F2>IFERROR(VALUE(F1),0),C2,"")
</code>```

Then copy these formulas down to the rest of the rows. Toggling formulas on (using ctrl+tilde) it should look like this:

Results should look like this (columns G & H):

ContentLicense: CC BY-SA 3.0

Body:
I am trying to find a way to remove duplicates from a list of values between a column of "have and not have" and includes everything from the original list. I need this to repeat for each set of IDs.

This list would be: A1, B1, C1, D1, E1.

An example of the raw data would be:

UniqueID | Have | Not Have
---------------------------
Z12345   | A1   | B1
Z12345   | A1   | C1
Z12345   | A1   | D1
Z12345   | A1   | E1
Y12345   | A1   | D1
Y12345   | B1   | E1
Y12345   | C1   | D1

The output I'm trying to get is:

UniqueID | Have | Not Have
---------------------------
Z12345   | A1   | B1
Z12345   |      | C1
Z12345   |      | D1
Z12345   |      | E1
Y12345   | A1   | D1
Y12345   | B1   | E1
Y12345   | C1   |

I can't think of any way to approach this. I thought maybe running If statements to check if the IDs are matching and then run an if statement to remove the duplicates, but I couldn't figure out how to run it separately for each set of IDs. Any help or direction on how to approach this would be really appreciated!

Body:
Here's my attempt using formulas. I would consider this just a starting point to spark ideas or improve on. Basically I use the offset function to create a dynamic range for each UniqueID set. Can't guarantee that this totally works and with all the lookups I would imagine it might be really slow with a large data set.

I would not consider this robust as I made quite a few assumptions:

Data is sorted by UniqueID

There are no duplicates across columns

The spreadsheet is setup exactly like this

First enter the following formulas:

D2: IF(A2<>A1,IFERROR(VALUE(D1),0)+COUNTA(A:A),D1)
E2: MATCH(B2,OFFSET($A$1,MATCH(A2,A:A,0)-1,1,COUNTIF(A:A,A2),1),0)+D2
F2: MATCH(C2,OFFSET($A$1,MATCH(A2,A:A,0)-1,2,COUNTIF(A:A,A2),1),0)+D2
G2: IF(E2>IFERROR(VALUE(E1),0),B2,"")
H2: IF(F2>IFERROR(VALUE(F1),0),C2,"")

Then copy these formulas down to the rest of the rows. Toggling formulas on (using ctrl+tilde) it should look like this:

Results should look like this (columns G & H):


问:
Uninstalled Mongovue by mistake and looking for license file
I uninstalled MongoVue by mistake.

I was attempting to move the license from my old PC to a new PC.

I went into license manager but there was nothing useful there, I then clicked uninstall expecting a menu but there was no menu.

The guy who purchased the license has left and I can't find the details.

Does anyone know if the license is still on my PC somewhere and where I can find it?

答:
I could no longer find my license file as my companies email policy has since purged it and tried for a long time finding it on the pc and couldn't. I really love this program and I can't get to the company to ask them to move it. I was moving to a new work PC and needed to move my data over (win7 to win10).

Here is what I did and it worked (your mileage may vary, some of these folders may be hidden):

Copy the folder in program files to the new machine

C:\Program Files (x86)\MongoVUE\MongoVUE 1.6.9

Copy your AppData to new machine (connections.xml file mainly):

C:\Users\user_login\AppData\Local\MongoVUE

export the registry key in old machine (regedit):

Computer\HKEY_CURRENT_USER\Software\MongoVUE\License

When exporting the registration file, name it something.reg (it will look like name: "data", Type: "REG_BINARY", Data: random_value) This is your license data as the name suggests.

import the key in the new system with regedit.

create a shortcut to the "C:\Program Files (x86)\MongoVUE\MongoVUE 1.6.9\MongoVUE.exe" in:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\MongoVUE

Should work like nothing happened. Worked for me at least.


问:
PHP access values in multi dimensional array
I have an array called $ticket_quantities coming from an API which when I var dump comes out as

```<code>array(1) {
    [4128] => array(1) {
        [168] => array(2) {
            [7] => int(4)[8] => int(2)
        }
    }
}
</code>```

How can I access the [7] => int(4) value and [8] => int(2) value?

答:
Will be better if You use array_keys function for undefined keys of incoming array. Look in this sample:

```<code>// rebuld Your array
$arr = array(4128 => array(168 => array(7 => 4,8 => 2)));
// get node of first level
$myArr = $arr[array_keys($arr)[0]];
// get node of second level
$myArr = $myArr[array_keys($myArr)[0]];

// get firs and second node from threed level
$One = $myArr[array_keys($myArr)[0]];
$Two = $myArr[array_keys($myArr)[1]];
print $One;
print '<hr>';
print $Two;
</code>```

Body:
I have an array called $ticket_quantities coming from an API which when I var dump comes out as

array(1) {
    [4128] => array(1) {
        [168] => array(2) {
            [7] => int(4)[8] => int(2)
        }
    }
}

How can I access the [7] => int(4) value and [8] => int(2) value?

Body:
Will be better if You use array_keys function for undefined keys of incoming array. Look in this sample:

// rebuld Your array
$arr = array(4128 => array(168 => array(7 => 4,8 => 2)));
// get node of first level
$myArr = $arr[array_keys($arr)[0]];
// get node of second level
$myArr = $myArr[array_keys($myArr)[0]];

// get firs and second node from threed level
$One = $myArr[array_keys($myArr)[0]];
$Two = $myArr[array_keys($myArr)[1]];
print $One;
print '<hr>';
print $Two;


问:
Successive use of same method in block recalculates the method?
I've always assumed every time I call a method in Java the method is executed again. I've assumed the return value is not stored automatically unless I store it in a variable.

Then I ran across this code in Princeton's algs4.BST class where they call three methods twice each:

```<code>private boolean check() {
    if (!isBST())            StdOut.println("Not in symmetric order");
    if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent");
    if (!isRankConsistent()) StdOut.println("Ranks not consistent");
    return isBST() && isSizeConsistent() && isRankConsistent();
}
</code>```

Are they simply not concerned with performance? Or is the compiler smart enough keep the first return value of each method to use in the return statement?

Sorry if this is a duplicate seems like this answer should exist but I can't find it here or in Java docs. I found these (and others) but they don't answer my question:

Is this the cleanest way to repeat method call in Java?

How to call a method without repeat from other methods in java

答:
The check function in that code is only called in the context:

```<code>assert check();
</code>```

Asserts are not normally enabled in production code, and if asserts are not enabled, the assert statement does absolutely nothing. So the check function will only be run in debugging runs. That fact does not give license to be arbitrarily inefficient, but it is common to make no attempt to optimize such code. The point of code run as an assertion is to be obviously and indisputably correct while it verifies an invariant, precondition or postcondition, and optimizations -- even trivial ones like saving a result in a local variable -- do not contribute to that goal.

##14.10. The assert Statement

An assertion is an assert statement containing a boolean expression. An assertion is either enabled or disabled. If an assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates to false. If the assertion is disabled, execution of the assertion has no effect whatsoever.

Body:
I've always assumed every time I call a method in Java the method is executed again. I've assumed the return value is not stored automatically unless I store it in a variable.

Then I ran across this code in Princeton's algs4.BST class where they call three methods twice each:

private boolean check() {
    if (!isBST())            StdOut.println("Not in symmetric order");
    if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent");
    if (!isRankConsistent()) StdOut.println("Ranks not consistent");
    return isBST() && isSizeConsistent() && isRankConsistent();
}

Are they simply not concerned with performance? Or is the compiler smart enough keep the first return value of each method to use in the return statement?

Sorry if this is a duplicate seems like this answer should exist but I can't find it here or in Java docs. I found these (and others) but they don't answer my question:

Is this the cleanest way to repeat method call in Java?

How to call a method without repeat from other methods in java

Body:
The check function in that code is only called in the context:

assert check();

Asserts are not normally enabled in production code, and if asserts are not enabled, the assert statement does absolutely nothing. So the check function will only be run in debugging runs. That fact does not give license to be arbitrarily inefficient, but it is common to make no attempt to optimize such code. The point of code run as an assertion is to be obviously and indisputably correct while it verifies an invariant, precondition or postcondition, and optimizations -- even trivial ones like saving a result in a local variable -- do not contribute to that goal.

##14.10. The assert Statement

An assertion is an assert statement containing a boolean expression. An assertion is either enabled or disabled. If an assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates to false. If the assertion is disabled, execution of the assertion has no effect whatsoever.


问:
CSS center with translate and prevent content overflow
I have this code for centering both horizontally and vertically. It works well except when there is more content than fits, the content gets cut off. Is there a way to restrict this with css so it doesn't go out of visible area? I dont want to involve javascript.

.b {
  padding: 0;
  position: absolute;
  margin: 0;
  width: 100%;
  max-width: 500px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  <div class="b">dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus. </div>
</div></code>```

答:
You can add max-height: 100%; , which works in the snippet below. You might also have to add height settings to the ancestor elements, if there are no fixed heights, make them 100% all the way up to body and html.

.b {
  padding: 0;
  position: absolute;
  margin: 0;
  width: 100%;
  max-width: 500px;
  max-height: 100%;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="a">
  <div class="b">dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus. </div>
</div></code>```

Body:
I have this code for centering both horizontally and vertically. It works well except when there is more content than fits, the content gets cut off. Is there a way to restrict this with css so it doesn't go out of visible area? I dont want to involve javascript.

.b {
  padding: 0;
  position: absolute;
  margin: 0;
  width: 100%;
  max-width: 500px;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus.

Body:
You can add max-height: 100%; , which works in the snippet below. You might also have to add height settings to the ancestor elements, if there are no fixed heights, make them 100% all the way up to body and html.

.b {
  padding: 0;
  position: absolute;
  margin: 0;
  width: 100%;
  max-width: 500px;
  max-height: 100%;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
}

<div class="a">
  <div class="b">dui ut erat. Phasellus nibh magna, tempor vitae, dictum sed, vehicula sed, mauris. In enim arcu, porta vel, dictum eu, pretium a, ipsum. Donec cursus, lorem ac posuere viverra, sem tellus accumsan dolor, vel accumsan tortor est et est. Praesent molestie.
    Nunc Venenatis Sapien Ultrices Dui. Vivamus dolor. Integer vel ante. Proin felis. Maecenas non nisl eu mi hendrerit fringilla. Nullam vel ante et nunc accumsan viverra. Vestibulum nulla justo, tristique nec, tincidunt eget, ultricies sollicitudin,
    nulla. Proin dui ante, consectetur a, tincidunt in, mattis ut, ipsum. Sed tristique. Mauris et sapien. Quisque risus. Ut laoreet hendrerit mi. Nam vestibulum viverra diam. Nullam eros ipsum, rutrum ut, ultricies sed, congue sed, est. Pellentesque
    porttitor. Donec dictum urna eu mi. Maecenas in lorem. Vestibulum in ipsum. Praesent ac nunc. Donec vitae lectus. Etiam commodo velit ut mi. Duis egestas, quam faucibus interdum tincidunt, enim sem tincidunt tellus, sed condimentum tellus tortor u
    mi. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce aliquet. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Aliquam ollicitudin, nisi egestas scelerisque
    pretium, odio enim sodales metus, venenatis vulputate arcu quam eget purus. Fusce convallis mattis nunc. Fusce non nunc. Maecenas nec tellus a mi ornare auctor. Proin magna nunc, congue ut, dapibus eu, placerat vitae, erat. Nam egestas pretium mauris.
    Cras posuere, est nec egestas scelerisque, tellus justo scelerisque nisi, at consequat ante dolor eget diam. Phasellus pharetra, lectus vel molestie tincidunt, orci tellus dapibus odio, vel semper lacus tortor vitae metus.Vestibulum accumsan enim
    nec ipsum. Nunc cursus sapien. Etiam fermentum luctus arcu. condimentum neque molestie tincidunt. Fusce egestas, est ut fringilla facilisis, quam purus blandit dui, eget egestas mauris nibh ut diam. Phasellus volutpat. Sed fringilla tellus in sem.
    Curabitur dignissim nunc id arcu. Nulla facilisi. In imperdiet. Aliquam enim. Nullam hendrerit purus. Suspendisse lectus orci, commodo eget, luctus ac, venenatis id, magna. In hac habitasse platea dictumst. Fusce aliquam. Donec ut nisi ac diam posuere
    imperdiet. Cras est enim, consequat non, pretium at, molestie quis, sapien. Suspendisse porta, quam ac ultricies sagittis, libero nisi gravida sem, in convallis sem ante nec purus. Suspendisse in tellus vitae purus porttitor pharetra. Curabitur in
    ipsum. Fusce lobortis, ligula eu facilisis semper, arcu ipsum ornare lorem, ultricies tempor diam arcu vitae est. Aliquam non sapien. Phasellus quam. Praesent eu ligula id mauris tincidunt hendrerit. Fusce nec enim. Nam posuere. Morbi at ipsum vitae
    diam tempus mollis. Pellentesque sollicitudin condimentum neque. Sed auctor consequat lorem. Donec quis lacus fringilla augue venenatis vulputate. Duis lobortis consectetur libero. Aliquam erat volutpat. Etiam interdum bibendum purus. Vivamus id tellus
    et tellus dictum molestie. Nam sit amet arcu dictum mauris rhoncus tristique. Nunc rhoncus porta velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer tempor diam eu leo. Praesent leo. Morbi blandit,
    nulla non rhoncus dapibus, metus tellus posuere justo, et condimentum leo ante cursus libero. Vestibulum eu magna a metus pellentesque molestie. Nulla elementum iaculis velit. Nullam sit amet velit et sapien interdum accumsan. Vestibulum dapibus lectus
    quis orci. Mauris gravida sodales velit. Maecenas sollicitudin malesuada lacus. Morbi sollicitudin augue vel elit. Duis ipsum felis, fermentum id, iaculis id, fermentum et, velit. Ut ultricies. In nibh orci, euismod venenatis, vulputate ut, pharetra
    in, purus. Nam condimentum leo in nunc. Donec ut nisi vitae ante viverra imperdiet. Suspendisse in neque eu metus fermentum malesuada. Aliquam erat volutpat. Aenean nibh sem, varius vitae, facilisis sed, venenatis faucibus, neque. Quisque odio. Cras
    eget enim. Suspendisse potenti. Donec mattis, felis vel dignissim mattis, mi enim feugiat ligula, eget imperdiet eros nibh non risus. Nullam fermentum eros et eros. Mauris facilisis est ac velit. Nunc ipsum odio, pharetra ac, posuere et, adipiscing
    at, lacus. Nunc malesuada velit at quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Integer ipsum felis, placerat id, rutrum sed, molestie ornare, leo. Nam fermentum luctus leo. Curabitur in ipsum.
    Maecenas non lectus a quam porta consequat. Fusce molestie egestas ligula. Cras nisl risus, tempus ac, tincidunt eu, gravida sit amet, eros. Duis nec lacus sed ipsum scelerisque tempus. Phasellus sapien nunc, lacinia sit amet, vulputate vel, tincidunt
    nec, eros. Praesent quis ligula. Nulla facilisi. Nullam fermentum bibendum elit. Vivamus feugiat lacus. Mauris tempus. Vivamus lorem. Quisque blandit odio non mi. Etiam tempus, enim in dictum commodo, ante augue cursus sapien, non vehicula dolor lacus
    sed mi. Etiam enim lectus, dictum eget, scelerisque eget, luctus quis, velit. Maecenas semper vulputate nisi. Duis fringilla. Etiam iaculis nisl a ipsum. Nunc varius dolor id nisi. Curabitur sit amet velit auctor arcu ullamcorper luctus. </div>
</div>


问:
Java DAO for all class
I'm new to Java and I must make some DAO for my app. However, I don't want to make a DAO for each class (with interface) et override methods.
Is it possible to make a DAO extended by all the others, with methods working with all kind of Class ?
For example, a DAO that could handle class MyClass and class Foo with a single mehtod getList().
Thank you !</p>

答:
Not that gooed idea, in general, but...

If it is about low-level JDBC (no framework like Hibernate, Spring, etc.), then:

You can make an AbstractDAO class, then your other DAO-classes (UserDAO, ProductDAO, etc.), then you can make a CommonService class that has all those DAO-classes and provides the functions you need.

Example:

```<code>abstract class AbstractDAO {
    private DataSource dataSource;

    protected getDataSource() { // Inject it or hard-coded dataSource
        return dataSource;
    }
}
</code>```

```<code>public class UserDAO extends AbstractDAO {

    public User read(long id) {
        // blablabla
        return user;
    }

    public List<User> findAll() {
        // blablabla
        return users;
    }
    // and so on...
}
</code>```

```<code>public class ProductDAO extends AbstractDAO {

    public Product read(long id) {
        // blablabla
        return product;
    }

    public List<Product> findAll() {
        // blablabla
        return products;
    }
    // and so on...
}
</code>```

Then other repositories, and then:

```<code>public class CommonService {
    private final UserDAO userDAO = new UserDAO();
    private final ProductDAO productDAO = new ProductDAO();
    // other repositories

    public User readUser(long id) {
       return userDAO.read(id);
    }

    public Product readProduct(long id) {
       return productDAO.read(id);
    }

    public List<User> findAllUsers() {
        return userDAO.findAll();
    }

    public List<Product> findAllProducts() {
        return productDAO.findAll();
    }
}
</code>```

Title: Java DAO for all class

Body:
Not that gooed idea, in general, but...

If it is about low-level JDBC (no framework like Hibernate, Spring, etc.), then:

You can make an AbstractDAO class, then your other DAO-classes (UserDAO, ProductDAO, etc.), then you can make a CommonService class that has all those DAO-classes and provides the functions you need.

Example:

abstract class AbstractDAO {
    private DataSource dataSource;

    protected getDataSource() { // Inject it or hard-coded dataSource
        return dataSource;
    }
}

public class UserDAO extends AbstractDAO {

    public User read(long id) {
        // blablabla
        return user;
    }

    public List<User> findAll() {
        // blablabla
        return users;
    }
    // and so on...
}

public class ProductDAO extends AbstractDAO {

    public Product read(long id) {
        // blablabla
        return product;
    }

    public List<Product> findAll() {
        // blablabla
        return products;
    }
    // and so on...
}

Then other repositories, and then:

public class CommonService {
    private final UserDAO userDAO = new UserDAO();
    private final ProductDAO productDAO = new ProductDAO();
    // other repositories

    public User readUser(long id) {
       return userDAO.read(id);
    }

    public Product readProduct(long id) {
       return productDAO.read(id);
    }

    public List<User> findAllUsers() {
        return userDAO.findAll();
    }

    public List<Product> findAllProducts() {
        return productDAO.findAll();
    }
}


问:
Bootstrap cells with equal height
I have the following

```<code><div class="row">
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Slightly short text
      </p>
    </div>
  </div>
  <div class="col-md-6">
    <div class = "box-cell">
      <p>
        Text that<br>literally<br>spans<br>4 lines
      </p>
    </div>
  </div>
</div>
</code>```

and css

```<code>.box-cell
{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}
</code>```

So the problem that I am facing is that one of the cells is usually taller than the other.IS there any way for me to equalize how much height each cell takes up?
Searching didn't yield me which property I can manipulate to get same height :(

Here is jsfiddle
However in this fiddle I can not get them to be side by side to prove my point

EDIT: I guess I didn't specify it properly. I would like to have the borders be as tall as the tallest cell. So all the examples provided here actually take out the borders and instead color the background. If I do that then yes it gives illusion of every cell being the same, but I would like there to be a border of same height.

答:
I tried replicating what it sounds like you are looking for.

I would recommend you mess around with flexbox since it seems to do exactly what you are looking for.

```<code><div class="myc">
    <div class="col">
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>

    </div>
    <div class="col">
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>

    </div>
  </div>
</code>```

And for the CSS

```<code>.myc {
  display: flex;
}

.col {
  background-color: yellow;
  margin-right: 20px;
}
</code>```

Title: Bootstrap cells with equal height

Body:
I have the following

        Slightly short text

        Text that
literally
spans
4 lines

and css

.box-cell
{
    position:        relative;
    margin:          3px;
    border-style:    groove ridge ridge groove;
    border-width:    3px;
    background-size: cover;
}

So the problem that I am facing is that one of the cells is usually taller than the other.IS there any way for me to equalize how much height each cell takes up?
Searching didn't yield me which property I can manipulate to get same height :(

Here is jsfiddle
However in this fiddle I can not get them to be side by side to prove my point

EDIT: I guess I didn't specify it properly. I would like to have the borders be as tall as the tallest cell. So all the examples provided here actually take out the borders and instead color the background. If I do that then yes it gives illusion of every cell being the same, but I would like there to be a border of same height.

Body:
I tried replicating what it sounds like you are looking for.

I would recommend you mess around with flexbox since it seems to do exactly what you are looking for.

<div class="myc">
    <div class="col">
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>

    </div>
    <div class="col">
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>
      <p>Text of some sorts</p>

    </div>
  </div>

And for the CSS

.myc {
  display: flex;
}

.col {
  background-color: yellow;
  margin-right: 20px;
}


问:
Port awk one-liner to perl using regexes (Summing groups of data)
Given the following input:

```<code>£ cat problem
  Team 7
  John: 19
  Sue: 20
  Pam: 35
  Team 42
  Jeff: 12
  Sam: 3
  Phil: 26
  Jill: 10
  Team 9
  Bill: 19
  John: 7
  Linda: 15
</code>```

I am trying to reproduce the following output in a perl one-liner:

```<code>£ awk '/Team/ {x=$2} /: *[0-9]+/ {myarray[x]+=$2}; END{for (key in myarray) {print "Team " key ": " myarray[key]}}' problem
Team 42: 51
Team 7: 74
Team 9: 41
</code>```

This (basic) problem and the data actually comes from a perl tutorial.  http://learnperl.scratchcomputing.com/tutorials/csss/

I'm interested in something close to this, which I have tried...literally over 50 variations of:

```<code> £ perl -e 'while(<>){if (/Team/){$x = /(\d+)/;}else{/(\d+)/;$myarray{$x}+= {$1}; }} foreach $key (keys %myarray){print "$key\n";}' problem
</code>```

I know that 1) these regexes are not returning the match (the += {$1} was an attempt to remedy that), and 2) even if they were I am probably populating the hash incorrectly.  Googling potential solutions returns me verbose, multiline code.  I was waiting to get the keys outputting correctly before I even bothered moving onto the values, btw.

答:
Without examining the awk code, I'd write this perl:

```<code>perl -lne '
        if (/Team (\d+)/) {
            $t = $1;
        } elsif (/: (\d+)/) {
            $score{$t} += $1
        }
    } END {
        printf "Team %d: %d\n", $_, $score{$_} for keys %score
' problem
</code>```

```<code>Team 7: 74
Team 9: 41
Team 42: 51
</code>```

The -n option implicitly wraps a while (<>) {...} loop around the given code. See perldoc perlrun for all the details.

The } END { bit exploits that, and allows you to collect data inside the while loop, then do stuff with it when the loop is complete.

You can see how perl deals with one-liners by adding the -MO=Deparse option:

```<code>perl -MO=Deparse -lne '
        if (/Team (\d+)/) {
            $t = $1;
        } elsif (/: (\d+)/) {
            $score{$t} += $1
        }
    } END {
        printf "Team %d: %d\n", $_, $score{$_} for keys %score
' problem
</code>```

```<code>BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
    chomp $_;
    if (/Team (\d+)/) {
        $t = $1;
    }
    elsif (/: (\d+)/) {
        $score{$t} += $1;
    }
}
sub END {
    printf "Team %d: %d\n", $_, $score{$_} foreach (keys %score);
}
-e syntax OK
</code>```

I'm not sure why it turns the END block into a subroutine though.

A couple of notes about your code:

Use better variable names.

$x = /(\d+)/

m// used in scalar context will return a true/false value, regardless of the use of capturing parentheses (ref: http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators)

to assign the captured text to variables, you must have a list context on the left-hand side: ($a, $list, $of, $variables) = (a, list, of, values), so

```<code>($x) = /(\d+)/;   # with parentheses on the left-hand side
</code>```

$myarray{$x}+= {$1}

when you use {...} as an expression, you are creating a hash reference

in this case {$1}, your hash does not have enough elements: it requires an even numbered list of key-value pairs.

you just want $myarray{$x} += $1

foreach $key (keys %myarray){...}

an alternate way to iterate over a hash is to use the each function in a while loop:

```<code>while (my ($key, $value) = each %myarray) {
    print "Team $key: $value\n";
}
</code>```

Body:
Given the following input:

£ cat problem
  Team 7
  John: 19
  Sue: 20
  Pam: 35
  Team 42
  Jeff: 12
  Sam: 3
  Phil: 26
  Jill: 10
  Team 9
  Bill: 19
  John: 7
  Linda: 15

I am trying to reproduce the following output in a perl one-liner:

£ awk '/Team/ {x=$2} /: *[0-9]+/ {myarray[x]+=$2}; END{for (key in myarray) {print "Team " key ": " myarray[key]}}' problem
Team 42: 51
Team 7: 74
Team 9: 41

This (basic) problem and the data actually comes from a perl tutorial.  http://learnperl.scratchcomputing.com/tutorials/csss/

I'm interested in something close to this, which I have tried...literally over 50 variations of:

 £ perl -e 'while(<>){if (/Team/){$x = /(\d+)/;}else{/(\d+)/;$myarray{$x}+= {$1}; }} foreach $key (keys %myarray){print "$key\n";}' problem

I know that 1) these regexes are not returning the match (the += {$1} was an attempt to remedy that), and 2) even if they were I am probably populating the hash incorrectly.  Googling potential solutions returns me verbose, multiline code.  I was waiting to get the keys outputting correctly before I even bothered moving onto the values, btw.

Body:
Without examining the awk code, I'd write this perl:

perl -lne '
        if (/Team (\d+)/) {
            $t = $1;
        } elsif (/: (\d+)/) {
            $score{$t} += $1
        }
    } END {
        printf "Team %d: %d\n", $_, $score{$_} for keys %score
' problem

Team 7: 74
Team 9: 41
Team 42: 51

The -n option implicitly wraps a while (<>) {...} loop around the given code. See perldoc perlrun for all the details.

The } END { bit exploits that, and allows you to collect data inside the while loop, then do stuff with it when the loop is complete.

You can see how perl deals with one-liners by adding the -MO=Deparse option:

perl -MO=Deparse -lne '
        if (/Team (\d+)/) {
            $t = $1;
        } elsif (/: (\d+)/) {
            $score{$t} += $1
        }
    } END {
        printf "Team %d: %d\n", $_, $score{$_} for keys %score
' problem

BEGIN { $/ = "\n"; $\ = "\n"; }
LINE: while (defined($_ = <ARGV>)) {
    chomp $_;
    if (/Team (\d+)/) {
        $t = $1;
    }
    elsif (/: (\d+)/) {
        $score{$t} += $1;
    }
}
sub END {
    printf "Team %d: %d\n", $_, $score{$_} foreach (keys %score);
}
-e syntax OK

I'm not sure why it turns the END block into a subroutine though.

A couple of notes about your code:

Use better variable names.

$x = /(\d+)/

m// used in scalar context will return a true/false value, regardless of the use of capturing parentheses (ref: http://perldoc.perl.org/perlop.html#Regexp-Quote-Like-Operators)

to assign the captured text to variables, you must have a list context on the left-hand side: ($a, $list, $of, $variables) = (a, list, of, values), so

($x) = /(\d+)/;   # with parentheses on the left-hand side

$myarray{$x}+= {$1}

when you use {...} as an expression, you are creating a hash reference

in this case {$1}, your hash does not have enough elements: it requires an even numbered list of key-value pairs.

you just want $myarray{$x} += $1

foreach $key (keys %myarray){...}

an alternate way to iterate over a hash is to use the each function in a while loop:

while (my ($key, $value) = each %myarray) {
    print "Team $key: $value\n";
}


问:
Fixing render blocking CSS on WP

Hello I am trying to fix render blocking CSS recommendation from Google Page speed.

```<code><style>here goes critical path</style>
<link rel="preload" as="style" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" onload="this.rel='stylesheet'" />
<noscript id="aonoscrcss">
<link type="text/css" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" rel="stylesheet" />
</noscript>
</code>```

I use Autoptimize for this purpose, so I inserted critical path and checked defer CSS. However Google doesn't count this as a fixed recommendation.
From this code part, is there any issues that causing it, or it something else? Any hints on how to troubleshoot this issue?

And also Google shows 2 blocking css files with the same name and url.

答: With Autoptimize, you can enable the Inline all CSS? option, the problem will gone.

Title: Fixing render blocking CSS on WP

Body:
Hello I am trying to fix render blocking CSS recommendation from Google Page speed.

<link rel="preload" as="style" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" onload="this.rel='stylesheet'" />

<link type="text/css" media="all" href="wp-content/cache/autoptimize/css/autoptimize_fb3761d5ff1bb5dcb1bc273f35788f8e.css" rel="stylesheet" />

I use Autoptimize for this purpose, so I inserted critical path and checked defer CSS. However Google doesn't count this as a fixed recommendation.
From this code part, is there any issues that causing it, or it something else? Any hints on how to troubleshoot this issue?

And also Google shows 2 blocking css files with the same name and url.


问:
Application crash without logcat entry
I found that application crashes without logcat entries due to some Native crash. As in Android Studio 2.3.3 the logcat has both Verbose and No filters options are set by default: Well what are the ways of solving native crashes or identify these crashes?

My application is crashing on opening MapsActivity more than two times i.e on third(edit : now fourth) click to open brings it to crash.

Here is my MapsActivity it receives Location List from the MainActivity and adds markers to the Map on those locations.

```<code>import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
ArrayList<Location> locs = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    Bundle bundle = getIntent().getExtras();
    String jsonString = bundle.getString("KEY_LOCATIONS");

    Gson gson = new Gson();
    Type listOfLocationType = new TypeToken<List<Location>>() {
    }.getType();
    locs = gson.fromJson(jsonString, listOfLocationType);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    setUpMap();
}

public void setUpMap() {

    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
       return;}
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.getUiSettings().setCompassEnabled(true);

    addMarkeratLocation();
}

public void addMarkeratLocation() {
    int i;
    double lt=0.0,lg=0.0;
    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.mipmap.dottt);
    LatLng addpoint = new LatLng(0.0, 0.0);
    for (i = 0; i < locs.size(); i++) {
        lt=locs.get(i).getLatitude();
        lg=locs.get(i).getLongitude();
        addpoint = new LatLng(lt,lg );
        mMap.addMarker(new MarkerOptions().position(addpoint).icon(icon));

    }
    mMap.moveCamera(CameraUpdateFactory.newLatLng(addpoint));
    LatLng camloc= new LatLng(lt,lg);
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(camloc, 15));

}
}
</code>```

And this is from where in MainActivity the MapsActivity is being fired.

```<code>direction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "Showing directions", Toast.LENGTH_LONG).show();
            TinyDB tinydb = new TinyDB(MainActivity.this);
            olati=tinydb.getDouble("destination_lati",lati);
            olongi=tinydb.getDouble("destination_longi",longi);

            Gson gson = new Gson();
            String jsonString = gson.toJson(locs);
            Intent intent = new Intent(MainActivity.this,MapsActivity.class);
            intent.putExtra("KEY_LOCATIONS",jsonString);
            startActivity(intent);
        }
    });
</code>```

I don't know what of Logcat shall I post. How do I sort it out? Thanks in advance.

EDIT : Added Error Logcat
This is something around where the application crashes

12-06 00:12:06.190 18296-18307/com.example.acer.mylocationmap A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x40 in tid 18307 (FinalizerDaemon)
  12-06 00:12:07.800 3624-3624/? E/audit: type=1701 msg=audit(1512499327.795:2175): auid=4294967295 uid=10495 gid=10495 ses=4294967295 subj=u:r:untrusted_app:s0 pid=18307 comm="FinalizerDaemon" reason="memory violation" sig=11
  12-06 00:12:07.845 2845-20348/? E/android.os.Debug: ro.product_ship = true
  12-06 00:12:07.845 2845-20348/? E/android.os.Debug: ro.debug_level = 0x4f4c
  12-06 00:12:07.930 2845-2925/? E/InputDispatcher: channel ~ Channel is unrecoverably broken and will be disposed!
  12-06 00:12:07.930 2845-2925/? E/InputDispatcher: channel ~ Channel is unrecoverably broken and will be disposed!
  12-06 00:12:07.990 20349-20349/? E/Zygote: MountEmulatedStorage()
  12-06 00:12:07.990 20349-20349/? E/Zygote: v2
  12-06 00:12:07.995 20349-20349/? E/Zygote: accessInfo : 0
  12-06 00:12:07.995 20349-20349/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
  12-06 00:12:15.020 2845-2889/? E/ViewRootImpl: sendUserActionEvent() mView == null

答:
Check your build variant has debug set to true in the build.gradle file

This is commonly set to false on release versions of applications as it is a requirement for publishing to the play store .

Title: Application crash without logcat entry

Body:
I found that application crashes without logcat entries due to some Native crash. As in Android Studio 2.3.3 the logcat has both Verbose and No filters options are set by default: Well what are the ways of solving native crashes or identify these crashes?

My application is crashing on opening MapsActivity more than two times i.e on third(edit : now fourth) click to open brings it to crash.

Here is my MapsActivity it receives Location List from the MainActivity and adds markers to the Map on those locations.

import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

private GoogleMap mMap;
ArrayList<Location> locs = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    Bundle bundle = getIntent().getExtras();
    String jsonString = bundle.getString("KEY_LOCATIONS");

    Gson gson = new Gson();
    Type listOfLocationType = new TypeToken<List<Location>>() {
    }.getType();
    locs = gson.fromJson(jsonString, listOfLocationType);
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    setUpMap();
}

public void setUpMap() {

    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
       return;}
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.getUiSettings().setCompassEnabled(true);

    addMarkeratLocation();
}

public void addMarkeratLocation() {
    int i;
    double lt=0.0,lg=0.0;
    BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.mipmap.dottt);
    LatLng addpoint = new LatLng(0.0, 0.0);
    for (i = 0; i < locs.size(); i++) {
        lt=locs.get(i).getLatitude();
        lg=locs.get(i).getLongitude();
        addpoint = new LatLng(lt,lg );
        mMap.addMarker(new MarkerOptions().position(addpoint).icon(icon));

    }
    mMap.moveCamera(CameraUpdateFactory.newLatLng(addpoint));
    LatLng camloc= new LatLng(lt,lg);
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(camloc, 15));

}
}

And this is from where in MainActivity the MapsActivity is being fired.

direction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getBaseContext(), "Showing directions", Toast.LENGTH_LONG).show();
            TinyDB tinydb = new TinyDB(MainActivity.this);
            olati=tinydb.getDouble("destination_lati",lati);
            olongi=tinydb.getDouble("destination_longi",longi);

            Gson gson = new Gson();
            String jsonString = gson.toJson(locs);
            Intent intent = new Intent(MainActivity.this,MapsActivity.class);
            intent.putExtra("KEY_LOCATIONS",jsonString);
            startActivity(intent);
        }
    });

I don't know what of Logcat shall I post. How do I sort it out? Thanks in advance.

EDIT : Added Error Logcat
This is something around where the application crashes

12-06 00:12:06.190 18296-18307/com.example.acer.mylocationmap A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x40 in tid 18307 (FinalizerDaemon)
  12-06 00:12:07.800 3624-3624/? E/audit: type=1701 msg=audit(1512499327.795:2175): auid=4294967295 uid=10495 gid=10495 ses=4294967295 subj=u:r:untrusted_app:s0 pid=18307 comm="FinalizerDaemon" reason="memory violation" sig=11
  12-06 00:12:07.845 2845-20348/? E/android.os.Debug: ro.product_ship = true
  12-06 00:12:07.845 2845-20348/? E/android.os.Debug: ro.debug_level = 0x4f4c
  12-06 00:12:07.930 2845-2925/? E/InputDispatcher: channel ~ Channel is unrecoverably broken and will be disposed!
  12-06 00:12:07.930 2845-2925/? E/InputDispatcher: channel ~ Channel is unrecoverably broken and will be disposed!
  12-06 00:12:07.990 20349-20349/? E/Zygote: MountEmulatedStorage()
  12-06 00:12:07.990 20349-20349/? E/Zygote: v2
  12-06 00:12:07.995 20349-20349/? E/Zygote: accessInfo : 0
  12-06 00:12:07.995 20349-20349/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
  12-06 00:12:15.020 2845-2889/? E/ViewRootImpl: sendUserActionEvent() mView == null


问:
mirroring app chromecast
I'm developping an android App and now I would like to add a screen mirroring button which display the same screen on a tv equipped with a chromecast.

I found a way : chromecast remote
but there given sample is in beta, crashing when I click on the button and the development seems to be hard time-consuming (because I don't need to create new view with 'presentation' if I just want to mirror).

A second way should be to launch the google home mirroring service, that just work really well. But I don't find a way to call it from my app..

In short, I have no more clue, if someone have any idea that would be nice.

Thanks for your answer !

答:
This sample works for me. May be you might be missing to add your AppID. Based on setup instructions, you need to have your own AppID. Refer to below setup instructions copied from the example:

Setup Instructions:-

Check out the code from GitHub

Create a new app ID for a Remote Display Receiver using the Google Cast SDK Developer Console: https://cast.google.com/publish/

Add the app ID to the resources strings.xml file

Run the app on your mobile device

Select a Google Cast device as a remote display by clicking on the "Play" button

Please share the error logs if you are unable fix it.

Note: The Remote Display API is compatible with Cast SDK v2 only, not v3.

Title: mirroring app chromecast


问:
calculating frequency for signal in c# .net
I am developing an application for an oscilloscope in c# .NET, I am drawing different kinds of waves (sine, square etc..) with the help of zedgraph control.
I get values from oscilloscope and stored in a buffer of size 1024(byte array) and have to calculate parameters like time period, Frequency, rise time, fall time etc at run time.
for this purpose i have to extract only a single cycle of whole signal.one more problem is that values are not always rise or fall continuously mean values are stored in buffer like this[0,0,0,1,1,2,3,4,5,5,6,6,6,5,5,4,3,2,1,1,0,0,0..........]. signals are continuously receive from machine.
it is not sure that waves are always oscillating around zero.
Thanks
Regards
Nilesh </p>

答:
You can estimate the frequency a number a of ways. Probably the easiest, if you have a math lib, is to compute the FFT and take the lowest frequency.

Alternatively you can check the zero crossings(around the mean value). The faster it oscillates about 0 the higher its frequency. Similarly the extrema tell you a lot about the frequency(think of a sinusoid whose extrema and zeroes alternate and are evenly spaced).

There is also a transform called the period transform but I don't remember it too much. I saw it in a book about music for finding the tempo of a song.

http://www.cs.berkeley.edu/~vazirani/s09quantum/notes/lecture4.pdf

Another way might be to use the auto-correlation and when it is large it means the function is in "sync" with itself(assuming it doesn't change shape to fast). and it should be easy to calculate the distance between these the maximums.

ContentLicense: CC BY-SA 2.5


问:
Raspberry Pi as mosca mqtt broker,Node-Red and MongoDB
I'm working on a school project and I'm a little bit overwhelmed. Is the first time that I work with mqtt service and Node-Red. In the structure of the project I have a Raspberry Pi communicated through gpio with a dht11 sensor, I want to communicate the RPi with my VPS where Node-Red is hosted. Finally this Node-Red working as suscriber in mqtt service has to save the data of measures in a MongoDB database and show the data in a graph. Can someone explain me how to communicate RPi and Node? RPi can work as broker and client in mqtt at the same time? Sorry for my English I'm learning.</p>

答:
MQTT is a client (subscriber/publisher) server (broker) process.

Both the broker (mosca) and the client can run on a computer (RPi, VPS).

Check that the RPi is the best place for the broker. Your VPS (virtual private server) must have a connection to the broker. If the RPi is behind a firewall in your private network, you need to open an inbound port!


问:
grpc & protobuf -- error: no type named 'type' in std::result_of<>
In my program I have a Master class (grpc async client) which distributes work to all the Workers (grpc async servers), and it does this via a class called WorkerClient which handles all communication overhead.

My Master class tries to setup a (detached) background thread to wait for the response from the server, and this is where my difficulty arises.

One strategy I've tried was to make my "AsyncComplete" function part of the WorkerClient class (identical to an approach for a recent program involving async client-server grpc based on the Async-Greeter tutorial on grpc.io), the class details for this approach are below.

```<code>    class WorkerClient {
        public:
        WorkerClient(std::shared_ptr<grpc::Channel> channel);

        void MapReduceWork(masterworker::WorkReq);
        void AsyncComplete(void *, void *, int);

        struct AsyncClientCall {
            masterworker::WorkReply     reply;
            grpc::ClientContext         context;
            grpc::Status                status;
std::unique_ptr<grpc::ClientAsyncResponseReader<masterworker::WorkReply>> rsp_reader;
        };

        std::mutex                                          mtx;
        std::unique_ptr<masterworker::MasterWorker::Stub>   stub;
        grpc::CompletionQueue                               cq;
        masterworker::WorkReq                               work_req;
        ClientState                                         state;
    };

    class Master {
            public:
            Master(const MapReduceSpec&, const std::vector<FileShard>&);
            ......
            private:
            std::mutex                      mtx;
            std::vector<FileShard>          map_tasks;
            std::vector<ReduceTask *>       reduce_tasks;
            std::vector<WorkerClient *>     clients;
            std::vector<std::string>        m_interm_files;

            std::vector<FileShard>          shards;
            MapReduceSpec                   mr_config;
        };
</code>```

Here are the relevant function details

```<code>void WorkerClient::AsyncComplete(void *c, void *m, int client_num)
{
    void            *got_tag = NULL;
    bool            ok = false;
    Master          *mast = static_cast<Master*>(m);
    WorkerClient    *client = static_cast<WorkerClient*>(c);

    cq.Next(&got_tag, &ok);
    if (ok == false) {
        fprintf(stderr, "cq->Next false!\n");
        return;
    }
    ......
}
</code>```

The call to create the thread

```<code>void Master::RunMapJob()
{
        // clients[] is of type WorkerClient
        ptr = new std::thread(&WorkerClient::AsyncComplete,
                static_cast<void*>(clients[i]), static_cast<void*>(this), i);
        ptr->detach();
    ......
}
</code>```

And finally, the problem itself

```<code>g++ -c master.cc -I../external/include -std=c++11 -g
In file included from /usr/include/c++/4.8/mutex:42:0,
                 from master.h:3,
                 from master.cc:2:
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (WorkerClient::*)(void*, void*, int)>(void*, void*, int)>’:
/usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (WorkerClient::*)(void*, void*, int); _Args = {void*, void*, int&}]’
master.cc:223:65:   required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (WorkerClient::*)(void*, void*, int)>(void*, void*, int)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (WorkerClient::*)(void*, void*, int)>(void*, void*, int)>’
         _M_invoke(_Index_tuple<_Indices...>)
         ^
make: *** [master.o] Error 1
</code>```

So far, I have ruled out the obvious things, like not using std::ref to pass variable references to the thread function, and just in general not passing the correct thread function arguments. I have also tried to make AsyncComplete a static stand-alone function, and that didn't work either because the call to cq.Next (changed to WorkerClient->cq.Next()) was throwing a std::bad_alloc exception (not able to figure that one out either as the CompletionQueue code is behind the scenes).

If it helps, I was able to find the /usr/include/c++/4.8/functional line that seems to be choking during compile (below)

```<code>typedef typename result_of<_Callable(_Args...)>::type result_type;
</code>```

Can anyone help me explain both why this is failing to compile, and what a proper fix might look like? I'm new to posting questions on here so feedback is welcome, and I know this is long, but I wanted to make sure I had all the information.

Thanks in advance.

[System details: ubuntu 14.04, protobufs 3.0, grpc built from source for protobufs 3.0]

答:
This line is the problem:

ptr = new std::thread(&WorkerClient::AsyncComplete,
                static_cast<void*>(clients[i]), static_cast<void*>(this), i)

The constructor of std::thread takes a functor and arguments to it. You are supplying &WorkerClient::AsyncComplete without giving an instance of WorkerClient to it. I guess that a client is actually contained in clients[i]. If you try

```<code>ptr = new std::thread(std::bind(&WorkerClient::AsyncComplete, clients[i], static_cast<void*>(clients[i]), static_cast<void*>(this), i))
</code>```

it should compile.

Body:
In my program I have a Master class (grpc async client) which distributes work to all the Workers (grpc async servers), and it does this via a class called WorkerClient which handles all communication overhead.

My Master class tries to setup a (detached) background thread to wait for the response from the server, and this is where my difficulty arises.

One strategy I've tried was to make my "AsyncComplete" function part of the WorkerClient class (identical to an approach for a recent program involving async client-server grpc based on the Async-Greeter tutorial on grpc.io), the class details for this approach are below.

    class WorkerClient {
        public:
        WorkerClient(std::shared_ptr<grpc::Channel> channel);

        void MapReduceWork(masterworker::WorkReq);
        void AsyncComplete(void *, void *, int);

        struct AsyncClientCall {
            masterworker::WorkReply     reply;
            grpc::ClientContext         context;
            grpc::Status                status;
std::unique_ptr<grpc::ClientAsyncResponseReader<masterworker::WorkReply>> rsp_reader;
        };

        std::mutex                                          mtx;
        std::unique_ptr<masterworker::MasterWorker::Stub>   stub;
        grpc::CompletionQueue                               cq;
        masterworker::WorkReq                               work_req;
        ClientState                                         state;
    };

    class Master {
            public:
            Master(const MapReduceSpec&, const std::vector<FileShard>&);
            ......
            private:
            std::mutex                      mtx;
            std::vector<FileShard>          map_tasks;
            std::vector<ReduceTask *>       reduce_tasks;
            std::vector<WorkerClient *>     clients;
            std::vector<std::string>        m_interm_files;

            std::vector<FileShard>          shards;
            MapReduceSpec                   mr_config;
        };

Here are the relevant function details

void WorkerClient::AsyncComplete(void *c, void *m, int client_num)
{
    void            *got_tag = NULL;
    bool            ok = false;
    Master          *mast = static_cast<Master*>(m);
    WorkerClient    *client = static_cast<WorkerClient*>(c);

    cq.Next(&got_tag, &ok);
    if (ok == false) {
        fprintf(stderr, "cq->Next false!\n");
        return;
    }
    ......
}

The call to create the thread

void Master::RunMapJob()
{
        // clients[] is of type WorkerClient
        ptr = new std::thread(&WorkerClient::AsyncComplete,
                static_cast<void*>(clients[i]), static_cast<void*>(this), i);
        ptr->detach();
    ......
}

And finally, the problem itself

g++ -c master.cc -I../external/include -std=c++11 -g
In file included from /usr/include/c++/4.8/mutex:42:0,
                 from master.h:3,
                 from master.cc:2:
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (WorkerClient::*)(void*, void*, int)>(void*, void*, int)>’:
/usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (WorkerClient::*)(void*, void*, int); _Args = {void*, void*, int&}]’
master.cc:223:65:   required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (WorkerClient::*)(void*, void*, int)>(void*, void*, int)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (WorkerClient::*)(void*, void*, int)>(void*, void*, int)>’
         _M_invoke(_Index_tuple<_Indices...>)
         ^
make: *** [master.o] Error 1

So far, I have ruled out the obvious things, like not using std::ref to pass variable references to the thread function, and just in general not passing the correct thread function arguments. I have also tried to make AsyncComplete a static stand-alone function, and that didn't work either because the call to cq.Next (changed to WorkerClient->cq.Next()) was throwing a std::bad_alloc exception (not able to figure that one out either as the CompletionQueue code is behind the scenes).

If it helps, I was able to find the /usr/include/c++/4.8/functional line that seems to be choking during compile (below)

typedef typename result_of<_Callable(_Args...)>::type result_type;

Can anyone help me explain both why this is failing to compile, and what a proper fix might look like? I'm new to posting questions on here so feedback is welcome, and I know this is long, but I wanted to make sure I had all the information.

Thanks in advance.

[System details: ubuntu 14.04, protobufs 3.0, grpc built from source for protobufs 3.0]

Body:
This line is the problem:

ptr = new std::thread(&WorkerClient::AsyncComplete,
                static_cast<void*>(clients[i]), static_cast<void*>(this), i)

The constructor of std::thread takes a functor and arguments to it. You are supplying &WorkerClient::AsyncComplete without giving an instance of WorkerClient to it. I guess that a client is actually contained in clients[i]. If you try

ptr = new std::thread(std::bind(&WorkerClient::AsyncComplete, clients[i], static_cast<void*>(clients[i]), static_cast<void*>(this), i))

it should compile.


问:
guidelines for importing modules in python
I know that there have been a number of questions concerning importing modules in python, but my question seems to be somewhat different.

I'm trying to understand when you have to import a whole module as opposed to when you have to import a specific entry in the module. It seems that only one of the two ways work.

For example if I want to use basename, importing os.path doesn't do the trick.

```<code>>>> import os.path
>>> basename('scripts/cy.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'basename' is not defined
</code>```

Instead I need to import basename from os.path as in

```<code>>>> from os.path import basename
>>> basename('scripts/cy.py')
'cy.py'
</code>```

Going the other way, if I want to use shutil.copyfile, importing copyfile from shutil doesn't work

```<code>>>>
>>> from shutil import copyfile
>>>
>>> shutil.copyfile('emma','newemma')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'shutil' is not defined
</code>```

Instead I must import shutil as in

```<code>>>>
>>> import shutil
>>>
>>> shutil.copyfile('emma','newemma')
'newemma'
>>>
</code>```

The only way I have been able to get this right is through experimentation.
Are there some guidelines to avoid experimentation?

答:
If you import

```<code>import os.path
</code>```

then you have to use full namespace os.path

```<code>os.path.basename()
</code>```

If you import with from

```<code>from shutil import copyfile
</code>```

then you don't have to use full namespace shutil

```<code>copyfile(...)
</code>```

That's all.

If you use as

```<code>import os.path as xxx
</code>```

then you have to use xxx instead of os.path

```<code>xxx.basename()
</code>```

If you use from and as

```<code>from os.path import basename as xxx
</code>```

then you have to use xxx instead of basename

```<code>xxx()
</code>```

Body:
I know that there have been a number of questions concerning importing modules in python, but my question seems to be somewhat different.

I'm trying to understand when you have to import a whole module as opposed to when you have to import a specific entry in the module. It seems that only one of the two ways work.

For example if I want to use basename, importing os.path doesn't do the trick.

>>> import os.path
>>> basename('scripts/cy.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'basename' is not defined

Instead I need to import basename from os.path as in

>>> from os.path import basename
>>> basename('scripts/cy.py')
'cy.py'

Going the other way, if I want to use shutil.copyfile, importing copyfile from shutil doesn't work

>>>
>>> from shutil import copyfile
>>>
>>> shutil.copyfile('emma','newemma')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'shutil' is not defined

Instead I must import shutil as in

>>>
>>> import shutil
>>>
>>> shutil.copyfile('emma','newemma')
'newemma'
>>>

The only way I have been able to get this right is through experimentation.
Are there some guidelines to avoid experimentation?

Body:
If you import

import os.path

then you have to use full namespace os.path

os.path.basename()

If you import with from

from shutil import copyfile

then you don't have to use full namespace shutil

copyfile(...)

That's all.

If you use as

import os.path as xxx

then you have to use xxx instead of os.path

xxx.basename()

If you use from and as

from os.path import basename as xxx

then you have to use xxx instead of basename

xxx()


问:
Why input is scaled in tf.nn.dropout in tensorflow?
I can't understand why dropout works like this in tensorflow. The blog of CS231n says that, "dropout is implemented by only keeping a neuron active with some probability p (a hyperparameter), or setting it to zero otherwise." Also you can see this from picture(Taken from the same site)

From tensorflow site, With probability keep_prob, outputs the input element scaled up by 1 / keep_prob, otherwise outputs 0.

Now, why the input element is scaled up by 1/keep_prob? Why not keep the input element as it is with probability and not scale it with 1/keep_prob?

答:
Let's say the network had n neurons and we applied dropout rate 1/2

Training phase, we would be left with n/2 neurons. So if you were expecting output x with all the neurons, now you will get on x/2. So for every batch, the network weights are trained according to this x/2

Testing/Inference/Validation phase, we dont apply any dropout so the output is x. So, in this case, the output would be with x and not x/2, which would give you the incorrect result. So what you can do is scale it to x/2 during testing.

Rather than the above scaling specific to Testing phase. What Tensorflow's dropout layer does is that whether it is with dropout or without (Training or testing), it scales the output so that the sum is constant.


问:
Adding multiple user inputs into one variable in Bash

I am fairly new to unix bash scripting and need to know if this is possible. I want to ask user for their input multiple times and then store that input in to one variable.

```<code>userinputs=   #nothing at the start

read string
<code to add $string to $userinputs>
read string
<code to add $string to $userinputs> #this should add this input along with the other input
</code>```

so if the user enters "abc" when asked first time, it add's "abc" in $userinputs

then when asked again for the input and the user enters "123" the script should store it in the same $userinputs

this would make the $userinput=abc123

答:
You can concatentate variables and store multiple strings in the same one like so:

```<code>foo=abc
echo $foo # prints 'abc'
bar=123
foo="${foo}${bar}"
echo $foo # prints 'abc123'
</code>```

You can use the other variables, or the same variable, when assigning to a variable, e.g. a="${a}123${b}". See this question for more info.

You don't have to quote the strings you're assigning to, or do the ${var} syntax, but learning when to quote and not to quote is a surprisingly nuanced art, so it's often better to be safe than sorry, and the "${var}" syntax in double quotes is usually the safest approach (see any of these links for more than you ever wanted to know: 1 2 3).

Anyway, you should read into a temporary variable (read, by default, reads into $REPLY) and concatentate that onto your main variable, like so:

```<code>allinput=
read # captures user input into $REPLY
allinput="${REPLY}"
read
allinput="${allinput}${REPLY}"
</code>```

Beware that the read command behaves very differently depending on supplied switches and the value of the IFS global variable, especially in the face of unusual input with special characters. A common "just do what I mean" choice is to empty out IFS via IFS= and use read -r to capture input. See the read builtin documentation for more info.

Body:
I am fairly new to unix bash scripting and need to know if this is possible. I want to ask user for their input multiple times and then store that input in to one variable.

userinputs=   #nothing at the start

read string

read string
 #this should add this input along with the other input

so if the user enters "abc" when asked first time, it add's "abc" in $userinputs

then when asked again for the input and the user enters "123" the script should store it in the same $userinputs

this would make the $userinput=abc123

Body:
You can concatentate variables and store multiple strings in the same one like so:

foo=abc
echo $foo # prints 'abc'
bar=123
foo="${foo}${bar}"
echo $foo # prints 'abc123'

You can use the other variables, or the same variable, when assigning to a variable, e.g. a="${a}123${b}". See this question for more info.

You don't have to quote the strings you're assigning to, or do the ${var} syntax, but learning when to quote and not to quote is a surprisingly nuanced art, so it's often better to be safe than sorry, and the "${var}" syntax in double quotes is usually the safest approach (see any of these links for more than you ever wanted to know: 1 2 3).

Anyway, you should read into a temporary variable (read, by default, reads into $REPLY) and concatentate that onto your main variable, like so:

allinput=
read # captures user input into $REPLY
allinput="${REPLY}"
read
allinput="${allinput}${REPLY}"

Beware that the read command behaves very differently depending on supplied switches and the value of the IFS global variable, especially in the face of unusual input with special characters. A common "just do what I mean" choice is to empty out IFS via IFS= and use read -r to capture input. See the read builtin documentation for more info.


问:
Accessing Data from within angular 2 component
I'm having some trouble trying to figure this out, I'm trying to dynamically add user video data which contains a video URL. I'm trying to access the data from the component so I can interpolate it in my HTML. I'm not exactly sure how this works but Ive tried doing this..

app.component.ts

```<code>import { Component, OnInit } from '@angular/core';

@Component({
   selector: 'app-video',
   templateUrl: './video.component.html',
   styleUrls: ['./video.component.scss'],
   providers: [
      DashboardServiceProxy
   ]
})

export class VideoComponent implements OnInit {
   videos: UserVideoDto[] = [];
   // videos: Array<UserVideoDto> = [];

constructor(
    private _dashboardService: DashboardServiceProxy
) {
    console.log(this.videos.VideoData); //data im trying to access
  }

  ngOnInit() {
    this.getVideos();
  }

  getVideos() {
    this._dashboardService.getAllUserVideos().subscribe((result) => {
    this.videos = result;
    console.log(this.videos);
  });
  }

  }
</code>```

at the moment im just trying to console.log the data but Im getting an error that says [ts] Property 'videoData' does not exist on type 'UserVideoDto[]'

this is the UserVideoDto[] class

```<code>public class UserVideoDto : EntityDto
  {
    public long UserId { get; set; }

    public DateTime CreationTime { get; set; }

    public int TenantId { get; set; }

    public string VideoData { get; set; }

    public string Thumbnail { get; set; }

    public String Name { get; set; }

    public String Series { get; set; }

    public String Subname { get; set; }

    public UserVideoDto()
    { }

  }
</code>```

Any help would be appreciated.

答:
You are trying to access VideoData in array, not instance of UserVideoDto.

It should be something like this.videos[x].VideoData

Body:
I'm having some trouble trying to figure this out, I'm trying to dynamically add user video data which contains a video URL. I'm trying to access the data from the component so I can interpolate it in my HTML. I'm not exactly sure how this works but Ive tried doing this..

app.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
   selector: 'app-video',
   templateUrl: './video.component.html',
   styleUrls: ['./video.component.scss'],
   providers: [
      DashboardServiceProxy
   ]
})

export class VideoComponent implements OnInit {
   videos: UserVideoDto[] = [];
   // videos: Array<UserVideoDto> = [];

constructor(
    private _dashboardService: DashboardServiceProxy
) {
    console.log(this.videos.VideoData); //data im trying to access
  }

  ngOnInit() {
    this.getVideos();
  }

  getVideos() {
    this._dashboardService.getAllUserVideos().subscribe((result) => {
    this.videos = result;
    console.log(this.videos);
  });
  }

  }

at the moment im just trying to console.log the data but Im getting an error that says [ts] Property 'videoData' does not exist on type 'UserVideoDto[]'

this is the UserVideoDto[] class

public class UserVideoDto : EntityDto
  {
    public long UserId { get; set; }

    public DateTime CreationTime { get; set; }

    public int TenantId { get; set; }

    public string VideoData { get; set; }

    public string Thumbnail { get; set; }

    public String Name { get; set; }

    public String Series { get; set; }

    public String Subname { get; set; }

    public UserVideoDto()
    { }

  }

Any help would be appreciated.


问:
Rails Background Jobs running twice
I am using Rufus Scheduler to trigger the background jobs that need to run every 1 hour.

```<code>scheduler = Rufus::Scheduler.singleton

scheduler.every '1h' do
 JobName.perform_now
end
</code>```

I have my Infra setup in AWS and for production, I have 2 Instances running the APP inside an ECS.

What happens is that the Scheduler schedules the jobs twice.

Instance A schedules the job at 00:00:05:01 and Instance B schedules at 00:00:05:05

The jobs are not failing. I am using ActiveJob. I was looking into other solutions like delayed Job but that has the same problem when there are multiple instances.

Can you guys provide an alternate approach to fix this issue? Or a workaround for the same?

答:
https://github.com/jmettraux/rufus-scheduler#lockfile--mylockfiletxt

"This is useful in environments where the Ruby process holding the scheduler gets started multiple times."

Try this:

```<code>scheduler = Rufus::Scheduler.singleton(:lockfile => ".rufus-scheduler.lock")

scheduler.every '1h' do
 JobName.perform_now
end
</code>```

Title: Rails Background Jobs running twice

Body:
I am using Rufus Scheduler to trigger the background jobs that need to run every 1 hour.

scheduler = Rufus::Scheduler.singleton

scheduler.every '1h' do
 JobName.perform_now
end

I have my Infra setup in AWS and for production, I have 2 Instances running the APP inside an ECS.

What happens is that the Scheduler schedules the jobs twice.

Instance A schedules the job at 00:00:05:01 and Instance B schedules at 00:00:05:05

The jobs are not failing. I am using ActiveJob. I was looking into other solutions like delayed Job but that has the same problem when there are multiple instances.

Can you guys provide an alternate approach to fix this issue? Or a workaround for the same?

Body:
https://github.com/jmettraux/rufus-scheduler#lockfile--mylockfiletxt

"This is useful in environments where the Ruby process holding the scheduler gets started multiple times."

Try this:

scheduler = Rufus::Scheduler.singleton(:lockfile => ".rufus-scheduler.lock")

scheduler.every '1h' do
 JobName.perform_now
end


问:
Getting null while trying to get an object propriety inside localStorage
I have this code:

```<code>let cart = [];
let item1 = {
        name: "CD - Animal",
        price: "12",
        qntd: "0"
    };

let item2 = {
    name: "CD - Cannibal",
    price: "10",
    qntd: "0"
};

$("button").click(function() {
    event.preventDefault();
    var li = $(this).parent();
    var quantity = $(li).find('input[type=number]').val();
    eval($(this).val()).qntd = quantity;
    cart.push(eval($(this).val()));
    console.log(item1.qntd);
    localStorage.setItem(cart, JSON.stringify(cart));
    console.log(cart[0].name);
    console.log(JSON.parse((localStorage.getItem(cart[0].name))));
});
</code>```

But cart[0].name does not return the object's name, instead, returns null.

cart[0] returns the object correctly, 0:{name: "CD - Animal", price: "12", qntd: "3"}, but when I try to get cart[0].name, it returns null instead of "CD - Animal".

HTML:

```<code><div class="card-content animal">
    <form style = "display: flex; justify-content: space-between; flex-wrap: wrap;">
        <input type = "number" class = "qntd" placeholder="Quantidade" style = "width: 100%; margin-top: -20px;" maxlength="10">
        <button class="btn waves-effect waves-light" type="submit" name="action" value = "item1">Add
            <i class="material-icons right">attach_money</i>
        </button>
    </form>
</div>
</code>```

答:
One problem here is eval is bad and you are using it and the variables you are referencing are not in global scope and that is where eval is looking. Use a better data structure and do not rely on variables.

```<code>var items = [
        {
            name: "CD - Animal",
            price: "12",
            qntd: "0"
        }, {
        name: "CD - Cannibal",
        price: "10",
        qntd: "0"
    }
]
</code>```

Now you can just reference it with items[0].qntd

or it you want to use a key, switch it to an object instead of an array.

```<code>var items = {
     item1: {
       name: "CD - Animal",
       price: "12",
       qntd: "0"
     },
     item2: {
        name: "CD - Cannibal",
        price: "10",
        qntd: "0"
    }
 }
</code>```

Body:
I have this code:

let cart = [];
let item1 = {
        name: "CD - Animal",
        price: "12",
        qntd: "0"
    };

let item2 = {
    name: "CD - Cannibal",
    price: "10",
    qntd: "0"
};

$("button").click(function() {
    event.preventDefault();
    var li = $(this).parent();
    var quantity = $(li).find('input[type=number]').val();
    eval($(this).val()).qntd = quantity;
    cart.push(eval($(this).val()));
    console.log(item1.qntd);
    localStorage.setItem(cart, JSON.stringify(cart));
    console.log(cart[0].name);
    console.log(JSON.parse((localStorage.getItem(cart[0].name))));
});

But cart[0].name does not return the object's name, instead, returns null.

cart[0] returns the object correctly, 0:{name: "CD - Animal", price: "12", qntd: "3"}, but when I try to get cart[0].name, it returns null instead of "CD - Animal".

HTML:

    <form style = "display: flex; justify-content: space-between; flex-wrap: wrap;">
        <input type = "number" class = "qntd" placeholder="Quantidade" style = "width: 100%; margin-top: -20px;" maxlength="10">
        <button class="btn waves-effect waves-light" type="submit" name="action" value = "item1">Add
            attach_money
        </button>
    </form>

Body:
One problem here is eval is bad and you are using it and the variables you are referencing are not in global scope and that is where eval is looking. Use a better data structure and do not rely on variables.

var items = [
        {
            name: "CD - Animal",
            price: "12",
            qntd: "0"
        }, {
        name: "CD - Cannibal",
        price: "10",
        qntd: "0"
    }
]

Now you can just reference it with items[0].qntd

or it you want to use a key, switch it to an object instead of an array.

var items = {
     item1: {
       name: "CD - Animal",
       price: "12",
       qntd: "0"
     },
     item2: {
        name: "CD - Cannibal",
        price: "10",
        qntd: "0"
    }
 }