问:
sorting the xmlElement by the child value with sort attribute value provided by User

<root>
 <SectionItem>
   <Cell columnid="1" InSeconds="1496761802">06/06/2017  03:10:02 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> abc</Cell>
   <Cell columnid="4">  None</Cell>
   <Cell columnid="5">  1 </Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> efg</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1496743990">06/06/2017  10:13:10 AM</Cell>
   <Cell columnid="2"> Error</Cell>3
   <Cell columnid="3"> o</Cell>
   <Cell columnid="4"> None</Cell>
   <Cell columnid="5"> 1 </Cell>
   <Cell columnid="6">  N/A </Cell>
   <Cell columnid="7"> ice age</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1496227357">31/05/2017  10:42:37 AM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3">  Microsoft-Windows-CAPI2</Cell>
   <Cell columnid="4">  N/A</Cell>
   <Cell columnid="5"> 513</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7">Access is denied.. </Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568786">23/05/2017  07:46:26 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> Microsoft-Windows-Immersive-Shell</Cell>
   <Cell columnid="4">  N/A</Cell>
   <Cell columnid="5">2484</Cell>
   <Cell columnid="6">SR</Cell>
   <Cell columnid="7">hello</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568789">23/05/2017  07:46:29 PM</Cell>
   <Cell columnid="2">Error</Cell>
   <Cell columnid="3"> Application Hang </Cell>
   <Cell columnid="4"> N/A</Cell>
   <Cell columnid="5">1002</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> here is a error</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568740">23/05/2017  07:45:40 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> Application Error</Cell>
   <Cell columnid="4"> Application Crashing Events</Cell>
   <Cell columnid="5">1000</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> error number 3</Cell>
  </SectionItem>
</root>```
</div>
</div>
</p>

<p>If i want to sort the sectionItem element base on Cell element value of the Cell attribute columnID giving by user, how can i approach this? Thank you in advance.</p>

<p>e.g. if user give colunid "1", then we want to sort the sectionItem base on the value of Cell with columnid="1".
if user give colunid "3", then we want to sort the sectionItem base on the value of Cell with columnid="3".</p>

<p>Hope that will make the question easier to understand as i am having difficulty putting the question together.</p>

<p>If i am sorting  with columnid="3"</p>

<p>i should get the the below output:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><root>
 <SectionItem>
   <Cell columnid="1" InSeconds="1496761802">06/06/2017  03:10:02 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> abc</Cell>
   <Cell columnid="4">  None</Cell>
   <Cell columnid="5">  1 </Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> efg</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568740">23/05/2017  07:45:40 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> Application Error</Cell>
   <Cell columnid="4"> Application Crashing Events</Cell>
   <Cell columnid="5">1000</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> error number 3</Cell>
  </SectionItem>
   <SectionItem>
   <Cell columnid="1" InSeconds="1495568789">23/05/2017  07:46:29 PM</Cell>
   <Cell columnid="2">Error</Cell>
   <Cell columnid="3"> Application Hang </Cell>
   <Cell columnid="4"> N/A</Cell>
   <Cell columnid="5">1002</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> here is a error</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1496227357">31/05/2017  10:42:37 AM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3">  Microsoft-Windows-CAPI2</Cell>
   <Cell columnid="4">  N/A</Cell>
   <Cell columnid="5"> 513</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7">Access is denied.. </Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568786">23/05/2017  07:46:26 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> Microsoft-Windows-Immersive-Shell</Cell>
   <Cell columnid="4">  N/A</Cell>
   <Cell columnid="5">2484</Cell>
   <Cell columnid="6">SR</Cell>
   <Cell columnid="7">hello</Cell>
  </SectionItem>
   <SectionItem>
   <Cell columnid="1" InSeconds="1496743990">06/06/2017  10:13:10 AM</Cell>
   <Cell columnid="2"> Error</Cell>3
   <Cell columnid="3"> o</Cell>
   <Cell columnid="4"> None</Cell>
   <Cell columnid="5"> 1 </Cell>
   <Cell columnid="6">  N/A </Cell>
   <Cell columnid="7"> ice age</Cell>
  </SectionItem>
</root></code>```

答:
Below is an example of what I was thinking about when I made my comment.  Note that the heart of this is the following linq statement:

```<code>var cells = xdoc.Element("root")
                .Elements("SectionItem")
                .Elements("Cell")
                .Where(x => x.Attribute("columnid").Value == sortCol)
                .OrderBy(x => ParseCol(sortCol, x));
</code>```

This starts at element "root", enumerates over all it's subelements "SectionItem" and over all their subelements "Cell" selecting the ones that match the sortCol, then sorts the enumeration (based on the types returned from a ParseCol function that provides appropriate type conversion for you XML string data.

I do like jdweng's DataTable approach, particularly if you are going to display this in some form of a gird/list.

```<code>using System;
using System.Linq;
using System.Xml.Linq;

namespace ParseXml {
class Program {
    static void Main(string[] args) {

        var xml = @"
<root>
<SectionItem>
     <Cell columnid='1' InSeconds='1496761802'>06/06/2017  03:10:02 PM</Cell>
     <Cell columnid='2'> Error</Cell>
     <Cell columnid='3'> abc</Cell>
     <Cell columnid='4'>  None</Cell>
     <Cell columnid='5'>  1 </Cell>
     <Cell columnid='6'> N/A</Cell>
     <Cell columnid='7'> efg</Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1496743990'>06/06/2017  10:13:10 AM</Cell>
     <Cell columnid='2'> Error</Cell>3
     <Cell columnid='3'> o</Cell>
     <Cell columnid='4'> None</Cell>
     <Cell columnid='5'> 1 </Cell>
     <Cell columnid='6'>  N/A </Cell>
     <Cell columnid='7'> ice age</Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1496227357'>31/05/2017  10:42:37 AM</Cell>
     <Cell columnid='2'> Error</Cell>
     <Cell columnid='3'>  Microsoft-Windows-CAPI2</Cell>
     <Cell columnid='4'>  N/A</Cell>
     <Cell columnid='5'> 513</Cell>
     <Cell columnid='6'> N/A</Cell>
     <Cell columnid='7'>Access is denied.. </Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1495568786'>23/05/2017  07:46:26 PM</Cell>
     <Cell columnid='2'> Error</Cell>
     <Cell columnid='3'> Microsoft-Windows-Immersive-Shell</Cell>
     <Cell columnid='4'>  N/A</Cell>
     <Cell columnid='5'>2484</Cell>
     <Cell columnid='6'>SR</Cell>
     <Cell columnid='7'>hello</Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1495568789'>23/05/2017  07:46:29 PM</Cell>
     <Cell columnid='2'>Error</Cell>
     <Cell columnid='3'> Application Hang </Cell>
     <Cell columnid='4'> N/A</Cell>
     <Cell columnid='5'>1002</Cell>
     <Cell columnid='6'> N/A</Cell>
     <Cell columnid='7'> here is a error</Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1495568740'>23/05/2017  07:45:40 PM</Cell>
     <Cell columnid='2'> Error</Cell>
     <Cell columnid='3'> Application Error</Cell>
     <Cell columnid='4'> Application Crashing Events</Cell>
     <Cell columnid='5'>1000</Cell>
     <Cell columnid='6'> N/A</Cell>
     <Cell columnid='7'> error number 3</Cell>
 </SectionItem>
</root>";

    var sortCol = "3";
    var xdoc = XDocument.Parse(xml);
    var cells = xdoc.Element("root")
                    .Elements("SectionItem")
                    .Elements("Cell")
                    .Where(x => x.Attribute("columnid").Value == sortCol)
                    .OrderBy(x => ParseCol(sortCol, x));

    var newDoc = new XDocument();
    var root = new XElement("root");
    newDoc.Add(root);
    foreach (var c in cells) {
        root.Add(c.Parent);
        }

    Console.WriteLine(newDoc.ToString(SaveOptions.None));
    }

    static object ParseCol(string col, XElement x) {
        switch (col) {
        case "1":
            return long.Parse(x.Attribute("InSeconds").Value);
        case "2":
        case "3":
        case "4":
            return x.Value.Trim();
        case "5":
            return long.Parse(x.Value);
        case "6":
        case "7":
            return x.Value.Trim();
        default:
            throw new ArgumentException("Bad column id string");
        }
    }
}
</code>```

}

Body:
<root>
 <SectionItem>
   <Cell columnid="1" InSeconds="1496761802">06/06/2017  03:10:02 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> abc</Cell>
   <Cell columnid="4">  None</Cell>
   <Cell columnid="5">  1 </Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> efg</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1496743990">06/06/2017  10:13:10 AM</Cell>
   <Cell columnid="2"> Error</Cell>3
   <Cell columnid="3"> o</Cell>
   <Cell columnid="4"> None</Cell>
   <Cell columnid="5"> 1 </Cell>
   <Cell columnid="6">  N/A </Cell>
   <Cell columnid="7"> ice age</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1496227357">31/05/2017  10:42:37 AM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3">  Microsoft-Windows-CAPI2</Cell>
   <Cell columnid="4">  N/A</Cell>
   <Cell columnid="5"> 513</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7">Access is denied.. </Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568786">23/05/2017  07:46:26 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> Microsoft-Windows-Immersive-Shell</Cell>
   <Cell columnid="4">  N/A</Cell>
   <Cell columnid="5">2484</Cell>
   <Cell columnid="6">SR</Cell>
   <Cell columnid="7">hello</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568789">23/05/2017  07:46:29 PM</Cell>
   <Cell columnid="2">Error</Cell>
   <Cell columnid="3"> Application Hang </Cell>
   <Cell columnid="4"> N/A</Cell>
   <Cell columnid="5">1002</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> here is a error</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568740">23/05/2017  07:45:40 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> Application Error</Cell>
   <Cell columnid="4"> Application Crashing Events</Cell>
   <Cell columnid="5">1000</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> error number 3</Cell>
  </SectionItem>
</root>

If i want to sort the sectionItem element base on Cell element value of the Cell attribute columnID giving by user, how can i approach this? Thank you in advance.

e.g. if user give colunid "1", then we want to sort the sectionItem base on the value of Cell with columnid="1".
if user give colunid "3", then we want to sort the sectionItem base on the value of Cell with columnid="3".

Hope that will make the question easier to understand as i am having difficulty putting the question together.

If i am sorting  with columnid="3"

i should get the the below output:

<root>
 <SectionItem>
   <Cell columnid="1" InSeconds="1496761802">06/06/2017  03:10:02 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> abc</Cell>
   <Cell columnid="4">  None</Cell>
   <Cell columnid="5">  1 </Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> efg</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568740">23/05/2017  07:45:40 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> Application Error</Cell>
   <Cell columnid="4"> Application Crashing Events</Cell>
   <Cell columnid="5">1000</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> error number 3</Cell>
  </SectionItem>
   <SectionItem>
   <Cell columnid="1" InSeconds="1495568789">23/05/2017  07:46:29 PM</Cell>
   <Cell columnid="2">Error</Cell>
   <Cell columnid="3"> Application Hang </Cell>
   <Cell columnid="4"> N/A</Cell>
   <Cell columnid="5">1002</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7"> here is a error</Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1496227357">31/05/2017  10:42:37 AM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3">  Microsoft-Windows-CAPI2</Cell>
   <Cell columnid="4">  N/A</Cell>
   <Cell columnid="5"> 513</Cell>
   <Cell columnid="6"> N/A</Cell>
   <Cell columnid="7">Access is denied.. </Cell>
  </SectionItem>
  <SectionItem>
   <Cell columnid="1" InSeconds="1495568786">23/05/2017  07:46:26 PM</Cell>
   <Cell columnid="2"> Error</Cell>
   <Cell columnid="3"> Microsoft-Windows-Immersive-Shell</Cell>
   <Cell columnid="4">  N/A</Cell>
   <Cell columnid="5">2484</Cell>
   <Cell columnid="6">SR</Cell>
   <Cell columnid="7">hello</Cell>
  </SectionItem>
   <SectionItem>
   <Cell columnid="1" InSeconds="1496743990">06/06/2017  10:13:10 AM</Cell>
   <Cell columnid="2"> Error</Cell>3
   <Cell columnid="3"> o</Cell>
   <Cell columnid="4"> None</Cell>
   <Cell columnid="5"> 1 </Cell>
   <Cell columnid="6">  N/A </Cell>
   <Cell columnid="7"> ice age</Cell>
  </SectionItem>
</root>

Body:
Below is an example of what I was thinking about when I made my comment.  Note that the heart of this is the following linq statement:

var cells = xdoc.Element("root")
                .Elements("SectionItem")
                .Elements("Cell")
                .Where(x => x.Attribute("columnid").Value == sortCol)
                .OrderBy(x => ParseCol(sortCol, x));

This starts at element "root", enumerates over all it's subelements "SectionItem" and over all their subelements "Cell" selecting the ones that match the sortCol, then sorts the enumeration (based on the types returned from a ParseCol function that provides appropriate type conversion for you XML string data.

I do like jdweng's DataTable approach, particularly if you are going to display this in some form of a gird/list.

using System;
using System.Linq;
using System.Xml.Linq;

namespace ParseXml {
class Program {
    static void Main(string[] args) {

        var xml = @"
<root>
<SectionItem>
     <Cell columnid='1' InSeconds='1496761802'>06/06/2017  03:10:02 PM</Cell>
     <Cell columnid='2'> Error</Cell>
     <Cell columnid='3'> abc</Cell>
     <Cell columnid='4'>  None</Cell>
     <Cell columnid='5'>  1 </Cell>
     <Cell columnid='6'> N/A</Cell>
     <Cell columnid='7'> efg</Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1496743990'>06/06/2017  10:13:10 AM</Cell>
     <Cell columnid='2'> Error</Cell>3
     <Cell columnid='3'> o</Cell>
     <Cell columnid='4'> None</Cell>
     <Cell columnid='5'> 1 </Cell>
     <Cell columnid='6'>  N/A </Cell>
     <Cell columnid='7'> ice age</Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1496227357'>31/05/2017  10:42:37 AM</Cell>
     <Cell columnid='2'> Error</Cell>
     <Cell columnid='3'>  Microsoft-Windows-CAPI2</Cell>
     <Cell columnid='4'>  N/A</Cell>
     <Cell columnid='5'> 513</Cell>
     <Cell columnid='6'> N/A</Cell>
     <Cell columnid='7'>Access is denied.. </Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1495568786'>23/05/2017  07:46:26 PM</Cell>
     <Cell columnid='2'> Error</Cell>
     <Cell columnid='3'> Microsoft-Windows-Immersive-Shell</Cell>
     <Cell columnid='4'>  N/A</Cell>
     <Cell columnid='5'>2484</Cell>
     <Cell columnid='6'>SR</Cell>
     <Cell columnid='7'>hello</Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1495568789'>23/05/2017  07:46:29 PM</Cell>
     <Cell columnid='2'>Error</Cell>
     <Cell columnid='3'> Application Hang </Cell>
     <Cell columnid='4'> N/A</Cell>
     <Cell columnid='5'>1002</Cell>
     <Cell columnid='6'> N/A</Cell>
     <Cell columnid='7'> here is a error</Cell>
 </SectionItem>
 <SectionItem>
     <Cell columnid='1' InSeconds='1495568740'>23/05/2017  07:45:40 PM</Cell>
     <Cell columnid='2'> Error</Cell>
     <Cell columnid='3'> Application Error</Cell>
     <Cell columnid='4'> Application Crashing Events</Cell>
     <Cell columnid='5'>1000</Cell>
     <Cell columnid='6'> N/A</Cell>
     <Cell columnid='7'> error number 3</Cell>
 </SectionItem>
</root>";

    var sortCol = "3";
    var xdoc = XDocument.Parse(xml);
    var cells = xdoc.Element("root")
                    .Elements("SectionItem")
                    .Elements("Cell")
                    .Where(x => x.Attribute("columnid").Value == sortCol)
                    .OrderBy(x => ParseCol(sortCol, x));

    var newDoc = new XDocument();
    var root = new XElement("root");
    newDoc.Add(root);
    foreach (var c in cells) {
        root.Add(c.Parent);
        }

    Console.WriteLine(newDoc.ToString(SaveOptions.None));
    }

    static object ParseCol(string col, XElement x) {
        switch (col) {
        case "1":
            return long.Parse(x.Attribute("InSeconds").Value);
        case "2":
        case "3":
        case "4":
            return x.Value.Trim();
        case "5":
            return long.Parse(x.Value);
        case "6":
        case "7":
            return x.Value.Trim();
        default:
            throw new ArgumentException("Bad column id string");
        }
    }
}

}


来源: stackexchange

问:
Transfer Google API keys to another account
I am transferring one of my published application to another Google account(which is possible), but i cant find anywhere how to transfer the API keys associated with old account to new account for application.

As this is old application and use GCM also and had many app users, so I want to keep my existing keys.

Any help please?

答: As stated in this post, just add the person or persons that will be in charge of it as owners of the project in the Developers Console. Once you invite other user as an owner and they accepted the invitation, you can remove yourself from the members then you will have no connection to the project. Here's a related post: How to transfer google cloud project ownership?

ContentLicense: CC BY-SA 3.0


问:
How can I sort the result of array_merge() function?
Here is my code:

```<code><?php

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

print_r(array_merge($arr1, $arr2));

/* Array
   (
       [o] => vote
       [u] => true
       [p] =>
       [v] => digit
   )
</code>```

Always there is one item which has empty value. In example above, that item is p. Now I need to put that item as the last one. How can I do that?

Note: I don't care about the order of other items.

So this is expected result:

```<code>/* Array
   (
       [o] => vote
       [u] => true
       [v] => digit
       [p] =>
   )
</code>```

答:
One simple way I found was to use rsort, which Sort an array in reverse order. Like so (run):

```<code>$merged = array_merge($arr1, $arr2);
rsort($merged);
</code>```

The output:

```<code>Array
(
    [0] => vote
    [1] => true
    [2] => digit
    [3] =>
)
</code>```

You could also go with a simple foreach (example) or even usort (example)

Body:
Here is my code:

<?php

$arr1 = ['o' => 'vote', 'u' => 'true'];
$arr2 = ['p' => '', 'v' => 'digit'];

print_r(array_merge($arr1, $arr2));

/* Array
   (
       [o] => vote
       [u] => true
       [p] =>
       [v] => digit
   )

Always there is one item which has empty value. In example above, that item is p. Now I need to put that item as the last one. How can I do that?

Note: I don't care about the order of other items.

So this is expected result:

/* Array
   (
       [o] => vote
       [u] => true
       [v] => digit
       [p] =>
   )

Body:
One simple way I found was to use rsort, which Sort an array in reverse order. Like so (run):

$merged = array_merge($arr1, $arr2);
rsort($merged);

The output:

Array
(
    [0] => vote
    [1] => true
    [2] => digit
    [3] =>
)

You could also go with a simple foreach (example) or even usort (example)


问:
Method has incompatible type
I have a trait that implements a Java interface

Java interface:

```<code>public interface Scheme extends Serializable {
    List<Object> deserialize(ByteBuffer var1);

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

Scala trait:

```<code>trait JSONScheme extends Scheme {

  type Event <: AnyRef

  override def deserialize(bytes: ByteBuffer): util.List[Event] = {
    val v: Seq[Event] = parseData(bytes)
    v.asJava
  }
}
</code>```

The question is why this does not work, as the Event type is defined to be bounded by AnyRef? This fails with:

```<code>Error:(35, 16) overriding method deserialize in trait Scheme of type (x$1: java.nio.ByteBuffer)java.util.List[Object];
 method deserialize has incompatible type
  override def deserialize(bytes: ByteBuffer): util.List[Event] = {
</code>```

If I rewrite the code to add Event manually to the Java collection, it works fine.

```<code>override def deserialize(bytes: ByteBuffer): util.List[AnyRef] = {
   val v: Seq[Event] = parseData(bytes)
   val vArray = new util.ArrayList[AnyRef]()
   v.map(vArray.add(_))
   vArray
}
</code>```

答:
Java lists are invariant in their element type, so List[Event] isn't a subclass of List[Object], and that makes your method incompatible: it's return type must be a subclass of the return type of the overridden method.

Your second snippet works not because you "add Event manually", but because the method is declared to return List[AnyRef] rather than List[Event].

Title: Method has incompatible type

Body:
I have a trait that implements a Java interface

Java interface:

public interface Scheme extends Serializable {
    List<Object> deserialize(ByteBuffer var1);

    Fields getOutputFields();
}

Scala trait:

trait JSONScheme extends Scheme {

  type Event <: AnyRef

  override def deserialize(bytes: ByteBuffer): util.List[Event] = {
    val v: Seq[Event] = parseData(bytes)
    v.asJava
  }
}

The question is why this does not work, as the Event type is defined to be bounded by AnyRef? This fails with:

Error:(35, 16) overriding method deserialize in trait Scheme of type (x$1: java.nio.ByteBuffer)java.util.List[Object];
 method deserialize has incompatible type
  override def deserialize(bytes: ByteBuffer): util.List[Event] = {

If I rewrite the code to add Event manually to the Java collection, it works fine.

override def deserialize(bytes: ByteBuffer): util.List[AnyRef] = {
   val v: Seq[Event] = parseData(bytes)
   val vArray = new util.ArrayList[AnyRef]()
   v.map(vArray.add(_))
   vArray
}


问:
Place Snackbar at highest z order to avoid from being blocked by AutoCompleteTextView drop down
I have a Snackbar which is as follows:

However, if the drop down of the AutoCompleteTextView is too long, the drop down will block the Snackbar.

As you can see in the above image, the Snackbar is actually showing. However, its visibility is blocked by the long drop down. You can see from the above image

I try to use the following Snackbar code. Adding bringToFront() doesn't help much.

```<code>private void showSnackbar(String message) {
    Snackbar snackbar
            = Snackbar.make(getActivity().findViewById(R.id.content), message, Snackbar.LENGTH_LONG);
    snackbar.getView().bringToFront();
    snackbar.show();
}
</code>```

R.id.content is a CoordinatorLayout:

```<code>    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/content"
        android:background="?attr/MyActivityBackground"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foreground="?attr/headerShadow" />
</code>```

Is there any good way, to avoid Snackbar from being covered by AutoCompleteTextView's drop down?

答:
You can calculate and adjust the height of the popup as an alternative.
In the following picture, I am setting the dropdown height as bellow:

```<code>textView.viewTreeObserver.addOnGlobalLayoutListener {
  textView.dropDownHeight = snackbarView.top - textView.bottom
}
</code>```

This calculation is for the case where the suggestion list's height is long enough. You might want to set that property to WRAP_CONTENT instead.

As far as I know, it is not possible to change the "z-order" unless you add the SnackBar directly to the WindowManager. AutoCompleteTextView internally is using ListPopupWindow to show the suggestions popup and ListPopupWindow has the window type of WindowManager.LayoutParams.TYPE_APPLICATION_PANEL = 1000 which is higher than the Activity's Window type which is of WindowManager.LayoutParams.TYPE_APPLICATION = 2.

Body:
I have a Snackbar which is as follows:

However, if the drop down of the AutoCompleteTextView is too long, the drop down will block the Snackbar.

As you can see in the above image, the Snackbar is actually showing. However, its visibility is blocked by the long drop down. You can see from the above image

I try to use the following Snackbar code. Adding bringToFront() doesn't help much.

private void showSnackbar(String message) {
    Snackbar snackbar
            = Snackbar.make(getActivity().findViewById(R.id.content), message, Snackbar.LENGTH_LONG);
    snackbar.getView().bringToFront();
    snackbar.show();
}

R.id.content is a CoordinatorLayout:

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/content"
        android:background="?attr/MyActivityBackground"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:foreground="?attr/headerShadow" />

Is there any good way, to avoid Snackbar from being covered by AutoCompleteTextView's drop down?

Body:
You can calculate and adjust the height of the popup as an alternative.
In the following picture, I am setting the dropdown height as bellow:

textView.viewTreeObserver.addOnGlobalLayoutListener {
  textView.dropDownHeight = snackbarView.top - textView.bottom
}

This calculation is for the case where the suggestion list's height is long enough. You might want to set that property to WRAP_CONTENT instead.

As far as I know, it is not possible to change the "z-order" unless you add the SnackBar directly to the WindowManager. AutoCompleteTextView internally is using ListPopupWindow to show the suggestions popup and ListPopupWindow has the window type of WindowManager.LayoutParams.TYPE_APPLICATION_PANEL = 1000 which is higher than the Activity's Window type which is of WindowManager.LayoutParams.TYPE_APPLICATION = 2.


问:
Selecting the file with the biggest size in a folder than applying couple of functions in Python
I am interested in finding the files with the biggest size in terms of kbs in a folder and then apply a function. After that, I want to apply a different function to remaining files in the same folder. If I knew which files I was going to use, names and sizes of the files, I would use the following code:

```<code>with open(big_file, 'r') as bigfile:
   bigfile.rotate #predefined function
   minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(bigfile) #predefined function
   w1 = maxx - minx
   l1 = maxy - miny
   h1 = maxz - minz
   copies = copy_obj(bigfile, (w1, l1, h1), 2, 2, 1)
with open(small_file, 'r') as smallfile:
    minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(smallfile)
    w2 = maxx - minx
    l2 = maxy - miny
    h2 = maxz - minz
    translate(smallfile, w1, w1 / 10., 3, 'x')
    copies2 = copy_obj(smallfile, (w2, l2, h2), 2, 2, 1)
    combined = mesh.Mesh(numpy.concatenate([bigfile.data, smallfile.data] +
                                [copy.data for copy in copies] +
                                [copy.data for copy in copies2]))
    combined.save(folder + '.stl', mode=stl.Mode.ASCII)  # save as ASCII
</code>```

How I could apply it to many folders that consist of many files

答:
Just list your files with os.listdir, check for files using os.path.isfile and use os.stat for a more reliable size readout, store them in a list and sort that list:

```<code>import os

target = "."  # let's use the current dir as our target

file_list = sorted((os.stat(os.path.join(target, f)).st_size, os.path.join(target, f))
                    for f in os.listdir(target)
                    if os.path.isfile(os.path.join(target, f)))
</code>```

Now your file_list will contain a list of tuples (file_size, file_path) ordered from smallest to the biggest size in the target directory.

You can then use file_list[-1][1] to get the biggest file, and you can loop through all of the others (file_list[:-1]) to execute something else on them, e.g.:

```<code>function_for_the_biggest_file(file_list[-1][1])

for other_file in file_list[:-1]:
    function_for_other_files(other_file[1])
</code>```

EDIT - It seems that after you execute your functions you want to save them all in one file, so:

```<code>with open(os.path.join(target, "combined.dat"), "w") as outfile:
    for files in file_list:
        with open(files[1], "r") as f:
            outfile.write(f.read())
</code>```

This will concentrate all of the files in combined.dat in the same directory, in order of the smallest to the biggest file. You can use for files in reversed(file_list): if you want to store from the biggest to the smallest file.

Body:
I am interested in finding the files with the biggest size in terms of kbs in a folder and then apply a function. After that, I want to apply a different function to remaining files in the same folder. If I knew which files I was going to use, names and sizes of the files, I would use the following code:

with open(big_file, 'r') as bigfile:
   bigfile.rotate #predefined function
   minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(bigfile) #predefined function
   w1 = maxx - minx
   l1 = maxy - miny
   h1 = maxz - minz
   copies = copy_obj(bigfile, (w1, l1, h1), 2, 2, 1)
with open(small_file, 'r') as smallfile:
    minx, maxx, miny, maxy, minz, maxz = find_mins_maxs(smallfile)
    w2 = maxx - minx
    l2 = maxy - miny
    h2 = maxz - minz
    translate(smallfile, w1, w1 / 10., 3, 'x')
    copies2 = copy_obj(smallfile, (w2, l2, h2), 2, 2, 1)
    combined = mesh.Mesh(numpy.concatenate([bigfile.data, smallfile.data] +
                                [copy.data for copy in copies] +
                                [copy.data for copy in copies2]))
    combined.save(folder + '.stl', mode=stl.Mode.ASCII)  # save as ASCII

How I could apply it to many folders that consist of many files

Body:
Just list your files with os.listdir, check for files using os.path.isfile and use os.stat for a more reliable size readout, store them in a list and sort that list:

import os

target = "."  # let's use the current dir as our target

file_list = sorted((os.stat(os.path.join(target, f)).st_size, os.path.join(target, f))
                    for f in os.listdir(target)
                    if os.path.isfile(os.path.join(target, f)))

Now your file_list will contain a list of tuples (file_size, file_path) ordered from smallest to the biggest size in the target directory.

You can then use file_list[-1][1] to get the biggest file, and you can loop through all of the others (file_list[:-1]) to execute something else on them, e.g.:

function_for_the_biggest_file(file_list[-1][1])

for other_file in file_list[:-1]:
    function_for_other_files(other_file[1])

EDIT - It seems that after you execute your functions you want to save them all in one file, so:

with open(os.path.join(target, "combined.dat"), "w") as outfile:
    for files in file_list:
        with open(files[1], "r") as f:
            outfile.write(f.read())

This will concentrate all of the files in combined.dat in the same directory, in order of the smallest to the biggest file. You can use for files in reversed(file_list): if you want to store from the biggest to the smallest file.


问:
Ellipsis width of the drop down selected item when an item with large name is selected
I am using a third party library for multi select dropdown.
https://github.com/softsimon/angular-2-dropdown-multiselect

I have the following settings

```<code>    selectSettings:IMultiSelectSettings = {
    enableSearch: true,
    checkedStyle: 'fontawesome',
    dynamicTitleMaxItems: 1,
    displayAllSelectedText: false
  };
</code>```

If I select an item from dropdown that has a long name it runs out of the dropdown. I have set a fixed width for the dropdown. So my question is that if its possible to ellipsis the name if the selected name is too long rather than running out of the dropdown box? Please help.

答:
Not sure if this will work with your 3rd party library, but I use a truncate pipe:

```<code>import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {

  transform(value: any, limit: number = 10, trail: string = '...'): string {
      return value.length > limit ? value.substring(0, limit) + trail : value;
  }

}
</code>```

An example of usage:

```<code>{{ name | truncate : 30 : '...' }}
</code>```

This will take the text in the variable name and truncate it to 30 characters and then append a set of ellipses onto the end of the string.

Body:
I am using a third party library for multi select dropdown.
https://github.com/softsimon/angular-2-dropdown-multiselect

I have the following settings

    selectSettings:IMultiSelectSettings = {
    enableSearch: true,
    checkedStyle: 'fontawesome',
    dynamicTitleMaxItems: 1,
    displayAllSelectedText: false
  };

If I select an item from dropdown that has a long name it runs out of the dropdown. I have set a fixed width for the dropdown. So my question is that if its possible to ellipsis the name if the selected name is too long rather than running out of the dropdown box? Please help.

Body:
Not sure if this will work with your 3rd party library, but I use a truncate pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {

  transform(value: any, limit: number = 10, trail: string = '...'): string {
      return value.length > limit ? value.substring(0, limit) + trail : value;
  }

}

An example of usage:

{{ name | truncate : 30 : '...' }}

This will take the text in the variable name and truncate it to 30 characters and then append a set of ellipses onto the end of the string.


问:
composer dump-autoload doesn´t work Laravel 4.2
If I run the composer dump-autoload in command line following happens :

```<code>Generating autoload files
Warning: Ambiguous class resolution, "CreateRevisionsTable" was found in both "$baseDir . '/app/database/migrations/2013_04_09_062329_create_revisions_table.php" and "C:\Users\Username\PhpstormProjects\projectname\www\ve ndor/venturecraft/revisionable/src/migrations\2013_04_09_062329_create_revisions_table.php" the first will be used
</code>```

But then nothing happenes and if i want to go and check out my project in browser he can´t find the Classes.

The autoload_classmap seems to be correct, too but still the error.

I tried to fix it for half a week and don´t seem to get a solution.

Please help.

Edit : Pasted in the file directorys
Additional Note : This error only happens to me. Other people working on this repository( shared via git) are totally fine

I recently upgraded my xampp to the php 7 version but even if i downgrade again it won´t work...

答: Ok i solved it... had to put the short_open_tag=On in my php.ini file... such a dumb little thing..</p>

Body:
If I run the composer dump-autoload in command line following happens :

Generating autoload files
Warning: Ambiguous class resolution, "CreateRevisionsTable" was found in both "$baseDir . '/app/database/migrations/2013_04_09_062329_create_revisions_table.php" and "C:\Users\Username\PhpstormProjects\projectname\www\ve ndor/venturecraft/revisionable/src/migrations\2013_04_09_062329_create_revisions_table.php" the first will be used

But then nothing happenes and if i want to go and check out my project in browser he can´t find the Classes.

The autoload_classmap seems to be correct, too but still the error.

I tried to fix it for half a week and don´t seem to get a solution.

Please help.

Edit : Pasted in the file directorys
Additional Note : This error only happens to me. Other people working on this repository( shared via git) are totally fine

I recently upgraded my xampp to the php 7 version but even if i downgrade again it won´t work...


问:
How do I read (i.e. understand) this Java array?
```<code>String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};
</code>```

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

```<code>int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };
</code>```

答:
Formatting the array will help to figure out that as a matrix of rows and cols

```<code>String[][][] arr  =
{
    {{"a", "b" , "c"}, {"d", "e", null} },
    {{"x"           }, null             },
    {{"y"           }                   },
    {{"z", "p"      }, {                }}
};
</code>```

2 Cols, 4 rows

element at 0,0: {"a", "b" , "c"}

element at 0,1: {"d", "e", null}

element at 1,0: {"x"}

element at 1,1: null

etc etc

Body:
String[][][] arr  =
{{ { "a", "b" , "c"}, { "d", "e", null } },{ {"x"}, null },{{"y"}},{ { "z","p"}, {} }};

I've reason to believe that something like this is going to come up on an exam eventually but in +10 years of coding, I've never seen such a horror. I sure could use some tips for mentally parsing this, so that I can figure out what it really means in my head. Sure, I could run it through IntelliJ but I won't have it available.

For the record, this makes perfect sense to me:

int[][] twoD = { { 1, 2, 3} , { 4, 5, 6, 7}, { 8, 9, 10 } };

Body:
Formatting the array will help to figure out that as a matrix of rows and cols

String[][][] arr  =
{
    {{"a", "b" , "c"}, {"d", "e", null} },
    {{"x"           }, null             },
    {{"y"           }                   },
    {{"z", "p"      }, {                }}
};

2 Cols, 4 rows

element at 0,0: {"a", "b" , "c"}

element at 0,1: {"d", "e", null}

element at 1,0: {"x"}

element at 1,1: null

etc etc


问:
Passing data to nested component with ngFor
I have a parent component (ParentComponent) whose html has several child components (ChildComponent). The number of child components displayed depends on the length of an array using an ngFor. I'm trying to figure out how to set a property on each of the child components in the template.

Here is my ParentComponent html:

```<code>    <div>
        <p-panel header="Parent Component Manager">
            <p-panel header="ChildComponents">
                <childComponent *ngFor="let cComponent of cComponentsArray" [name]="childComponentTitle">
                </childComponent>
            </p-panel>
        </p-panel>
    </div>
</code>```

My ParentComponent.component.ts file contains (I want to stop using this and use string values from cComponentsArray:

```<code>childComponentTitle: string = "This text is passed to child."
</code>```

My ChildComponent html:

```<code><p-accordion [multiple]="true">
    <p-accordionTab header="ChildComponent name: {{name}}">
        <h4>Random text</h4>
        <h4>Random text</h4>
    </p-accordionTab>
</p-accordion>
</code>```

My ChildComponent.component.ts file contains:

```<code>@Input() name: string;
</code>```

With the current code above this will set EACH of the child components "name" property to the same thing. I would like to set it according to a string value contained within cComponent of cComponentsArray.

I've tried using in ParentComponent.html

```<code>[name] = {{cComponent.name}}
</code>```

without any luck. Could someone explain to me what I'm doing wrong and how to properly implement this?

答:
[] and {{}} can never be used together.

Just use

```<code>[name]="cComponent.name"
</code>```

Body:
I have a parent component (ParentComponent) whose html has several child components (ChildComponent). The number of child components displayed depends on the length of an array using an ngFor. I'm trying to figure out how to set a property on each of the child components in the template.

Here is my ParentComponent html:

                <childComponent *ngFor="let cComponent of cComponentsArray" [name]="childComponentTitle">
                </childComponent>

My ParentComponent.component.ts file contains (I want to stop using this and use string values from cComponentsArray:

childComponentTitle: string = "This text is passed to child."

My ChildComponent html:

Random text

Random text

My ChildComponent.component.ts file contains:

@Input() name: string;

With the current code above this will set EACH of the child components "name" property to the same thing. I would like to set it according to a string value contained within cComponent of cComponentsArray.

I've tried using in ParentComponent.html

[name] = {{cComponent.name}}

without any luck. Could someone explain to me what I'm doing wrong and how to properly implement this?

Body:
[] and {{}} can never be used together.

Just use

[name]="cComponent.name"


问:
C# 20,000 records selected from oracle need to be inserted into SQL2005
i have a console app in c# that extracts 20 fields from an oracle DB witht he code below and i wanted an efficient way to insert them into SQL 2005.

i dotn want to insert each one of the 20,000 within the while loop, obviously. i was thinking to change the code to use a data set to cache all the records and then do a bulk insert...

thoughts?

pseudo code would be nice since i am new to oracle.

this is my code where i was testing getting a connection to oracle and seeing if i can view the data... now i can view it i want to get it out and into sql2005... what do i do from here?

```<code>static void getData()
{
    string connectionString = GetConnectionString();
    using (OracleConnection connection = new OracleConnection())
    {
        connection.ConnectionString = connectionString;
        connection.Open();

        OracleCommand command = connection.CreateCommand();
        string sql = "SELECT * FROM BUG";
        command.CommandText = sql;

        OracleDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            //string myField = (string)reader["Project"];
            string myField = reader[0].ToString();
            Console.WriteLine(myField);
        }
    }

}
</code>```

答: You can actually do 100-1000 inserts per sql batch. Just generate multiple inserts, then submit. Pregenerate the next SELECT batch WHILE THE FIRST EXECUTES.</p>

ContentLicense: CC BY-SA 2.5

Body:
i have a console app in c# that extracts 20 fields from an oracle DB witht he code below and i wanted an efficient way to insert them into SQL 2005.

i dotn want to insert each one of the 20,000 within the while loop, obviously. i was thinking to change the code to use a data set to cache all the records and then do a bulk insert...

thoughts?

pseudo code would be nice since i am new to oracle.

this is my code where i was testing getting a connection to oracle and seeing if i can view the data... now i can view it i want to get it out and into sql2005... what do i do from here?

static void getData()
{
    string connectionString = GetConnectionString();
    using (OracleConnection connection = new OracleConnection())
    {
        connection.ConnectionString = connectionString;
        connection.Open();

        OracleCommand command = connection.CreateCommand();
        string sql = "SELECT * FROM BUG";
        command.CommandText = sql;

        OracleDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            //string myField = (string)reader["Project"];
            string myField = reader[0].ToString();
            Console.WriteLine(myField);
        }
    }

}


问:
Will using a parallel stream on a single-core processor be slower than using a sequential stream?
I am applying an operation to every element in a very large LinkedList<LinkedList<Double>>:

```<code>list.stream().map(l -> l.stream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));
</code>```

On my computer (quad-core), parallel streams seem to be faster than using sequential streams:

```<code>list.parallelStream().map(l -> l.parallelStream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));
</code>```

However, not every computer is going to be multi-core. My question is, will using parallel streams on a single-processor computer be noticeably slower than using sequential streams?

答:
I did three benchmarking tests, one testing Holger's suggested optimizations, one using parallel and sequential streams on my quad-core computer (Asus FX550IU-WSFX), without optimizations, and one using parallel and sequential streams on a single core computer (Dell Optiplex 170L), also without optimizations. The lists for every test will contain 1.25 million elements.

Benchmarking code:

```<code>long average = 0;
for(int i = 0; i < 100; i++) {
    long start = System.nanoTime();
    //testing code...
    average += (System.nanoTime() - start);
}

System.out.println((average / 100) / 1000000 + "ms average");
</code>```

Testing Optimizations (on a 4-core processor)

Un-optimized code:

```<code>List<List<Double>> result = list.parallelStream().map(l -> l.parallelStream().filter(d ->
    (Collections.max(l) - d) < 5)
        .collect(Collectors.toCollection(LinkedList::new)))
            .collect(Collectors.toCollection(LinkedList::new));
</code>```

Optimized code:

```<code>List<List<Double>> result =
    list.parallelStream()
        .map(l -> {
                double limit = Collections.max(l)-5;
                return l.parallelStream()
                        .filter(d -> limit < d)
                        .collect(Collectors.toList());
            })
        .collect(Collectors.toList());
</code>```

Times:

Using the un-optimized code, the average execution time was 633ms, while using the optimized code, the average execution time was 25ms.

Testing Un-optimized Code on 4-core Processor

Sequential code:

```<code>List<List<Double>> result = list.stream().map(l -> l.stream().filter(d ->
    (Collections.max(l) - d) < 5)
        .collect(Collectors.toCollection(LinkedList::new)))
            .collect(Collectors.toCollection(LinkedList::new));
</code>```

Parallel code:

```<code>List<List<Double>> result = list.parallelStream().map(l -> l.parallelStream().filter(d ->
        (Collections.max(l) - d) < 5)
            .collect(Collectors.toCollection(LinkedList::new)))
                .collect(Collectors.toCollection(LinkedList::new));
</code>```

Times:

Using the sequential code, the average execution time was 879ms, while using the parallel code yields an average execution time of 539ms.

Testing Un-optimized Code on 1-core Processor

Sequential code:

```<code>List<List<Double>> result = list.stream().map(l -> l.stream().filter(d ->
    (Collections.max(l) - d) < 5)
        .collect(Collectors.toCollection(LinkedList::new)))
            .collect(Collectors.toCollection(LinkedList::new));
</code>```

Parallel code:

```<code>List<List<Double>> result = list.parallelStream().map(l -> l.parallelStream().filter(d ->
        (Collections.max(l) - d) < 5)
            .collect(Collectors.toCollection(LinkedList::new)))
                .collect(Collectors.toCollection(LinkedList::new));
</code>```

Times:

Using the sequential code, the average execution time was 2398ms, while using the parallel code yields an average execution time of 3942ms.

Conclusion

While using parallel streams on a single-core processor, and sequential streams on a four-core processor, does seem to be slower, optimizing the code resulted in the fastest execution times.

Body:
I am applying an operation to every element in a very large LinkedList<LinkedList<Double>>:

list.stream().map(l -> l.stream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));

On my computer (quad-core), parallel streams seem to be faster than using sequential streams:

list.parallelStream().map(l -> l.parallelStream().filter(d ->
(Collections.max(l) - d) < 5)
.collect(Collectors.toCollection(LinkedList::new))).collect(Collectors.toCollection(LinkedList::new));

However, not every computer is going to be multi-core. My question is, will using parallel streams on a single-processor computer be noticeably slower than using sequential streams?

Body:
I did three benchmarking tests, one testing Holger's suggested optimizations, one using parallel and sequential streams on my quad-core computer (Asus FX550IU-WSFX), without optimizations, and one using parallel and sequential streams on a single core computer (Dell Optiplex 170L), also without optimizations. The lists for every test will contain 1.25 million elements.

Benchmarking code:

long average = 0;
for(int i = 0; i < 100; i++) {
    long start = System.nanoTime();
    //testing code...
    average += (System.nanoTime() - start);
}

System.out.println((average / 100) / 1000000 + "ms average");

Testing Optimizations (on a 4-core processor)

Un-optimized code:

List<List<Double>> result = list.parallelStream().map(l -> l.parallelStream().filter(d ->
    (Collections.max(l) - d) < 5)
        .collect(Collectors.toCollection(LinkedList::new)))
            .collect(Collectors.toCollection(LinkedList::new));

Optimized code:

List<List<Double>> result =
    list.parallelStream()
        .map(l -> {
                double limit = Collections.max(l)-5;
                return l.parallelStream()
                        .filter(d -> limit < d)
                        .collect(Collectors.toList());
            })
        .collect(Collectors.toList());

Times:

Using the un-optimized code, the average execution time was 633ms, while using the optimized code, the average execution time was 25ms.

Testing Un-optimized Code on 4-core Processor

Sequential code:

List<List<Double>> result = list.stream().map(l -> l.stream().filter(d ->
    (Collections.max(l) - d) < 5)
        .collect(Collectors.toCollection(LinkedList::new)))
            .collect(Collectors.toCollection(LinkedList::new));

Parallel code:

List<List<Double>> result = list.parallelStream().map(l -> l.parallelStream().filter(d ->
        (Collections.max(l) - d) < 5)
            .collect(Collectors.toCollection(LinkedList::new)))
                .collect(Collectors.toCollection(LinkedList::new));

Times:

Using the sequential code, the average execution time was 879ms, while using the parallel code yields an average execution time of 539ms.

Testing Un-optimized Code on 1-core Processor

Sequential code:

List<List<Double>> result = list.stream().map(l -> l.stream().filter(d ->
    (Collections.max(l) - d) < 5)
        .collect(Collectors.toCollection(LinkedList::new)))
            .collect(Collectors.toCollection(LinkedList::new));

Parallel code:

List<List<Double>> result = list.parallelStream().map(l -> l.parallelStream().filter(d ->
        (Collections.max(l) - d) < 5)
            .collect(Collectors.toCollection(LinkedList::new)))
                .collect(Collectors.toCollection(LinkedList::new));

Times:

Using the sequential code, the average execution time was 2398ms, while using the parallel code yields an average execution time of 3942ms.

Conclusion

While using parallel streams on a single-core processor, and sequential streams on a four-core processor, does seem to be slower, optimizing the code resulted in the fastest execution times.


问:
Perl - escaple new line character using regex in a file from the command line
I have the following CSV file, and need the escape the new line inside the double quote with the character "/"

```<code>101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017
103|abc|this is is another long desc
and it stop here"|2017
</code>```

and the output should looks like below file. How can I use Perl from the command to perform this?

```<code>101|abc|this is desc|2017
102|xyz|"thie is a long desc/
des for xyz continue here."|2017
103|bbb|"this is is another long desc/
and it stop here"|2017
</code>```

答:
Typically you'd do it like s =~ /(?:(?!\A)\G[^"\r\n]*\K|\|"[^"\r\n]*\K)(?<!\/)(\R)/\/$1/g

Since you've shown no effort, you get no explanation.

Body:
I have the following CSV file, and need the escape the new line inside the double quote with the character "/"

101|abc|this is desc|2017
102|xyz|"thie is a long desc
des for xyz continue here."|2017
103|abc|this is is another long desc
and it stop here"|2017

and the output should looks like below file. How can I use Perl from the command to perform this?

101|abc|this is desc|2017
102|xyz|"thie is a long desc/
des for xyz continue here."|2017
103|bbb|"this is is another long desc/
and it stop here"|2017


问:
How to debug "quotes is not defined" error in Chrome Tools?
I keep getting an error in Chrome Tools that "quotes is not defined". I can find the solution. When I click to have Chrome Tools to show me the error it ends up in the Math.floor-Math.random.

Here is my code.

```<code><div class="container-fluid text-center">
<h1>Random quote Generator</h1>

<br>
<button class="btn btn-danger" type="submit">New Quote</button>

<a href="#" id="tweet" class="btn btn-primary">Tweet Out!</a>
<br>
<div class="quotes">
    <span class="quote"></span>
    <span class="author"></span>
</div>

</div>

$(document).ready(function(){

function getQuote(){
var quotes = ["With the new day comes new strength and new thoughts.", "War is
peace. Freedom is slavery. Ignorance is strength.", "The goal of education is
the advancement of knowledge and the dissemination of truth.", "Success is
getting what you want. Happiness is wanting what you get." , "You know an odd
feeling? Sitting on the toilet eating a chocolate candy bar."];
var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale
Carnegie", "George Carlin"];
};

  var randumNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);

  $(".btn").on("click", function(){
  getQuote();
  });

 });
</code>```

答:
Your quotes variable is defined within method getQuotes(), thus is not visible outside. I assume your getQuote function is closed too early, simply move } after setting author.

```<code>$(document).ready(function(){
 function getQuote(){
    var quotes = ["With the new day comes new strength and new thoughts.", "War is
             peace. Freedom is slavery. Ignorance is strength.", "The goal of education is
             the advancement of knowledge and the dissemination of truth.", "Success is
             getting what you want. Happiness is wanting what you get." , "You know an odd
            feeling? Sitting on the toilet eating a chocolate candy bar."];

     var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale
Carnegie", "George Carlin"];

  var randumNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);
 };

 $(".btn").on("click", function(){
   getQuote();
  });
 });
</code>```

Body:
I keep getting an error in Chrome Tools that "quotes is not defined". I can find the solution. When I click to have Chrome Tools to show me the error it ends up in the Math.floor-Math.random.

Here is my code.

Random quote Generator

<button class="btn btn-danger" type="submit">New Quote</button>

Tweet Out!

$(document).ready(function(){

function getQuote(){
var quotes = ["With the new day comes new strength and new thoughts.", "War is
peace. Freedom is slavery. Ignorance is strength.", "The goal of education is
the advancement of knowledge and the dissemination of truth.", "Success is
getting what you want. Happiness is wanting what you get." , "You know an odd
feeling? Sitting on the toilet eating a chocolate candy bar."];
var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale
Carnegie", "George Carlin"];
};

  var randumNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);

  $(".btn").on("click", function(){
  getQuote();
  });

 });

Body:
Your quotes variable is defined within method getQuotes(), thus is not visible outside. I assume your getQuote function is closed too early, simply move } after setting author.

$(document).ready(function(){
 function getQuote(){
    var quotes = ["With the new day comes new strength and new thoughts.", "War is
             peace. Freedom is slavery. Ignorance is strength.", "The goal of education is
             the advancement of knowledge and the dissemination of truth.", "Success is
             getting what you want. Happiness is wanting what you get." , "You know an odd
            feeling? Sitting on the toilet eating a chocolate candy bar."];

     var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale
Carnegie", "George Carlin"];

  var randumNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);
 };

 $(".btn").on("click", function(){
   getQuote();
  });
 });


答:
In Python 3.5 and higher, you can do this:

```<code>import os

direntries = list(os.scandir(PATH))
bigfile = max(direntries, key=lambda x: x.stat().st_size)
</code>```

Now bigfile is a DirEntry object. Then bigfile.name is the filename, and bigfile.path is the full path.

Then you can do

```<code>dostuff(bigfile)
for f in direntries:
    if f is not bigfile:
       otherstuff(f)
</code>```

Or, if you want to skip directories:

```<code>for f in direntries:
    if f.is_file() and f is not bigfile:
       otherstuff(f)
</code>```

Title: Selecting the file with the biggest size in a folder than applying couple of functions in Python

Body:
In Python 3.5 and higher, you can do this:

import os

direntries = list(os.scandir(PATH))
bigfile = max(direntries, key=lambda x: x.stat().st_size)

Now bigfile is a DirEntry object. Then bigfile.name is the filename, and bigfile.path is the full path.

Then you can do

dostuff(bigfile)
for f in direntries:
    if f is not bigfile:
       otherstuff(f)

Or, if you want to skip directories:

for f in direntries:
    if f.is_file() and f is not bigfile:
       otherstuff(f)


问:
Laravel issue No 'Access-Control-Allow-Origin'
I'm writing a very common topic, but I am desperate, wasted two days trying to make this work.

I'm on Chrome, trying to make my first Login/Register app and at the time of sending the data to the backend, i get the following error:

XMLHttpRequest cannot load http://192.168.1.133:8100/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.

I am making a POST request from AngularJS like follows:

```<code>$scope.data = "UserName"; // for example

$scope.register = function() {

      var withAjax = $http.post('http://192.168.1.133/api/register', $scope.data);

      withAjax
        .success(function(answer){
           console.log(answer.message);
      })
        .error(function(answer) {
          console.log("error");
        });
    }
])
</code>```

And the Laravel API backend is simple, just return 'Correct'.

```<code>public function login (Request $request) {

  $inputArray = $request->all();

  return response()->json(["message" => "Login: All Correct"]);
}
</code>```

In my front-end app I alowed all kind connections with:

```<code><allow-navigation href="http://*/*" />
<allow-navigation href="*" />
<access origin="*"/>
</code>```

In PHP I tried all. Disabled CSFR token for API, and installed properly "barryvdh/laravel-cors" and configured cors file like follows:

```<code>return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],  // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [],
];
</code>```

When I can make, sending data back and forth easy process, I will care about protection. Now I decided to open 'all' to make it straightforward.

I'm crazy about this, lost two days just trying to solve this.
Any clue would be of help.

Thank you!

答: Try this plugin for Chrome, might help you. CORS</p>

Body:
I'm writing a very common topic, but I am desperate, wasted two days trying to make this work.

I'm on Chrome, trying to make my first Login/Register app and at the time of sending the data to the backend, i get the following error:

XMLHttpRequest cannot load http://192.168.1.133:8100/api/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500.

I am making a POST request from AngularJS like follows:

$scope.data = "UserName"; // for example

$scope.register = function() {

      var withAjax = $http.post('http://192.168.1.133/api/register', $scope.data);

      withAjax
        .success(function(answer){
           console.log(answer.message);
      })
        .error(function(answer) {
          console.log("error");
        });
    }
])

And the Laravel API backend is simple, just return 'Correct'.

public function login (Request $request) {

  $inputArray = $request->all();

  return response()->json(["message" => "Login: All Correct"]);
}

In my front-end app I alowed all kind connections with:

<allow-navigation href="http://*/*" />
<allow-navigation href="*" />
<access origin="*"/>

In PHP I tried all. Disabled CSFR token for API, and installed properly "barryvdh/laravel-cors" and configured cors file like follows:

return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],  // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [],
];

When I can make, sending data back and forth easy process, I will care about protection. Now I decided to open 'all' to make it straightforward.

I'm crazy about this, lost two days just trying to solve this.
Any clue would be of help.

Thank you!


答:
your getQuote function closes only defining 2 veriables 'quotes' and 'author' outside the funcion youre trying to read its values and thats not possible, so thats why you get th quotes undefined, you need to close your function (};) after this line of code

```<code>$(".author").text(randomAuthor);
</code>```

$(document).ready(function(){
 function getQuote(){
    var quotes = ["With the new day comes new strength and new thoughts.", "War is peace. Freedom is slavery. Ignorance is strength.", "The goal of education is the advancement of knowledge and the dissemination of truth.", "Success is getting what you want. Happiness is wanting what you get." , "You know an odd feeling? Sitting on the toilet eating a chocolate candy bar."];

     var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale Carnegie", "George Carlin"];

  var randomNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);
 };

 $(".btn").on("click", function(){
   getQuote();
  });
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<button class="btn">click me and see</button>

<p class="quotes"></p>
<p><small class="author"></small></p></code>```

EDIT: Heres your snippet up and running just fine with the tweaks we all mention but one and its that you have a variable called 'randumNum and then you try to read the value as 'randomNum' (u and o)

Title: How to debug "quotes is not defined" error in Chrome Tools?

Body:
your getQuote function closes only defining 2 veriables 'quotes' and 'author' outside the funcion youre trying to read its values and thats not possible, so thats why you get th quotes undefined, you need to close your function (};) after this line of code

$(".author").text(randomAuthor);

$(document).ready(function(){
 function getQuote(){
    var quotes = ["With the new day comes new strength and new thoughts.", "War is peace. Freedom is slavery. Ignorance is strength.", "The goal of education is the advancement of knowledge and the dissemination of truth.", "Success is getting what you want. Happiness is wanting what you get." , "You know an odd feeling? Sitting on the toilet eating a chocolate candy bar."];

     var author = ["-Eleanor Roosevelt", "George Orwell", "John F. Kennedy", "Dale Carnegie", "George Carlin"];

  var randomNum = Math.floor((Math.random()*quotes.length));
  var randomQuote = quotes[randomNum];
  var randomAuthor = author[randomNum];

  $(".quotes").text(randomQuote);
  $(".author").text(randomAuthor);
 };

 $(".btn").on("click", function(){
   getQuote();
  });
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<button class="btn">click me and see</button>

<p class="quotes"></p>
<p><small class="author"></small></p>

EDIT: Heres your snippet up and running just fine with the tweaks we all mention but one and its that you have a variable called 'randumNum and then you try to read the value as 'randomNum' (u and o)


问:
ZF3 - composer require module -> module could not be initialised
I am working with the skeleton-application as a base, using the Vagrant / Composer setup. After the initial install I realised I would need the LDAP module. I then ran composer require zendframework/zend-ldap which ran successfully and I have located the files in ~/vendor/zendframework/zend-ldap.

The issue is when I add 'Zend\Ldap' to my ~/config/modules.config.php I encounter the following error:

```<code>Fatal error: Uncaught Zend\ModuleManager\Exception\RuntimeException: Module (Zend\Ldap) could not be initialized. in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php:203 Stack trace: #0 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Zend\\Ldap') #2 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent))
#4 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(120): Zend\EventManager\EventManager->triggerEvent(Object(Zend\ModuleManager\ModuleEvent))
#5 /var/www/vendor/zendfr in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php on line 203
</code>```

The ~/config/modules.config.php file:

```<code>/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Zend\Ldap',    // All is well if this is commented out
    'Application',

];
</code>```

and the ~/config/application.config.php file:

```<code>/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => [
            './module',
            './vendor',
        ],

        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => [
            realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
        ],

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => true,

        // The key used to create the configuration cache file name.
        'config_cache_key' => 'application.config.cache',

        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => true,

        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'application.module.cache',

        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache/',

        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        // 'check_dependencies' => true,
    ],

    // Used to create an own service manager. May contain one or more child arrays.
    // 'service_listener_options' => [
    //     [
    //         'service_manager' => $stringServiceManagerName,
    //         'config_key'      => $stringConfigKey,
    //         'interface'       => $stringOptionalInterface,
    //         'method'          => $stringRequiredMethodName,
    //     ],
    // ],

    // Initial configuration with which to seed the ServiceManager.
    // Should be compatible with Zend\ServiceManager\Config.
    // 'service_manager' => [],
];
</code>```

I have tried removing cache folder, running composer update, restarting Vagrant, adding the full path to the 'modules_path' array in application.config.php but it is always the same error. Interestingly I run into the same issue with 'Zend\View' that was included from the install, but a module such as 'Zend\Session' can be added to the modules.config.php file with no issues (They are all located in the vendor/zendframework directory)

Can anyone point me in the right direction to resolve this issue?

答:
Zend\Ldap is one of the ZF components. As it does not have a Module.php in its /src directory which is mandatory for a module. So you do not need to initialize like other modules through modules.config.php to use it in your application.

This component is not included as required with default installation of ZF. So if you want to use any component, you must add them to autoloader. Once you added a component like this one composer require zendframework/zend-ldap in your project, you would then be able to use it.

Check this answer and this issue to be clear!

Body:
I am working with the skeleton-application as a base, using the Vagrant / Composer setup. After the initial install I realised I would need the LDAP module. I then ran composer require zendframework/zend-ldap which ran successfully and I have located the files in ~/vendor/zendframework/zend-ldap.

The issue is when I add 'Zend\Ldap' to my ~/config/modules.config.php I encounter the following error:

Fatal error: Uncaught Zend\ModuleManager\Exception\RuntimeException: Module (Zend\Ldap) could not be initialized. in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php:203 Stack trace: #0 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(175): Zend\ModuleManager\ModuleManager->loadModuleByName(Object(Zend\ModuleManager\ModuleEvent))
#1 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(97): Zend\ModuleManager\ModuleManager->loadModule('Zend\\Ldap') #2 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(322): Zend\ModuleManager\ModuleManager->onLoadModules(Object(Zend\ModuleManager\ModuleEvent))
#3 /var/www/vendor/zendframework/zend-eventmanager/src/EventManager.php(171): Zend\EventManager\EventManager->triggerListeners(Object(Zend\ModuleManager\ModuleEvent))
#4 /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php(120): Zend\EventManager\EventManager->triggerEvent(Object(Zend\ModuleManager\ModuleEvent))
#5 /var/www/vendor/zendfr in /var/www/vendor/zendframework/zend-modulemanager/src/ModuleManager.php on line 203

The ~/config/modules.config.php file:

/**
 * List of enabled modules for this application.
 *
 * This should be an array of module namespaces used in the application.
 */
return [
    'Zend\Session',
    'Zend\Mvc\Plugin\Prg',
    'Zend\Mvc\Plugin\Identity',
    'Zend\Mvc\Plugin\FlashMessenger',
    'Zend\Mvc\Plugin\FilePrg',
    'Zend\Log',
    'Zend\Form',
    'Zend\Db',
    'Zend\Router',
    'Zend\Validator',
    'Zend\Ldap',    // All is well if this is commented out
    'Application',

];

and the ~/config/application.config.php file:

/**
 * If you need an environment-specific system or application configuration,
 * there is an example in the documentation
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-system-configuration
 * @see https://docs.zendframework.com/tutorials/advanced-config/#environment-specific-application-configuration
 */
return [
    // Retrieve list of modules used in this application.
    'modules' => require __DIR__ . '/modules.config.php',

    // These are various options for the listeners attached to the ModuleManager
    'module_listener_options' => [
        // This should be an array of paths in which modules reside.
        // If a string key is provided, the listener will consider that a module
        // namespace, the value of that key the specific path to that module's
        // Module class.
        'module_paths' => [
            './module',
            './vendor',
        ],

        // An array of paths from which to glob configuration files after
        // modules are loaded. These effectively override configuration
        // provided by modules themselves. Paths may use GLOB_BRACE notation.
        'config_glob_paths' => [
            realpath(__DIR__) . '/autoload/{{,*.}global,{,*.}local}.php',
        ],

        // Whether or not to enable a configuration cache.
        // If enabled, the merged configuration will be cached and used in
        // subsequent requests.
        'config_cache_enabled' => true,

        // The key used to create the configuration cache file name.
        'config_cache_key' => 'application.config.cache',

        // Whether or not to enable a module class map cache.
        // If enabled, creates a module class map cache which will be used
        // by in future requests, to reduce the autoloading process.
        'module_map_cache_enabled' => true,

        // The key used to create the class map cache file name.
        'module_map_cache_key' => 'application.module.cache',

        // The path in which to cache merged configuration.
        'cache_dir' => 'data/cache/',

        // Whether or not to enable modules dependency checking.
        // Enabled by default, prevents usage of modules that depend on other modules
        // that weren't loaded.
        // 'check_dependencies' => true,
    ],

    // Used to create an own service manager. May contain one or more child arrays.
    // 'service_listener_options' => [
    //     [
    //         'service_manager' => $stringServiceManagerName,
    //         'config_key'      => $stringConfigKey,
    //         'interface'       => $stringOptionalInterface,
    //         'method'          => $stringRequiredMethodName,
    //     ],
    // ],

    // Initial configuration with which to seed the ServiceManager.
    // Should be compatible with Zend\ServiceManager\Config.
    // 'service_manager' => [],
];

I have tried removing cache folder, running composer update, restarting Vagrant, adding the full path to the 'modules_path' array in application.config.php but it is always the same error. Interestingly I run into the same issue with 'Zend\View' that was included from the install, but a module such as 'Zend\Session' can be added to the modules.config.php file with no issues (They are all located in the vendor/zendframework directory)

Can anyone point me in the right direction to resolve this issue?


问:
Button overlapping input 100% when hovering
I'm trying to make a button expand fully across an input element. I can't seem to figure it out. I've tried using absolute:position; and that didn't seem to work and I have tried a few other methods that seemed to be more complicated then what I probably needed and did not work for the most part

Here is the code I have at the moment:

  .s-btn {width:40px;height:40px;}

  .expand > span {display:none;}
  .expand:hover > span {display:inline-block;}
  .expand:hover {width:100%;}

  .transition {
    /*Transition*/
    -webkit-transition: All 0.5s ease;
    -moz-transition: All 0.5s ease;
    -o-transition: All 0.5s ease;
    -ms-transition: All 0.5s ease;
    transition: All 0.5s ease;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<div class="w3-container">
  <h2>Help</h2>
  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Test Modal for Help Button</button>

  <div id="id01" class="w3-modal">
    <div class="w3-modal-content">
      <div class="w3-container" style="overflow:hidden;padding:50px 0;">
        <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-hover-red w3-display-topright">×</span>
        <form class="w3-container" style="width:80%;margin:0 auto;">
          <!-- Trouble Area: -->
          <button class="w3-button expand s-btn transition w3-deep-purple"><span>What's my company code</span>?</button>
          <input class="w3-input w3-border" name="message" type="text" placeholder="Company Code">
          <!-- END: -->
          <button class="w3-button w3-block w3-section w3-blue w3-ripple w3-padding">Submit</button>
        </form>
      </div>
    </div>
  </div>
</div></code>```

Here the button expands to 100% like i'm looking for but I want to have it expand on top of the input field.

Below is an example of how I would like it to look but of course implement the full width of the input field.

答:
You can absolutely position the button to the left of the input, and trigger the width change on :hover and it will expand over the input

.s-btn {
  width: 40px;
  height: 40px;
  position: absolute;
}

.s-btn + .w3-input {
  margin-left: 45px;
  width: auto;
  width: calc(100% - 45px);
}

.w3-container {
  position: relative;
}

.expand > span {
  display: none;
}
.expand:hover > span {
  display: inline-block;
}

.expand:hover {
  width: calc(100% - 32px);
  z-index: 1;
}

.transition {
  /*Transition*/
  -webkit-transition: All 0.5s ease;
  -moz-transition: All 0.5s ease;
  -o-transition: All 0.5s ease;
  -ms-transition: All 0.5s ease;
  transition: All 0.5s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<div class="w3-container">
  <h2>Help</h2>
  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Test Modal for Help Button</button>

  <div id="id01" class="w3-modal">
    <div class="w3-modal-content">
      <div class="w3-container" style="overflow:hidden;padding:50px 0;">
        <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-hover-red w3-display-topright">×</span>
        <form class="w3-container" style="width:80%;margin:0 auto;">
          <!-- Trouble Area: -->
          <button class="w3-button expand s-btn transition w3-deep-purple"><span>What's my company code</span>?</button>
          <input class="w3-input w3-border" name="message" type="text" placeholder="Company Code">
          <!-- END: -->
          <button class="w3-button w3-block w3-section w3-blue w3-ripple w3-padding">Submit</button>
        </form>
      </div>
    </div>
  </div>
</div></code>```

Body:
I'm trying to make a button expand fully across an input element. I can't seem to figure it out. I've tried using absolute:position; and that didn't seem to work and I have tried a few other methods that seemed to be more complicated then what I probably needed and did not work for the most part

Here is the code I have at the moment:

  .s-btn {width:40px;height:40px;}

  .expand > span {display:none;}
  .expand:hover > span {display:inline-block;}
  .expand:hover {width:100%;}

  .transition {
    /*Transition*/
    -webkit-transition: All 0.5s ease;
    -moz-transition: All 0.5s ease;
    -o-transition: All 0.5s ease;
    -ms-transition: All 0.5s ease;
    transition: All 0.5s ease;
  }

<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>

Help

  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Test Modal for Help Button</button>

        ×
        <form class="w3-container" style="width:80%;margin:0 auto;">

          <button class="w3-button expand s-btn transition w3-deep-purple">What's my company code?</button>
          <input class="w3-input w3-border" name="message" type="text" placeholder="Company Code">

          <button class="w3-button w3-block w3-section w3-blue w3-ripple w3-padding">Submit</button>
        </form>

Here the button expands to 100% like i'm looking for but I want to have it expand on top of the input field.

Below is an example of how I would like it to look but of course implement the full width of the input field.

Body:
You can absolutely position the button to the left of the input, and trigger the width change on :hover and it will expand over the input

.s-btn {
  width: 40px;
  height: 40px;
  position: absolute;
}

.s-btn + .w3-input {
  margin-left: 45px;
  width: auto;
  width: calc(100% - 45px);
}

.w3-container {
  position: relative;
}

.expand > span {
  display: none;
}
.expand:hover > span {
  display: inline-block;
}

.expand:hover {
  width: calc(100% - 32px);
  z-index: 1;
}

.transition {
  /*Transition*/
  -webkit-transition: All 0.5s ease;
  -moz-transition: All 0.5s ease;
  -o-transition: All 0.5s ease;
  -ms-transition: All 0.5s ease;
  transition: All 0.5s ease;
}

<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<div class="w3-container">
  <h2>Help</h2>
  <button onclick="document.getElementById('id01').style.display='block'" class="w3-button w3-black">Test Modal for Help Button</button>

  <div id="id01" class="w3-modal">
    <div class="w3-modal-content">
      <div class="w3-container" style="overflow:hidden;padding:50px 0;">
        <span onclick="document.getElementById('id01').style.display='none'" class="w3-button w3-hover-red w3-display-topright">&times;</span>
        <form class="w3-container" style="width:80%;margin:0 auto;">
          <!-- Trouble Area: -->
          <button class="w3-button expand s-btn transition w3-deep-purple"><span>What's my company code</span>?</button>
          <input class="w3-input w3-border" name="message" type="text" placeholder="Company Code">
          <!-- END: -->
          <button class="w3-button w3-block w3-section w3-blue w3-ripple w3-padding">Submit</button>
        </form>
      </div>
    </div>
  </div>
</div>


问:
Looping through web pages to webscrape data
I'm trying to loop through Zillow pages and extract data. I know that the URL is being updated with a new page number after each iteration but the data extracted is as if the URL is still on page 1.</p>

```<code>import selenium
from selenium import webdriver
import requests
from bs4 import BeautifulSoup
import pandas as pd

next_page='https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/'

num_data1=pd.DataFrame(columns=['name','number'])

browser=webdriver.Chrome()
browser.get('https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/')

while True:

    page=requests.get(next_page)

    contents=page.content

    soup = BeautifulSoup(contents, 'html.parser')

    number_p=soup.find_all('p', attrs={'class':'ldb-phone-number'},text=True)
    name_p=soup.find_all('p', attrs={'class':'ldb-contact-name'},text=True)

    number_p=pd.DataFrame(number_p,columns=['number'])
    name_p=pd.DataFrame(name_p,columns=['name'])

    num_data=number_p['number'].apply(lambda x: x.text.strip())
    nam_data=name_p['name'].apply(lambda x: x.text.strip())

    number_df=pd.DataFrame(num_data,columns=['number'])
    name_df=pd.DataFrame(nam_data,columns=['name'])

    num_data0=pd.concat([number_df,name_df],axis=1)

    num_data1=num_data1.append(num_data0)

        try:

            button=browser.find_element_by_css_selector('.zsg-pagination>li.zsg-pagination-next>a').click()
            next_page=str(browser.current_url)

        except IndexError:

            break
</code>```

答: why not make your life easier and use the Zillow API instead of scraping?  (do you even have permission to scrape their site?)</p>

Body:
I'm trying to loop through Zillow pages and extract data. I know that the URL is being updated with a new page number after each iteration but the data extracted is as if the URL is still on page 1.

import selenium
from selenium import webdriver
import requests
from bs4 import BeautifulSoup
import pandas as pd

next_page='https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/'

num_data1=pd.DataFrame(columns=['name','number'])

browser=webdriver.Chrome()
browser.get('https://www.zillow.com/romeo-mi-48065/real-estate-agent-reviews/')

while True:

    page=requests.get(next_page)

    contents=page.content

    soup = BeautifulSoup(contents, 'html.parser')

    number_p=soup.find_all('p', attrs={'class':'ldb-phone-number'},text=True)
    name_p=soup.find_all('p', attrs={'class':'ldb-contact-name'},text=True)

    number_p=pd.DataFrame(number_p,columns=['number'])
    name_p=pd.DataFrame(name_p,columns=['name'])

    num_data=number_p['number'].apply(lambda x: x.text.strip())
    nam_data=name_p['name'].apply(lambda x: x.text.strip())

    number_df=pd.DataFrame(num_data,columns=['number'])
    name_df=pd.DataFrame(nam_data,columns=['name'])

    num_data0=pd.concat([number_df,name_df],axis=1)

    num_data1=num_data1.append(num_data0)

        try:

            button=browser.find_element_by_css_selector('.zsg-pagination>li.zsg-pagination-next>a').click()
            next_page=str(browser.current_url)

        except IndexError:

            break


问:
how to reload only navbar in angularjs because I have to change to login to logout anchor in it
How to reload only navbar to change the login anchor to logout with the help of session.

before login it should be like this

after login it should change with help of session

code of navbar

```<code>    <body>
     <?php

    session_start();
    ?>
             <div class="container-fluid" style="margin-left: 0px ">
            <img  src="Images/pro_1.JPG" class="img-responsive" style="width:90%; height:170px;"  />
         </div>

            <nav class="navbar navbar-inverse my-navbar"  style="border-bottom: thin solid red; width:100%;  border-width:5px;">
        <div class="container-fluid" >
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header" ng-app="Demo" ng-hide="myVar">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
        <a class="navbar-brand" href="#/" style="font-size: 15px; font-weight: 900; ">HOME</a>
        <a class="navbar-brand" href="#/search" style="font-size: 15px; font-weight: 900; ">SEARCH DONORS</a>
        </div>
        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"  ng-controller="loginCtrl" >
          <ul class="nav navbar-nav" id="ul1">
            <li style="font-size: 15px; font-weight: 900; "><a href="#/bloodtips">BLOOD TIPS</a>
            </li>
            <li style="font-size: 15px; font-weight: 900; "><a href="#/aboutus">ABOUT US</a>
            </li>
         </ul>
          <ul class="nav navbar-nav navbar-right">

    <!--      <li style="font-size: 15px; font-weight: 900; "><a href="#/login" ng-show="!isUserLoggedIn"><span class="glyphicon glyphicon-log-in"></span> LOGIN</a></li>
          <li style="font-size: 15px; font-weight: 900; "><a href="#/login" ng-show="isUserLoggedIn"><span class="glyphicon glyphicon-log-out"></span> LOGOUT</a></li>-->
          <?php
          if(@$_SESSION['id']!="")
                {?>
                <div class="mainmenu pull-left">
                    <ul class="nav navbar-nav collapse navbar-collapse">
                        <li class="dropdown"><a href="#/dashboard"><?php echo @$_SESSION['id']; ?>
                    <i class="fa fa-angle-down"></i></a>
                <ul role="menu" class="sub-menu">
                <li><a style="background: transparent" href="logout.php">Logout</a></li>
                    </ul>
                    </li>
                </ul>
                </div>

            <?php   }
                    else
                    {   ?>
                 <li style="font-size: 15px; font-weight: 900; " ><a href="#/register"  ><span class="glyphicon glyphicon-user"></span> REGISTER AS DONAR</a></li>
              <li><a href="#/login"><i class="fa fa-lock"></i> Login</a></li>
                    <?php   }   ?>
        </ul>
        </div>
      </div>

    </nav>
  </body>
</code>```

答:
There is no reload of a specific part in AngularJS.

What you have to do is 2 templates; one for logged user and one for not logged.

Your function responsible for authentication will set a variable :
 - as true for authenticated user
 - as false for logout

Within your html; you will have a ng-if="autenticationVariable=== true" test to check that

Body:
How to reload only navbar to change the login anchor to logout with the help of session.

before login it should be like this

after login it should change with help of session

code of navbar

     <?php

    session_start();
    ?>

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
            Toggle navigation

          </button>
        HOME
        SEARCH DONORS

BLOOD TIPS

ABOUT US

          <?php
          if(@$_SESSION['id']!="")
                {?>

<?php echo @$_SESSION['id']; ?>

Logout

            <?php   }
                    else
                    {   ?>

 REGISTER AS DONAR

 Login

                    <?php   }   ?>


问:
WCF client https request
I am trying to send SOAP message to endpoint starting with HTTPS. This is one way SSL, so I should not need certificate to send request.

While using the config from below I get following exception:

```<code>Could not establish secure channel for SSL/TLS with authority 'some.domain.com/endpoint'.
</code>```

I tried many different transport settings, sometimes it asks for username or certification in ClientCredentials, but hey - I should not need them! I could visit the requested endpoint via browser window without any authentication.
Am I missing something in configuration? I feel a little confused right now.

```<code><bindings>
  <basicHttpBinding>
    <binding name="PublisherBinding">
        <security mode="Transport">
        <transport clientCredentialType="None" />
        </security>
    </binding>
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="https://some.domain.com/endpoint"
    binding="basicHttpBinding" bindingConfiguration="PublisherBinding"
    contract="PublisherContract" name="NotificationsEndpoint"/>
</client>
</code>```

答: unfortunately wcf test client does not support invalid certificates. you can make it work like this Is it possible to force the WCF test client to accept a self-signed certificate? or you can use wcfstorm. second solution is better.</p>

Title: WCF client https request

Body:
I am trying to send SOAP message to endpoint starting with HTTPS. This is one way SSL, so I should not need certificate to send request.

While using the config from below I get following exception:

Could not establish secure channel for SSL/TLS with authority 'some.domain.com/endpoint'.

I tried many different transport settings, sometimes it asks for username or certification in ClientCredentials, but hey - I should not need them! I could visit the requested endpoint via browser window without any authentication.
Am I missing something in configuration? I feel a little confused right now.

<bindings>
  <basicHttpBinding>
    <binding name="PublisherBinding">
        <security mode="Transport">
        <transport clientCredentialType="None" />
        </security>
    </binding>
  </basicHttpBinding>
</bindings>
<client>
  <endpoint address="https://some.domain.com/endpoint"
    binding="basicHttpBinding" bindingConfiguration="PublisherBinding"
    contract="PublisherContract" name="NotificationsEndpoint"/>
</client>


问:
imageview animated gif show only static
i have this code that show banner in view but only show static image even its an animsted gif, how to make this work on animated gif.

java code

```<code>  ImageLoader.getInstance().displayImage(ConstValue.CONTENTS_IMAGE+"big/"+companyMap.get("banner"), imgthumb, options, animateFirstListener);
</code>```

xml code

```<code>            <ImageView
                android:id="@+id/img_thumb"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitCenter"
                android:src="@drawable/thumb_bg" />
</code>```

答:
you can use Glide to show gif animations in ImageView. usage:</p>

```<code>Glide.with(context).load(YOUR_IMAGE_URL).asGif().crossFade().into(YOUR_IMAGE_VIEW);
</code>```

Title: imageview animated gif show only static

Body:
i have this code that show banner in view but only show static image even its an animsted gif, how to make this work on animated gif.

java code

  ImageLoader.getInstance().displayImage(ConstValue.CONTENTS_IMAGE+"big/"+companyMap.get("banner"), imgthumb, options, animateFirstListener);

xml code

            <ImageView
                android:id="@+id/img_thumb"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitCenter"
                android:src="@drawable/thumb_bg" />

Body:
you can use Glide to show gif animations in ImageView. usage:

Glide.with(context).load(YOUR_IMAGE_URL).asGif().crossFade().into(YOUR_IMAGE_VIEW);


问:
jsonschema ref as direct parent schema fields
I have two json schemas:

```<code>//person schema
{
  "id": "/person",
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "baseFields": {"$ref": "/baseFields"}
  },
  "additionalProperties": false
}

//baseFields schema
{
  "id": "/baseFields",
  "type": "object",
  "properties": {
    "age": {"type": "string"},
    "hobby": {"type": "string"}
  },
  "additionalProperties": false
}
</code>```

below object will pass 'person scema' validation:

```<code>{
    "name":"person1",
    "baseFields":{
    "age":"33",
    "hobby":"diving"
    }
}
</code>```

what I need is that below object to pass 'person scema' validation:

```<code>{
    "name":"person1",
    "age":"33",
    "hobby":"diving"
}
</code>```

I need it because I have few fields that are relevant to few different schemas

Thank you

答:
What you are trying to do is inheritance. But there is no inheritance in JSON schema.

You could use the "allOf" keyword. But it has some gotchas. See here for an example and more info (check the 3rd example that has "street_address, city and state" fields).

Also check this answer in so.

Body:
I have two json schemas:

//person schema
{
  "id": "/person",
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "baseFields": {"$ref": "/baseFields"}
  },
  "additionalProperties": false
}

//baseFields schema
{
  "id": "/baseFields",
  "type": "object",
  "properties": {
    "age": {"type": "string"},
    "hobby": {"type": "string"}
  },
  "additionalProperties": false
}

below object will pass 'person scema' validation:

{
    "name":"person1",
    "baseFields":{
    "age":"33",
    "hobby":"diving"
    }
}

what I need is that below object to pass 'person scema' validation:

{
    "name":"person1",
    "age":"33",
    "hobby":"diving"
}

I need it because I have few fields that are relevant to few different schemas

Thank you