问:
The compiler is unhappy about my generics in Java
It always complains with:

```<code>The method add(Matrix<T>) in the type List<Matrix<T>> is not applicable for the arguments (Matrix<String>)
</code>```

In the line of the Extractor class:

```<code>matrixList.add(new Matrix<String>(attributes));
</code>```

It seems there is a problem in defining my generics in these 3 classes. Is there an easy way to fix that? Tried different ways and can't figure it out.

```<code>public class Test {

    public static void main(String[] args) {

        Extractor<String> extractor = new Extractor<>();
        extractor.extract();
    }
}

class Extractor<T> {

    private List<Matrix<T>> matrixList;

    public Extractor() {
        this.matrixList = new ArrayList<>();
    }

    public void extract() {
        List<Attribute<String>> attributes = new ArrayList<>();

        attributes.add(new Attribute<String>("Test 1"));
        attributes.add(new Attribute<String>("Test 2"));

       // !!!! The compiler is complaining here!
        matrixList.add(new Matrix<String>(attributes));
    }

    public List<Matrix<T>> getList() {
        return matrixList;
    }
}

class Matrix<T> {

    private List<Attribute<T>> attributes;

    public Matrix(List<Attribute<T>> attributes) {
        this.attributes = attributes;
    }

    public List<Attribute<T>> getAttributes() {
        return attributes;
    }
}

class Attribute<T> {
    private T attribute;
    public Attribute(T attr) {
        attribute = attr;
    }

    public T getAttr() {
        return attribute;
    }
}
</code>```

答: You can't put Matrix<String> to list of  Matrix<T> (T may be any type here). If the Extractor works only with Matrix of type String, remove the type argument from there and set matrixList type to  List<Matrix<String>>.

Body:
It always complains with:

The method add(Matrix<T>) in the type List<Matrix<T>> is not applicable for the arguments (Matrix<String>)

In the line of the Extractor class:

matrixList.add(new Matrix<String>(attributes));

It seems there is a problem in defining my generics in these 3 classes. Is there an easy way to fix that? Tried different ways and can't figure it out.

public class Test {

    public static void main(String[] args) {

        Extractor<String> extractor = new Extractor<>();
        extractor.extract();
    }
}

class Extractor<T> {

    private List<Matrix<T>> matrixList;

    public Extractor() {
        this.matrixList = new ArrayList<>();
    }

    public void extract() {
        List<Attribute<String>> attributes = new ArrayList<>();

        attributes.add(new Attribute<String>("Test 1"));
        attributes.add(new Attribute<String>("Test 2"));

       // !!!! The compiler is complaining here!
        matrixList.add(new Matrix<String>(attributes));
    }

    public List<Matrix<T>> getList() {
        return matrixList;
    }
}

class Matrix<T> {

    private List<Attribute<T>> attributes;

    public Matrix(List<Attribute<T>> attributes) {
        this.attributes = attributes;
    }

    public List<Attribute<T>> getAttributes() {
        return attributes;
    }
}

class Attribute<T> {
    private T attribute;
    public Attribute(T attr) {
        attribute = attr;
    }

    public T getAttr() {
        return attribute;
    }
}


来源: stackexchange

问:
Using OrientDB 3.0.0m1 java API with TinkerPop 3
I am attempting to issue Tinker Pop 3 [Orient-DB 3.0 snapshot] requests via the Java API.  I am using OCommandGremlin as follows [should match 2 Vs]:
>

```<code>OGremlinHelper.global().create();
OCommandRequest req  = graph.command(new OCommandGremlin("g.V().has('name', 'fast').both()"));
Iterable<Vertex> result2 = req.execute();
</code>```

....

It seems to be looking for TinkerPop 2.x class com.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine

I get the following error:

```<code>WARNING: $ANSI{green {db=demodb}} GREMLIN language not available (not in classpath)
Exception in thread "main" java.lang.NoClassDefFoundError: com/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngine
    at com.orientechnologies.orient.graph.gremlin.OGremlinEngineThreadLocal.get(OGremlinEngineThreadLocal.java:61)
    at com.orientechnologies.orient.graph.gremlin.OGremlinHelper.getGremlinEngine(OGremlinHelper.java:165)
    at com.orientechnologies.orient.graph.gremlin.OGremlinHelper.execute(OGremlinHelper.java:83)
    at com.orientechnologies.orient.graph.gremlin.OGremlinHelper.execute(OGremlinHelper.java:75)
    at com.orientechnologies.orient.graph.gremlin.OCommandGremlinExecutor.execute(OCommandGremlinExecutor.java:59)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.executeCommand(OAbstractPaginatedStorage.java:2480)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.command(OAbstractPaginatedStorage.java:2425)
    at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:68)
    at com.tinkerpop.blueprints.impls.orient.OrientGraphCommand.execute(OrientGraphCommand.java:49)
    at BasicGremlinDriver.main(BasicGremlinDriver.java:202)
Caused by: java.lang.ClassNotFoundException: com.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
</code>```

My maven file is as follows:

```<code><dependencies>
    <dependency>
        <groupId>com.orientechnologies</groupId>
        <artifactId>orientdb-graphdb</artifactId>
        <version>3.0.0m1</version>
    </dependency>
    <dependency>
        <groupId>com.orientechnologies</groupId>
        <artifactId>orientdb-spatial</artifactId>
        <version>3.0.0m1</version>
    </dependency>
    <dependency>
        <groupId>com.orientechnologies</groupId>
        <artifactId>orientdb-lucene</artifactId>
        <version>3.0.0m1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tinkerpop</groupId>
        <artifactId>gremlin-core</artifactId>
        <version>3.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tinkerpop</groupId>
        <artifactId>tinkergraph-gremlin</artifactId>
        <version>3.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tinkerpop</groupId>
        <artifactId>gremlin-groovy</artifactId>
        <version>3.2.4</version>
    </dependency>
</code>```

....

I also set $/META-INF/services/javax.script.ScriptEngineFactory to org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineFactory which is the Tinker Pop 3 version and I can find it on my class path.

Feedback appreciated.

Thanks

JGZ

答:
Try this:

```<code><dependency>
    <groupId>com.tinkerpop.gremlin</groupId>
    <artifactId>gremlin-groovy</artifactId>
    <version>2.6.0</version>
</dependency>
</code>```

Hope it helps.

Regards

ContentLicense: CC BY-SA 3.0

Body:
I am attempting to issue Tinker Pop 3 [Orient-DB 3.0 snapshot] requests via the Java API.  I am using OCommandGremlin as follows [should match 2 Vs]:
>

OGremlinHelper.global().create();
OCommandRequest req  = graph.command(new OCommandGremlin("g.V().has('name', 'fast').both()"));
Iterable<Vertex> result2 = req.execute();

....

It seems to be looking for TinkerPop 2.x class com.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine

I get the following error:

WARNING: $ANSI{green {db=demodb}} GREMLIN language not available (not in classpath)
Exception in thread "main" java.lang.NoClassDefFoundError: com/tinkerpop/gremlin/groovy/jsr223/GremlinGroovyScriptEngine
    at com.orientechnologies.orient.graph.gremlin.OGremlinEngineThreadLocal.get(OGremlinEngineThreadLocal.java:61)
    at com.orientechnologies.orient.graph.gremlin.OGremlinHelper.getGremlinEngine(OGremlinHelper.java:165)
    at com.orientechnologies.orient.graph.gremlin.OGremlinHelper.execute(OGremlinHelper.java:83)
    at com.orientechnologies.orient.graph.gremlin.OGremlinHelper.execute(OGremlinHelper.java:75)
    at com.orientechnologies.orient.graph.gremlin.OCommandGremlinExecutor.execute(OCommandGremlinExecutor.java:59)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.executeCommand(OAbstractPaginatedStorage.java:2480)
    at com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage.command(OAbstractPaginatedStorage.java:2425)
    at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:68)
    at com.tinkerpop.blueprints.impls.orient.OrientGraphCommand.execute(OrientGraphCommand.java:49)
    at BasicGremlinDriver.main(BasicGremlinDriver.java:202)
Caused by: java.lang.ClassNotFoundException: com.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

My maven file is as follows:

<dependencies>
    <dependency>
        <groupId>com.orientechnologies</groupId>
        <artifactId>orientdb-graphdb</artifactId>
        <version>3.0.0m1</version>
    </dependency>
    <dependency>
        <groupId>com.orientechnologies</groupId>
        <artifactId>orientdb-spatial</artifactId>
        <version>3.0.0m1</version>
    </dependency>
    <dependency>
        <groupId>com.orientechnologies</groupId>
        <artifactId>orientdb-lucene</artifactId>
        <version>3.0.0m1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tinkerpop</groupId>
        <artifactId>gremlin-core</artifactId>
        <version>3.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tinkerpop</groupId>
        <artifactId>tinkergraph-gremlin</artifactId>
        <version>3.2.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.tinkerpop</groupId>
        <artifactId>gremlin-groovy</artifactId>
        <version>3.2.4</version>
    </dependency>

....

I also set $/META-INF/services/javax.script.ScriptEngineFactory to org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineFactory which is the Tinker Pop 3 version and I can find it on my class path.

Feedback appreciated.

Thanks

JGZ

Body:
Try this:

<dependency>
    <groupId>com.tinkerpop.gremlin</groupId>
    <artifactId>gremlin-groovy</artifactId>
    <version>2.6.0</version>
</dependency>

Hope it helps.

Regards


问:
I want to make the text below the CSS shape be on top
I already tried z-index. I think it has something to do with the pseudo classes, but I don't know what it is, exactly... I'm a newbie so I can only do HTML and CSS for now, I don't know any JS. Thank you! :)

.h1bcg {
  margin-top: 180px;
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 200px;
  width: 666px;
}

.h1bcg:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, 6deg);
  -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

.h1bcg:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, -6deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <div class="h1bcg:before h1bcg:after ">
         <h1 class="text-center h1bcg"> Lorem              ipsum dolor sit amet. </h1>
      </div></code>```

答:
Pseudo classes and z-index is correct.

Position the pseudo-classes below the element by giving it a negative z-index.

Also note: Pseudo classes (the :before and :after styling rules) are applied to the element containing the original class (.h1bcg) appropriately.  You don't have to specify these classes in your HTML for them to take effect.

.h1bcg {
  margin-top: 180px;
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 200px;
  width: 666px;
}

.h1bcg:before {
  content: '';
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, 6deg);
  -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

.h1bcg:after {
  content: '';
  position: absolute;
  z-index: -1;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, -6deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <h1 class="text-center h1bcg"> Lorem              ipsum dolor sit amet. </h1>
</div></code>```

Body:
I already tried z-index. I think it has something to do with the pseudo classes, but I don't know what it is, exactly... I'm a newbie so I can only do HTML and CSS for now, I don't know any JS. Thank you! :)

.h1bcg {
  margin-top: 180px;
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 200px;
  width: 666px;
}

.h1bcg:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, 6deg);
  -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

.h1bcg:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, -6deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

 Lorem              ipsum dolor sit amet.

Body:
Pseudo classes and z-index is correct.

Position the pseudo-classes below the element by giving it a negative z-index.

Also note: Pseudo classes (the :before and :after styling rules) are applied to the element containing the original class (.h1bcg) appropriately.  You don't have to specify these classes in your HTML for them to take effect.

.h1bcg {
  margin-top: 180px;
  position: relative;
  text-align: center;
  padding: 12px;
  margin-bottom: 6px;
  height: 200px;
  width: 666px;
}

.h1bcg:before {
  content: '';
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  height: 100%;
  width: 51%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, 6deg);
  -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

.h1bcg:after {
  content: '';
  position: absolute;
  z-index: -1;
  top: 0;
  right: 0;
  height: 100%;
  width: 50%;
  background: rgba(88, 255, 171, 0.7);
  -webkit-transform: skew(0deg, -6deg);
  -moz-transform: skew(0deg, -6deg);
  -ms-transform: skew(0deg, -6deg);
  -o-transform: skew(0deg, -6deg);
  transform: skew(0deg, -6deg);
  box-shadow:  0.1rem 0.6rem 9px  rgba(0, 0, 0, 0.4);
}

<div>
  <h1 class="text-center h1bcg"> Lorem              ipsum dolor sit amet. </h1>
</div>


问:
catching button clicks in javascript without server interaction
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.

Currently my JavaScript code for this is as follows:

```<code>    function toggleShowPassword() {
        var button = $get('PASSWORD_TEXTBOX_ID');
        var password;
        if (button)
        {
            password = button.value;
            alert(password);
            button.value = password;
        }
   }
</code>```

The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.

My questions are:

Why does the password field keep getting reset with each button click?

How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?

答: It sounds that you're doing a request to the server on each click, the password box being reset in each page load is typical behavior of the browsers.</p>

OwnerDisplayName: eviljack

Body:
I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.

Currently my JavaScript code for this is as follows:

    function toggleShowPassword() {
        var button = $get('PASSWORD_TEXTBOX_ID');
        var password;
        if (button)
        {
            password = button.value;
            alert(password);
            button.value = password;
        }
   }

The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.

My questions are:

Why does the password field keep getting reset with each button click?

How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?

OwnerDisplayName: jeds

ContentLicense: CC BY-SA 2.5


问:
SQL to find why PK canidate has duplicates on unkeyed table
If my title hurts your head... I'm with you. I don't want to get into why this table exists except that it is part of a legacy system, also the system does "record level access"(RLA) and this I know will be an issue for many tables, anyways the RLA is mentioned because adding a column will change the table format and then many very old programs will no longer work...

Apparently adding a PK has been shown not to change the table format. So I've been told that a certain set of keys is guarantied to be unique, well what do you know... it isn't. And now I need to show where they aren't.

All I can think of is:

Get the cross product where the table matches on it's primary key.

Somehow get a count column onto the result set for the number of entries where the PK matches it self.

Filter that result set for values where count id greater than 2.

I'm going to see if I expand the PK sufficiently I'll actually find something unique.

答:
Remove the constraints / unique indexes, insert the data, and then run this query:

```<code>SELECT col1, col2, ..., coln, COUNT(*)
FROM your_table
GROUP BY col1, col2, ..., coln
HAVING COUNT(*) > 1
</code>```

where col1, col2, ..., coln is the list of columns in your key (one or more columns). The result will be the list of keys that occur more than once together with a count showing how often they occur.

Body:
Remove the constraints / unique indexes, insert the data, and then run this query:

SELECT col1, col2, ..., coln, COUNT(*)
FROM your_table
GROUP BY col1, col2, ..., coln
HAVING COUNT(*) > 1

where col1, col2, ..., coln is the list of columns in your key (one or more columns). The result will be the list of keys that occur more than once together with a count showing how often they occur.


问:
How to stop an asynchronous PowerShell scriptblock?
I'm trying to have a Powershell script start a looping asynchronous script block and then do some "other stuff".  When the "other stuff" is complete at some unknown later time, I want to stop/kill the script block.

I see the MS dev network info on the stopasych() method, but can't figure out how to apply it in Powershell.

A simple example:

```<code>$runspace = [runspacefactory]::CreateRunspace()
$ps = [powershell]::create()
$ps.runspace = $runspace

[void]$ps.addscript({
   $beep = "`a"
   for ($i = 1; $i -lt 5000; $i++) {
      $beep
      Start-Sleep -Seconds 10
   }
})
$runspace.open()
$asyncObject = $ps.beginInvoke()

Copy-Item "c:\bigdata" "\\server\share"
</code>```

That gets me started, but when the copying is done, I want to kill the beeping.  I can't reverse these (i.e. do the "copying" in the background) because there ends up with a delay until the condition, $ps.InvocationStateInfo.state is checked again.

Can anyone help?  BTW, I'd like to stick to PoSh v2.

答:
Just like Invoke() has an asynchronous Begin/End pair, so does Stop().

You can wrap them like this to stop invocation:

```<code>$ps.EndStop($ps.BeginStop($null,$asyncObject))
</code>```

Body:
I'm trying to have a Powershell script start a looping asynchronous script block and then do some "other stuff".  When the "other stuff" is complete at some unknown later time, I want to stop/kill the script block.

I see the MS dev network info on the stopasych() method, but can't figure out how to apply it in Powershell.

A simple example:

$runspace = [runspacefactory]::CreateRunspace()
$ps = [powershell]::create()
$ps.runspace = $runspace

[void]$ps.addscript({
   $beep = "`a"
   for ($i = 1; $i -lt 5000; $i++) {
      $beep
      Start-Sleep -Seconds 10
   }
})
$runspace.open()
$asyncObject = $ps.beginInvoke()

Copy-Item "c:\bigdata" "\\server\share"

That gets me started, but when the copying is done, I want to kill the beeping.  I can't reverse these (i.e. do the "copying" in the background) because there ends up with a delay until the condition, $ps.InvocationStateInfo.state is checked again.

Can anyone help?  BTW, I'd like to stick to PoSh v2.

Body:
Just like Invoke() has an asynchronous Begin/End pair, so does Stop().

You can wrap them like this to stop invocation:

$ps.EndStop($ps.BeginStop($null,$asyncObject))


问:
Eliminate Duplicate form entry linked to query result
I am new to VBA and Access and I have a query on a table which gives me only the active patients from my table as a result. The attached form allows my users to enter data into the table perfectly.

One of the fields for data entry on my form is the room number, which is not a unique field as far as the data in my table. However, on the query, this must be unique because there can not be two patients assigned to one room.

Is there a way to prevent users from assigning two active patients with the same room number using my query result? I have looked everywhere for an answer and the closest thing I have found was using DlookUp but I am unsure how this might work.

Thanks in advance.

答:
Thanks Wayne for your answer, I made the compound key but noticed the user would have to add lots of information into the form and hit enter only to see no patient added to the list. That didn't really get me what I was after but it sent me looking in the right direction...

I finally came up with a code to find the room numbers entered into the form by using Dcount on the query result and placed this code in the onExit event of the room number so I would be able to send the focus back to the field until the correct answer is submitted by the user.

I already had the field validation set to ensure the correct range of room numbers would be entered. This now has the potential of getting the user stuck in an endless loop. So, I will have to add another if statement to the error msg to send the user out of the loop if they just can't think of an empty room number to place into the field.

Anyway, here is the solution I came up with.
First off, I added another text box "Me.txtResult" to my form to watch the results of Dcount which now isn't really necessary. However, it's in the code, so I thought I should explain that part.

```<code>Private Sub txtRoomNo_Exit(Cancel As Integer)
    On Error GoTo Err_txtRoomNo_Exit

    Dim strRmX As Integer
    Dim strRmNo As Integer

    strRmNo = Me.txtRoomNo

strRmX = DCount("[2017].[ID]", "2017 Query", "[2017].[Room#]=" & strRmNo)
    Me.txtResult = strRmX

    If strRmX > 0 Then
        MsgBox "Sorry, it appears the room number you entered" & vbCrLf & _
       "      is already occupied by another patient" & vbCrLf & vbCrLf & _
       "      Click OK to try another room number.", vbCritical,
       "Surgical Weaning Tool          User Data Entry Error!"

       Me.txtRoomNo.SetFocus
    End If

    Exit_txtRoomNo_Exit:
    Exit Sub
    Err_txtRoomNo_Exit:
       MsgBox "        Error: For Room# Entry Duplicate Check" & vbCrLf & _
   "                      for New Patient Form" & vbCrLf & vbCrLf & _
   "     " & Error$ & " " & vbCrLf & vbCrLf & _
   "  Please write down ALL the above message and" & vbCrLf & _
   "                      Inform Jim about this error" & vbCrLf & _
   "                  As Soon As Possible. Thank You!" & vbCrLf & vbCrLf & _
   "      Please double check the room number you" & vbCrLf & _
   "                  just entered is not alread in use!", vbCritical,
   "Surgical Weaning Tool   -   -    ERROR!"
        Resume Exit_txtRoomNo_Exit

End Sub
</code>```

Body:
Thanks Wayne for your answer, I made the compound key but noticed the user would have to add lots of information into the form and hit enter only to see no patient added to the list. That didn't really get me what I was after but it sent me looking in the right direction...

I finally came up with a code to find the room numbers entered into the form by using Dcount on the query result and placed this code in the onExit event of the room number so I would be able to send the focus back to the field until the correct answer is submitted by the user.

I already had the field validation set to ensure the correct range of room numbers would be entered. This now has the potential of getting the user stuck in an endless loop. So, I will have to add another if statement to the error msg to send the user out of the loop if they just can't think of an empty room number to place into the field.

Anyway, here is the solution I came up with.
First off, I added another text box "Me.txtResult" to my form to watch the results of Dcount which now isn't really necessary. However, it's in the code, so I thought I should explain that part.

Private Sub txtRoomNo_Exit(Cancel As Integer)
    On Error GoTo Err_txtRoomNo_Exit

    Dim strRmX As Integer
    Dim strRmNo As Integer

    strRmNo = Me.txtRoomNo

strRmX = DCount("[2017].[ID]", "2017 Query", "[2017].[Room#]=" & strRmNo)
    Me.txtResult = strRmX

    If strRmX > 0 Then
        MsgBox "Sorry, it appears the room number you entered" & vbCrLf & _
       "      is already occupied by another patient" & vbCrLf & vbCrLf & _
       "      Click OK to try another room number.", vbCritical,
       "Surgical Weaning Tool          User Data Entry Error!"

       Me.txtRoomNo.SetFocus
    End If

    Exit_txtRoomNo_Exit:
    Exit Sub
    Err_txtRoomNo_Exit:
       MsgBox "        Error: For Room# Entry Duplicate Check" & vbCrLf & _
   "                      for New Patient Form" & vbCrLf & vbCrLf & _
   "     " & Error$ & " " & vbCrLf & vbCrLf & _
   "  Please write down ALL the above message and" & vbCrLf & _
   "                      Inform Jim about this error" & vbCrLf & _
   "                  As Soon As Possible. Thank You!" & vbCrLf & vbCrLf & _
   "      Please double check the room number you" & vbCrLf & _
   "                  just entered is not alread in use!", vbCritical,
   "Surgical Weaning Tool   -   -    ERROR!"
        Resume Exit_txtRoomNo_Exit

End Sub


问:
How can i achieve img coming out from border. email templates?
http://imgur.com/a/fKv2H

I need banner with height 100px. and img inside it with height 120px. So  the picture comeee out my banner for 20px;
Its for emails.
Also i need text column right before picture, so that text in column with background f4f4f4

```<code><table>
   <tr>
      <td>
         <img src="" style="margin-top:-20px;" />
      </td>
      <td>
        banner text here
      </td>
   </tr>
</table>
</code>```

答:
You can do this two ways, one involved slicing the image into two and the other is using two more tables. I have added the code below for you to decide which one you want to go with.

Option 1:
This option has the image as one piece sitting in an outer table with 3 columns. The outer two columns have a table with white background to cater for the heads/hats popping out of the grey area. I have set the table width at 100% to show it will look.

```
</div>
</div>
</p>

<p>Option 2
For this option, you will need to slice the top part of the image (with white background) and place both the images in one table with two rows. Both images are centered and I have set the table width at 100% to show it will look.</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><table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tbody>
    <tr>
      <td align="center" valign="top" bgcolor="#ffffff"><img src="http://i64.tinypic.com/lz7f6.png" style="display: block;">
</td>
    </tr>
    <tr>
      <td align="center" valign="top" bgcolor="#f4f4f4"><img src="http://i68.tinypic.com/4qo1mu.png" style="display: block;"></td>
    </tr>
  </tbody>
</table></code>```

The final outcome for both codes should look like this:

Let me know which option best suits you.

** UPDATE **

Your question asked if you can have option 1 with image to the left and text on the right, here is the example:

      This is some text for your email

```

Body:
http://imgur.com/a/fKv2H

I need banner with height 100px. and img inside it with height 120px. So  the picture comeee out my banner for 20px;
Its for emails.
Also i need text column right before picture, so that text in column with background f4f4f4

        banner text here

Body:
You can do this two ways, one involved slicing the image into two and the other is using two more tables. I have added the code below for you to decide which one you want to go with.

Option 1:
This option has the image as one piece sitting in an outer table with 3 columns. The outer two columns have a table with white background to cater for the heads/hats popping out of the grey area. I have set the table width at 100% to show it will look.

<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
  <td valign="top" bgcolor="#f4f4f4">
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tbody>
   <tr>
     <td bgcolor="#ffffff" style="height: 23px;" height="23"></td>
   </tr>
    </tbody>
  </table>
</td>
  <td width="171" valign="top"><img src="http://i67.tinypic.com/sdk1hh.jpg" width="171" height="178" style="display: block;"></td>
  <td valign="top" bgcolor="#f4f4f4">
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tbody>
   <tr>
     <td bgcolor="#ffffff" style="height: 23px;" height="23"></td>
   </tr>
    </tbody>
  </table>
</td>
</tr>
</tbody>
</table>

Option 2
For this option, you will need to slice the top part of the image (with white background) and place both the images in one table with two rows. Both images are centered and I have set the table width at 100% to show it will look.

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tbody>
    <tr>
      <td align="center" valign="top" bgcolor="#ffffff"><img src="http://i64.tinypic.com/lz7f6.png" style="display: block;">
</td>
    </tr>
    <tr>
      <td align="center" valign="top" bgcolor="#f4f4f4"><img src="http://i68.tinypic.com/4qo1mu.png" style="display: block;"></td>
    </tr>
  </tbody>
</table>

The final outcome for both codes should look like this:

Let me know which option best suits you.

** UPDATE **

Your question asked if you can have option 1 with image to the left and text on the right, here is the example:

<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
  <td width="171" valign="top" style="padding-left:20px;"><img src="http://i67.tinypic.com/sdk1hh.jpg" width="171" height="178" style="display: block;"></td>
  <td valign="top" bgcolor="#f4f4f4">
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tbody>
   <tr>
     <td bgcolor="#ffffff" style="height: 23px;" height="23"></td>
   </tr>
      <tr>
      <td style="font-family:Arial; font-size:12px; color:#000000; padding:5px 10px;">This is some text for your email</td>
      </tr>
    </tbody>
  </table>
</td>
</tr>
</tbody>
</table>


问:
datatables.net ajax error - http://datatables.net/tn/7
I am trying to follow an example of adding data to a datatables.net datatable using a JSON response based on this example https://www.datatables.net/examples/ajax/objects.html.

I am using an AJAX call to get a JSON response from a database.

I am getting the data and then using NewtonSoft JSON.Net to convert a datatable into a JSON array as per the code below

```<code>string jsonResult = null;
jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
jsonResult = jsonResult.Replace("[{", "{\"data\" :[{").Replace("}]", "}]}");
return jsonResult;
</code>```

This is being successfully called from an AJAX call in a separate javascript file as per the next code snippet

```<code> $.ajax({
            type: "POST",
            url: "TeamChecks.aspx/GetDataTables",
            data: JSON.stringify(params),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                console.log(data.d);
                populateTable(data.d, tableId);

            },
            error: function (data) {
                console.log(data);
            }
        }
</code>```

Which then passes the returned values to a function that should format enter the data into the datatable accordingly as per the next set of code

```<code>function populateTable(json, tableId) {
        try {
            var table = $('#table_' + tableId).DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": json,
                "columns:": [

                    { "data": "CaseHandlerStaffNumber" },
                    { "data": "RiskProfileText" },
                    { "data": "AssignedCheckerStaffNumber" },
                    { "data": "FeedbackUserStaffNumber" },
                    { "data": "ComplaintRef" },
                    { "data": "ChildComplaintRef" },
                    { "data": "CaseTypeText" },
                    { "data": "CheckGrade" }
                ]
            });
        } catch (e) {

        }
    }
</code>```

The problem that I am getting is similar to this question here jquery datatables Ajax-Error / http://datatables.net/tn/7 however, I have tried this users solution and have the same issue.

I have followed all the recommended steps as detailed here https://www.datatables.net/manual/tech-notes/7 but do not see anything wrong with the responses that come back that relate to this.

I would be grateful if anyone could help me with this as I cannot see a way around the issue at the moment

thanks

Simon

答:
Basically, you are working against yourself when you have an ajax call to get the data but then add ajax to the datatables definition.

Set up web method; note that when you do it like this, the data gets serialized twice, once by you and once by the scripting services module.

```<code>[WebMethod]
public string getTheData(String params){
    SomeDataClass dt = getthedata();
    return Newtonsoft.Json.JsonConvert.SerializeObject(dt);
}
</code>```

now the ajax:

```<code>$(document).ready(function(){
    $.ajax({
        type: "POST",
        url: "TeamChecks.aspx/GetDataTables",
        data: JSON.stringify(params),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            // jquery did the first deserialization
            // here is where the second deserization happens.
            var data = JSON.parse(reponse.d);

            populateTable(data, tableId);

        },
        error: function (data) {
            console.log(data);
        }
    }
 });
</code>```

then your function

```<code>function populateTable(json, tableId) {

        var table = $('#table_' + tableId).DataTable({
             // in this layout DataTables is expecting a straight array of objects or array of arrays depending on how you are sending the data back
            "data": json,
            "columns:": [
                { "data": "CaseHandlerStaffNumber" },
                { "data": "RiskProfileText" },
                { "data": "AssignedCheckerStaffNumber" },
                { "data": "FeedbackUserStaffNumber" },
                { "data": "ComplaintRef" },
                { "data": "ChildComplaintRef" },
                { "data": "CaseTypeText" },
                { "data": "CheckGrade" }
            ]
        });

  }
</code>```

Body:
I am trying to follow an example of adding data to a datatables.net datatable using a JSON response based on this example https://www.datatables.net/examples/ajax/objects.html.

I am using an AJAX call to get a JSON response from a database.

I am getting the data and then using NewtonSoft JSON.Net to convert a datatable into a JSON array as per the code below

string jsonResult = null;
jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(dt);
jsonResult = jsonResult.Replace("[{", "{\"data\" :[{").Replace("}]", "}]}");
return jsonResult;

This is being successfully called from an AJAX call in a separate javascript file as per the next code snippet

 $.ajax({
            type: "POST",
            url: "TeamChecks.aspx/GetDataTables",
            data: JSON.stringify(params),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                console.log(data.d);
                populateTable(data.d, tableId);

            },
            error: function (data) {
                console.log(data);
            }
        }

Which then passes the returned values to a function that should format enter the data into the datatable accordingly as per the next set of code

function populateTable(json, tableId) {
        try {
            var table = $('#table_' + tableId).DataTable({
                "processing": true,
                "serverSide": true,
                "ajax": json,
                "columns:": [

                    { "data": "CaseHandlerStaffNumber" },
                    { "data": "RiskProfileText" },
                    { "data": "AssignedCheckerStaffNumber" },
                    { "data": "FeedbackUserStaffNumber" },
                    { "data": "ComplaintRef" },
                    { "data": "ChildComplaintRef" },
                    { "data": "CaseTypeText" },
                    { "data": "CheckGrade" }
                ]
            });
        } catch (e) {

        }
    }

The problem that I am getting is similar to this question here jquery datatables Ajax-Error / http://datatables.net/tn/7 however, I have tried this users solution and have the same issue.

I have followed all the recommended steps as detailed here https://www.datatables.net/manual/tech-notes/7 but do not see anything wrong with the responses that come back that relate to this.

I would be grateful if anyone could help me with this as I cannot see a way around the issue at the moment

thanks

Simon

Body:
Basically, you are working against yourself when you have an ajax call to get the data but then add ajax to the datatables definition.

Set up web method; note that when you do it like this, the data gets serialized twice, once by you and once by the scripting services module.

[WebMethod]
public string getTheData(String params){
    SomeDataClass dt = getthedata();
    return Newtonsoft.Json.JsonConvert.SerializeObject(dt);
}

now the ajax:

$(document).ready(function(){
    $.ajax({
        type: "POST",
        url: "TeamChecks.aspx/GetDataTables",
        data: JSON.stringify(params),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            // jquery did the first deserialization
            // here is where the second deserization happens.
            var data = JSON.parse(reponse.d);

            populateTable(data, tableId);

        },
        error: function (data) {
            console.log(data);
        }
    }
 });

then your function

function populateTable(json, tableId) {

        var table = $('#table_' + tableId).DataTable({
             // in this layout DataTables is expecting a straight array of objects or array of arrays depending on how you are sending the data back
            "data": json,
            "columns:": [
                { "data": "CaseHandlerStaffNumber" },
                { "data": "RiskProfileText" },
                { "data": "AssignedCheckerStaffNumber" },
                { "data": "FeedbackUserStaffNumber" },
                { "data": "ComplaintRef" },
                { "data": "ChildComplaintRef" },
                { "data": "CaseTypeText" },
                { "data": "CheckGrade" }
            ]
        });

  }


问:
Reading data from one-to-many relationship SQL table into my model
I have below two classes which represent my SQL tables (generated by ADO.net entity data model):

```<code>public partial class Parent
{
    public Parent()
    {
        this.Students = new HashSet<Student>();
    }

    public int Parent_Id { get; set; }
    public string Parent1_Last_Name { get; set; }
    public string Parent1_First_Name { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

public partial class Student
{
        public int Student_Id { get; set; }
        public string Student_Last_Name { get; set; }
        public string Student_First_Name { get; set; }
        public int Parent_Id { get; set; }
        public virtual Parent Parent { get; set; }
}
</code>```

Now I am trying to read the data from my tables in a method as below:

```<code>var parent = new Parent();
var students = new List<Student>();

using (var dc = new SchoolDataEntities())
{
    students = dc.Students.Where(s => s.Parent_Id.Equals(parentId)).ToList();
    parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));
    parent.Students = students;
}
</code>```

I am getting a run-time "Invalid Cast" exception error when I reading from Parent table (Students table is working fine).

Error: System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SchoolApplication.Parent]' to type 'SchoolApplication.Parent'.'

Someone please educate me what I was doing wrong?

答:
This part of code returns IQueryable collection instead of single Parent model:

```<code>parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));
</code>```

For this reason, you need to materialize the query to Parent model with either FirstOrDefault() or SingleOrDefault():

```<code>parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId)).FirstOrDefault();

parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId)).SingleOrDefault();
</code>```

Related: Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[]' using linq lambda expression

Body:
I have below two classes which represent my SQL tables (generated by ADO.net entity data model):

public partial class Parent
{
    public Parent()
    {
        this.Students = new HashSet<Student>();
    }

    public int Parent_Id { get; set; }
    public string Parent1_Last_Name { get; set; }
    public string Parent1_First_Name { get; set; }
    public virtual ICollection<Student> Students { get; set; }
}

public partial class Student
{
        public int Student_Id { get; set; }
        public string Student_Last_Name { get; set; }
        public string Student_First_Name { get; set; }
        public int Parent_Id { get; set; }
        public virtual Parent Parent { get; set; }
}

Now I am trying to read the data from my tables in a method as below:

var parent = new Parent();
var students = new List<Student>();

using (var dc = new SchoolDataEntities())
{
    students = dc.Students.Where(s => s.Parent_Id.Equals(parentId)).ToList();
    parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));
    parent.Students = students;
}

I am getting a run-time "Invalid Cast" exception error when I reading from Parent table (Students table is working fine).

Error: System.InvalidCastException: 'Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[SchoolApplication.Parent]' to type 'SchoolApplication.Parent'.'

Someone please educate me what I was doing wrong?

Body:
This part of code returns IQueryable collection instead of single Parent model:

parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId));

For this reason, you need to materialize the query to Parent model with either FirstOrDefault() or SingleOrDefault():

parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId)).FirstOrDefault();

parent = dc.Parents.Where(p => p.Parent_Id.Equals(parentId)).SingleOrDefault();

Related: Unable to cast object of type 'System.Data.Entity.Infrastructure.DbQuery`1[]' using linq lambda expression


问:
Wait for the termination of n goroutines
I need to start a huge amount of goroutines and wait for their termination. The intuitive way seems to use a channel to wait till all of them are finished :

```<code>package main

type Object struct {
    //data
}

func (obj *Object) Update(channel chan int) {
    //update data
    channel <- 1
    return
}

func main() {

    channel := make(chan int, n)
    list := make([]Object, n, m)
    for {
        for _, object := range list {
            go object.Update(channel)
        }
        for i := 0; i < n; i++ {
            <-channel
        }
        //now everything has been updated. start again
    }
}
</code>```

But the problem is that the amount of objects and therefore the amount of goroutines could change. Is it possible to change the buffer size of a channel ?

Is there maybe a more elegant way to do this ?

答:
@tjameson did a great job explaining how to use WaitGroup, how to pass a reference to your WaitGroup object to your function. The one change I would make to his example is leverage defer when you are Done. I think this defer ws.Done() should be the first statement in your function.

I like WaitGroup's simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

```<code>// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}
</code>```

So your example could be solved this way:

```<code>type Object struct {
    //data
}

func (obj *Object) Update() {
    //update data
    time.Sleep(time.Second)
    fmt.Println("Update done")
    return
}

func main() {
    functions := []func(){}
    list := make([]Object, 5)
    for _, object := range list {
        function := func(obj Object){ object.Update() }(object)
        functions = append(functions, function)
    }

    Parallelize(functions...)

    fmt.Println("Group done")
}
</code>```

If you would like to use it, you can find it here https://github.com/shomali11/util

Body:
I need to start a huge amount of goroutines and wait for their termination. The intuitive way seems to use a channel to wait till all of them are finished :

package main

type Object struct {
    //data
}

func (obj *Object) Update(channel chan int) {
    //update data
    channel <- 1
    return
}

func main() {

    channel := make(chan int, n)
    list := make([]Object, n, m)
    for {
        for _, object := range list {
            go object.Update(channel)
        }
        for i := 0; i < n; i++ {
            <-channel
        }
        //now everything has been updated. start again
    }
}

But the problem is that the amount of objects and therefore the amount of goroutines could change. Is it possible to change the buffer size of a channel ?

Is there maybe a more elegant way to do this ?

Body:
@tjameson did a great job explaining how to use WaitGroup, how to pass a reference to your WaitGroup object to your function. The one change I would make to his example is leverage defer when you are Done. I think this defer ws.Done() should be the first statement in your function.

I like WaitGroup's simplicity. However, I do not like that we need to pass the reference to the goroutine because that would mean that the concurrency logic would be mixed with your business logic.

So I came up with this generic function to solve this problem for me:

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

So your example could be solved this way:

type Object struct {
    //data
}

func (obj *Object) Update() {
    //update data
    time.Sleep(time.Second)
    fmt.Println("Update done")
    return
}

func main() {
    functions := []func(){}
    list := make([]Object, 5)
    for _, object := range list {
        function := func(obj Object){ object.Update() }(object)
        functions = append(functions, function)
    }

    Parallelize(functions...)

    fmt.Println("Group done")
}

If you would like to use it, you can find it here https://github.com/shomali11/util


答:
Your code simply does not make sense. You are making Extractor etc generic, which means you want it to work for different types.

However, in Extractor.extract() method, you are specifically creating a Matrix of String and put it into your List<Matrix<T>> matrixList.

If your code only works for String, then you shouldn't make it generic.  Just make List<Matrix<String>> matrixList.

Give it a thought: if now you are creating a Extractor<Integer> intExtractor, and calling intExtractor.extract(), how can it be reasonable for your code to work?

Or, to further polish your design, make it:

```<code>interface Extractor<T> {
    public List<Matrix<T>> extract();
}

class DummyStringMatrixExtractor implements Extractor<String> {

    // useless now, can be put in extract()
    private List<Matrix<T>> matrixList;

    public Extractor() {
        this.matrixList = new ArrayList<>();
    }

    @Override
    public List<Matrix<String>> extract() {
        List<Attribute<String>> attributes = new ArrayList<>();

        attributes.add(new Attribute<String>("Test 1"));
        attributes.add(new Attribute<String>("Test 2"));

        matrixList.add(new Matrix<String>(attributes));

        return matrixList;
    }

    // useless now
    public List<Matrix<T>> getList() {
        return matrixList;
    }
}
</code>```

Title: The compiler is unhappy about my generics in Java

Body:
It always complains with:

The method add(Matrix<T>) in the type List<Matrix<T>> is not applicable for the arguments (Matrix<String>)

In the line of the Extractor class:

matrixList.add(new Matrix<String>(attributes));

It seems there is a problem in defining my generics in these 3 classes. Is there an easy way to fix that? Tried different ways and can't figure it out.

public class Test {

    public static void main(String[] args) {

        Extractor<String> extractor = new Extractor<>();
        extractor.extract();
    }
}

class Extractor<T> {

    private List<Matrix<T>> matrixList;

    public Extractor() {
        this.matrixList = new ArrayList<>();
    }

    public void extract() {
        List<Attribute<String>> attributes = new ArrayList<>();

        attributes.add(new Attribute<String>("Test 1"));
        attributes.add(new Attribute<String>("Test 2"));

       // !!!! The compiler is complaining here!
        matrixList.add(new Matrix<String>(attributes));
    }

    public List<Matrix<T>> getList() {
        return matrixList;
    }
}

class Matrix<T> {

    private List<Attribute<T>> attributes;

    public Matrix(List<Attribute<T>> attributes) {
        this.attributes = attributes;
    }

    public List<Attribute<T>> getAttributes() {
        return attributes;
    }
}

class Attribute<T> {
    private T attribute;
    public Attribute(T attr) {
        attribute = attr;
    }

    public T getAttr() {
        return attribute;
    }
}

Body:
Your code simply does not make sense. You are making Extractor etc generic, which means you want it to work for different types.

However, in Extractor.extract() method, you are specifically creating a Matrix of String and put it into your List<Matrix<T>> matrixList.

If your code only works for String, then you shouldn't make it generic.  Just make List<Matrix<String>> matrixList.

Give it a thought: if now you are creating a Extractor<Integer> intExtractor, and calling intExtractor.extract(), how can it be reasonable for your code to work?

Or, to further polish your design, make it:

interface Extractor<T> {
    public List<Matrix<T>> extract();
}

class DummyStringMatrixExtractor implements Extractor<String> {

    // useless now, can be put in extract()
    private List<Matrix<T>> matrixList;

    public Extractor() {
        this.matrixList = new ArrayList<>();
    }

    @Override
    public List<Matrix<String>> extract() {
        List<Attribute<String>> attributes = new ArrayList<>();

        attributes.add(new Attribute<String>("Test 1"));
        attributes.add(new Attribute<String>("Test 2"));

        matrixList.add(new Matrix<String>(attributes));

        return matrixList;
    }

    // useless now
    public List<Matrix<T>> getList() {
        return matrixList;
    }
}


问:
Creating backends according to path
I am using HAProxy as a proxy server in front of Consul, a microservice registry. I use HAProxy to route traffic to a specific backend according to what type of node it is (what service it runs, is it active, what version it is, etc etc)

So far, I can use HAProxy to see what the path begins with, and route it to one backend eg.if the path begins with /blog, it'll go to the blog backend.

My question is, when there are multiple criterion to select a backend, how should I create said backends? Can I nest them in a way? Should I just exhaustive list all combinations of criteria and add a backend for that?

答:
A backend is one or more servers (services, endpoints) that can all handle the same set of requests.  You don't define backends based on what goes to them, but rather on what can go to them.

Example, if you have a set of servers that can serve several kinds of static assets, you wouldn't make a backend for javascript, another for CSS, another for images. You'd make one.

```<code>backend static-assets
    mode http
    server static-1 203.0.113.100:80
    server static-2 203.0.113.200:80
</code>```

Then route the appropriate requests to that backend.

You can do this in several ways.

Anonymous ACLs, one per pattern:

```<code>frontend main
    mode http
    bind :80
    use_backend static-assets if { path_end .js }
    use_backend static-assets if { path_end .css }
    use_backend static-assets if { path_end .png }
</code>```

Anonymous ACLs with explicit || (logical OR):

```<code>frontend main
    mode http
    bind :80
    use_backend static-assets if { path_end .js } || { path_end .css } || { path_end .png }
</code>```

Or use named ACLs.  Each line in a named ACL is OR -- only one line needs to match for the ACL to match.

```<code>frontend main
    mode http
    bind :80
    acl is_static path_end .js
    acl is_static path_end .css
    acl is_static path_end .png
    use_backend static-assets if is_static
</code>```

Or use any combination of these.

The first use_backend directive to match is the backend the request will go to -- they're processed in defined order.  No "nesting" should be necessary.

Title: Creating backends according to path

Body:
A backend is one or more servers (services, endpoints) that can all handle the same set of requests.  You don't define backends based on what goes to them, but rather on what can go to them.

Example, if you have a set of servers that can serve several kinds of static assets, you wouldn't make a backend for javascript, another for CSS, another for images. You'd make one.

backend static-assets
    mode http
    server static-1 203.0.113.100:80
    server static-2 203.0.113.200:80

Then route the appropriate requests to that backend.

You can do this in several ways.

Anonymous ACLs, one per pattern:

frontend main
    mode http
    bind :80
    use_backend static-assets if { path_end .js }
    use_backend static-assets if { path_end .css }
    use_backend static-assets if { path_end .png }

Anonymous ACLs with explicit || (logical OR):

frontend main
    mode http
    bind :80
    use_backend static-assets if { path_end .js } || { path_end .css } || { path_end .png }

Or use named ACLs.  Each line in a named ACL is OR -- only one line needs to match for the ACL to match.

frontend main
    mode http
    bind :80
    acl is_static path_end .js
    acl is_static path_end .css
    acl is_static path_end .png
    use_backend static-assets if is_static

Or use any combination of these.

The first use_backend directive to match is the backend the request will go to -- they're processed in defined order.  No "nesting" should be necessary.


问:
I'm can't quite wrap my head around this code for checking for a perfect square
I'm a novice as may be obvious, in advanced c++ at my school and I was working on home work and was having issues with try to figure out how to decide if an integer is a perfect square or not when I stumbled across this piece of code. </p>

```<code>if (num <= 0 || sqrt(num) != static_cast<int>(sqrt(num)))
      throw "Error: The number is not a perfect square.\n";

    return sqrt(num);
</code>```

<p>If possible  as an exception function I just don't quite understand how the piece after || works. And would just like to know for future reference. </p>

答: sqrt(num) returns the square root as a floating point number.  static_cast will attempt to convert the return value to an integer, which will be successful and truncate the value to an integer.  If num was a perfect square, this won't do anything and the values will be equal.</p>

Body:
I'm a novice as may be obvious, in advanced c++ at my school and I was working on home work and was having issues with try to figure out how to decide if an integer is a perfect square or not when I stumbled across this piece of code.

if (num <= 0 || sqrt(num) != static_cast<int>(sqrt(num)))
      throw "Error: The number is not a perfect square.\n";

    return sqrt(num);

If possible  as an exception function I just don't quite understand how the piece after || works. And would just like to know for future reference.


问:
Detecting Browser Autofill
How do you tell if a browser has auto filled a text-box? Especially with username & password boxes that autofill around page load.

My first question is when does this occur in the page load sequence? Is it before or after document.ready?

Secondly how can I use logic to find out if this occurred? Its not that i want to stop this from occurring, just hook into the event. Preferably something like this:

```<code>if (autoFilled == true) {

} else {

}
</code>```

If possible I would love to see a jsfiddle showing your answer.

Possible duplicates

DOM event for browser password autofill?

Browser Autofill and Javascript triggered events

--Both these questions don't really explain what events are triggered, they just continuously recheck the text-box (not good for performance!).

答:
On chrome, you can detect autofill fields by settings a special css rule for autofilled elements, and then checking with javascript if the element has that rule applied.

Example:

CSS

```<code>input:-webkit-autofill {
  -webkit-box-shadow: 0 0 0 30px white inset;
}
</code>```

JavaScript

```<code>  let css = $("#selector").css("box-shadow")
  if (css.match(/inset/))
    console.log("autofilled:", $("#selector"))
</code>```

Title: Detecting Browser Autofill

Body:
How do you tell if a browser has auto filled a text-box? Especially with username & password boxes that autofill around page load.

My first question is when does this occur in the page load sequence? Is it before or after document.ready?

Secondly how can I use logic to find out if this occurred? Its not that i want to stop this from occurring, just hook into the event. Preferably something like this:

if (autoFilled == true) {

} else {

}

If possible I would love to see a jsfiddle showing your answer.

Possible duplicates

DOM event for browser password autofill?

Browser Autofill and Javascript triggered events

--Both these questions don't really explain what events are triggered, they just continuously recheck the text-box (not good for performance!).

Body:
On chrome, you can detect autofill fields by settings a special css rule for autofilled elements, and then checking with javascript if the element has that rule applied.

Example:

CSS

input:-webkit-autofill {
  -webkit-box-shadow: 0 0 0 30px white inset;
}

JavaScript

  let css = $("#selector").css("box-shadow")
  if (css.match(/inset/))
    console.log("autofilled:", $("#selector"))


问:
VueJS - Axios array not updated
I'm trying to update from an API my array declared in data. When I init the array with an object, this object appears well in the HTML code. It seems that the array is not "saved" after the scope of the axios call. Anyone can help me please ? I don't have any error code/message.

```<code>var vm = new Vue({
el: '#recettes',
data: {
  results: []
},
created() {
  axios.get('url')
  .then((response) => {
    this.results = response.data
    console.log("Size before end of scope = " + this.results.length)  // = 4
  });
  console.log("Size after = " + this.results.length) // = 0
}
});
</code>```

The response API is:

```<code>[
  {
    "id": 1,
    "titre": "Cassoulet",
    "contenu": "Couper. Faire cuire...",
    "id_util": 1
  },
  {
    "id": 2,
    "titre": "Gateau",
    "contenu": "chocolat",
    "id_util": 4
  },
  {
    "id": 3,
    "titre": "Gateau",
    "contenu": "fraise",
    "id_util": 5
  },
  {
    "id": 4,
    "titre": "Gateau",
    "contenu": "Mélanger, cuire, four 220°...",
    "id_util": 5
  }
]
</code>```

Template:

```<code>    <div id="recettes">
    <div v-for="result in results">
      <div class="card">
        <div class="card-divider">
          {{ result.titre }}
        </div>
        <div class="card-section">
          {{ result.contenu }}
        </div>
      </div>
    </div>
    </div>
</code>```

UPDATE

```<code>var vm = new Vue({
  el: '#recettes',
  data: {
    results: []
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});
</code>```

With this code, results[0].titre contains the right string. But in the HTML code, no cards are displayed.
And with this code:

```<code>var vm = new Vue({
  el: '#recettes',
  data: {
    results: [
      {"id" = 1, "id":1,"titre":"Cassoulet","contenu":"Couper. Faire cuire...","id_util":1}
    ]
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});
</code>```

One card is displayed in the HTML with titre = "Cassoulet" and contenu = "Couper. Faire cuire..."

It's why I said that it seems that the array is not updated...

答:
Hi I think this is an async problem. As you can see, javascript doesn't wait for another for a function to finish. Try this one.

```<code>created() {
  axios.get('url')
  .then((response) => {
    this.results = response.data
    console.log("Size before end of scope = " + this.results.length)  // = 4
    return true;
  }).then((response) => {
      console.log("Size after = " + this.results.length) // = 4
  });
  // console.log("Size after = " + this.results.length) // = 0
}
</code>```

UPDATE1 : Added fiddle

Here's a sample fiddle for you to look on.
https://jsfiddle.net/khenxi/n49zj258/

Title: VueJS - Axios array not updated

Body:
I'm trying to update from an API my array declared in data. When I init the array with an object, this object appears well in the HTML code. It seems that the array is not "saved" after the scope of the axios call. Anyone can help me please ? I don't have any error code/message.

var vm = new Vue({
el: '#recettes',
data: {
  results: []
},
created() {
  axios.get('url')
  .then((response) => {
    this.results = response.data
    console.log("Size before end of scope = " + this.results.length)  // = 4
  });
  console.log("Size after = " + this.results.length) // = 0
}
});

The response API is:

[
  {
    "id": 1,
    "titre": "Cassoulet",
    "contenu": "Couper. Faire cuire...",
    "id_util": 1
  },
  {
    "id": 2,
    "titre": "Gateau",
    "contenu": "chocolat",
    "id_util": 4
  },
  {
    "id": 3,
    "titre": "Gateau",
    "contenu": "fraise",
    "id_util": 5
  },
  {
    "id": 4,
    "titre": "Gateau",
    "contenu": "Mélanger, cuire, four 220°...",
    "id_util": 5
  }
]

Template:

          {{ result.titre }}

          {{ result.contenu }}

UPDATE

var vm = new Vue({
  el: '#recettes',
  data: {
    results: []
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});

With this code, results[0].titre contains the right string. But in the HTML code, no cards are displayed.
And with this code:

var vm = new Vue({
  el: '#recettes',
  data: {
    results: [
      {"id" = 1, "id":1,"titre":"Cassoulet","contenu":"Couper. Faire cuire...","id_util":1}
    ]
},
created() {
  axios.get('URL')
  .then(response => {
    this.results = response.data
    console.log("size: " + this.results.length)
    console.log('results[0]: ' + this.results[0].titre)
  })
}
});

One card is displayed in the HTML with titre = "Cassoulet" and contenu = "Couper. Faire cuire..."

It's why I said that it seems that the array is not updated...

Body:
Hi I think this is an async problem. As you can see, javascript doesn't wait for another for a function to finish. Try this one.

created() {
  axios.get('url')
  .then((response) => {
    this.results = response.data
    console.log("Size before end of scope = " + this.results.length)  // = 4
    return true;
  }).then((response) => {
      console.log("Size after = " + this.results.length) // = 4
  });
  // console.log("Size after = " + this.results.length) // = 0
}

UPDATE1 : Added fiddle

Here's a sample fiddle for you to look on.
https://jsfiddle.net/khenxi/n49zj258/


问:
PHP autodoc(Inheritance) autodocumentor tags
I am using phpautodocumentor, I am writing a class which extends a class which is in completely different folder, How can I write in comments that I am extending that particular class. Because intellisense in visual studio or Aptana doesn't recognize. The code works fine.The problem is documenting. It doesn't say I am extending so and so class in documentation</p>

答:
There's no tag for extending, your IDE should realize it from the code, good ones - like PDT, Zend Studio or PhpStorm - do. However, there's a @see tag to refer to other content in the docs. </p>

```<code> /**
  * this class extends main_class.
  * @see main_class, TEST_CONST
  */
  subclass extends main_class {
  }
</code>```

Body:
There's no tag for extending, your IDE should realize it from the code, good ones - like PDT, Zend Studio or PhpStorm - do. However, there's a @see tag to refer to other content in the docs.

 /**
  * this class extends main_class.
  * @see main_class, TEST_CONST
  */
  subclass extends main_class {
  }


问:
Chartjs stacked bar single max value
Is it possible to use chartjs stacked bar with one max value?

I have two values. One is sales and second is net revenue which is made from sales.

I want to show both, but I don't want to have revenue added on top of the sales value since it's already part of it.

data

```<code>sales (max value) | earning
500               | 100
300               | 30
</code>```

now it is showing 600 and 330, rather than keeping it to 500 and 300.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: 'Sales',
        data: [500, 300],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)'
        ],
        borderColor: [
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)'
        ],
        borderWidth: 2
      },
      {
        label: 'Earning',
        data: [100, 30],
        backgroundColor: [
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 2
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }]

    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>

<canvas id="myChart" width="400" height="400"></canvas></code>```

答:
Basically, you need to subtract the second value from the first one before the chart initializes, so that, it doesn't draw the graph with combined values.

To accomplish so, you can use the following chart plugin ...

```<code>plugins: [{
   beforeInit: function(c) {
      var data1 = c.data.datasets[0].data;
      var data2 = c.data.datasets[1].data;
      c.data.datasets[0].data = data1.map(function(e, i) {
         return e - data2[i];
      });
   }
}]
</code>```

add this plugin followed by your chart options.

UPDATE

use the following tooltips callback function to show the old values on tooltip's label ...

```<code>tooltips: {
   callbacks: {
      label: function(t, d) {
         var dst1_label = d.datasets[t.datasetIndex].label + ': ' + (+t.yLabel + d.datasets[1].data[t.index]);
         var dst2_label = d.datasets[t.datasetIndex].label + ': ' + t.yLabel;
         if (t.datasetIndex === 0) return dst1_label;
         else return dst2_label;
      }
   }
}
</code>```

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
         label: 'Sales',
         data: [500, 300],
         backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)'
         ],
         borderColor: [
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)'
         ],
         borderWidth: 2
      }, {
         label: 'Earning',
         data: [100, 30],
         backgroundColor: [
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)'
         ],
         borderColor: [
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)'
         ],
         borderWidth: 2
      }]
   },
   options: {
      scales: {
         yAxes: [{
            stacked: true,
            ticks: {
               beginAtZero: true
            }
         }],
         xAxes: [{
            stacked: true,
            ticks: {
               beginAtZero: true
            }
         }]
      },
      tooltips: {
         callbacks: {
            label: function(t, d) {
               var dst1_label = d.datasets[t.datasetIndex].label + ': ' + (+t.yLabel + d.datasets[1].data[t.index]);
               var dst2_label = d.datasets[t.datasetIndex].label + ': ' + t.yLabel;
               if (t.datasetIndex === 0) return dst1_label;
               else return dst2_label;

            }
         }
      }
   },
   plugins: [{
      beforeInit: function(c) {
         var data1 = c.data.datasets[0].data;
         var data2 = c.data.datasets[1].data;
         c.data.datasets[0].data = data1.map(function(e, i) {
            return e - data2[i];
         });
      }
   }]
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas></code>```

Title: Chartjs stacked bar single max value

Body:
Is it possible to use chartjs stacked bar with one max value?

I have two values. One is sales and second is net revenue which is made from sales.

I want to show both, but I don't want to have revenue added on top of the sales value since it's already part of it.

data

sales (max value) | earning
500               | 100
300               | 30

now it is showing 600 and 330, rather than keeping it to 500 and 300.

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: 'Sales',
        data: [500, 300],
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)',
          'rgba(255, 99, 132, 0.2)'
        ],
        borderColor: [
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)',
          'rgba(255,99,132,1)'
        ],
        borderWidth: 2
      },
      {
        label: 'Earning',
        data: [100, 30],
        backgroundColor: [
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)',
          'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 2
      }
    ]
  },
  options: {
    scales: {
      yAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true
        }
      }]

    }
  }
});

<canvas id="myChart" width="400" height="400"></canvas>

Body:
Basically, you need to subtract the second value from the first one before the chart initializes, so that, it doesn't draw the graph with combined values.

To accomplish so, you can use the following chart plugin ...

plugins: [{
   beforeInit: function(c) {
      var data1 = c.data.datasets[0].data;
      var data2 = c.data.datasets[1].data;
      c.data.datasets[0].data = data1.map(function(e, i) {
         return e - data2[i];
      });
   }
}]

add this plugin followed by your chart options.

UPDATE

use the following tooltips callback function to show the old values on tooltip's label ...

tooltips: {
   callbacks: {
      label: function(t, d) {
         var dst1_label = d.datasets[t.datasetIndex].label + ': ' + (+t.yLabel + d.datasets[1].data[t.index]);
         var dst2_label = d.datasets[t.datasetIndex].label + ': ' + t.yLabel;
         if (t.datasetIndex === 0) return dst1_label;
         else return dst2_label;
      }
   }
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
      labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
      datasets: [{
         label: 'Sales',
         data: [500, 300],
         backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)',
            'rgba(255, 99, 132, 0.2)'
         ],
         borderColor: [
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)',
            'rgba(255,99,132,1)'
         ],
         borderWidth: 2
      }, {
         label: 'Earning',
         data: [100, 30],
         backgroundColor: [
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)',
            'rgba(255, 159, 64, 0.2)'
         ],
         borderColor: [
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)',
            'rgba(255, 159, 64, 1)'
         ],
         borderWidth: 2
      }]
   },
   options: {
      scales: {
         yAxes: [{
            stacked: true,
            ticks: {
               beginAtZero: true
            }
         }],
         xAxes: [{
            stacked: true,
            ticks: {
               beginAtZero: true
            }
         }]
      },
      tooltips: {
         callbacks: {
            label: function(t, d) {
               var dst1_label = d.datasets[t.datasetIndex].label + ': ' + (+t.yLabel + d.datasets[1].data[t.index]);
               var dst2_label = d.datasets[t.datasetIndex].label + ': ' + t.yLabel;
               if (t.datasetIndex === 0) return dst1_label;
               else return dst2_label;

            }
         }
      }
   },
   plugins: [{
      beforeInit: function(c) {
         var data1 = c.data.datasets[0].data;
         var data2 = c.data.datasets[1].data;
         c.data.datasets[0].data = data1.map(function(e, i) {
            return e - data2[i];
         });
      }
   }]
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>


问:
AttributeError in Python regarding classes
```<code>import tkinter

DEFAULT_FONT = 'Helvetica, 16'

class UserInterface:
    def __init__(self):
        self._root_window = tkinter.Tk()

        self._canvas = tkinter.Canvas(master=self._root_window,
                                      width=400,
                                      height=400,
                                      background='#2A722E')

        self._canvas.grid(row=0,
                          column=0,
                          padx=30,
                          pady=30,
                          sticky=tkinter.W + tkinter.E + tkinter.N + tkinter.S)

        self._ask_user_input()

    def run(self):
        self._root_window.mainloop()

    def _ask_user_input(self):
        user_input = UserInput()
        user_input.show()

        if user_input.ok_is_clicked():
            input_list = user_input.get_input_list()
            return input_list

class UserInput:
    def __init__(self):
        self._user_input = tkinter.Toplevel()

        row_num = tkinter.Label(master=self._user_input,
                                text='Specify a row number 4-16:',
                                font=DEFAULT_FONT)
        row_num.grid(row=0,
                     column=0,
                     padx=10,
                     pady=10,
                     sticky=tkinter.W)

        self._row_num_entry = tkinter.Entry(master=self._user_input,
                                            width=15,
                                            font=DEFAULT_FONT)
        self._row_num_entry.grid(row=0,
                                 column=1,
                                 padx=10,
                                 pady=10,
                                 sticky=tkinter.E)

        col_num = tkinter.Label(master=self._user_input,
                                text='Specify a column number 4-16:',
                                font=DEFAULT_FONT)
        col_num.grid(row=1,
                     column=0,
                     padx=10,
                     pady=10,
                     sticky=tkinter.W)

        self._col_num_entry = tkinter.Entry(master=self._user_input,
                                            width=15,
                                            font=DEFAULT_FONT)
        self._col_num_entry.grid(row=1,
                                 column=1,
                                 padx=10,
                                 pady=10, sticky=tkinter.E)

        first_player = tkinter.Label(master=self._user_input,
                                     text='Specify the first player B/W:',
                                     font=DEFAULT_FONT)
        first_player.grid(row=2,
                          column=0,
                          padx=10,
                          pady=10,
                          sticky=tkinter.W)

        self._first_player_entry = tkinter.Entry(master=self._user_input,
                                                 width=15,
                                                 font=DEFAULT_FONT)
        self._first_player_entry.grid(row=2,
                                      column=1,
                                      padx=10,
                                      pady=10,
                                      sticky=tkinter.W)

        win_condition = tkinter.Label(master=self._user_input,
                                      text='Specify a winning condition, < or >:',
                                      font=DEFAULT_FONT)
        win_condition.grid(row=3,
                           column=0,
                           padx=10,
                           pady=10,
                           sticky=tkinter.W)

        self._win_condition_entry = tkinter.Entry(master=self._user_input,
                                                  width=15,
                                                  font=DEFAULT_FONT)
        self._win_condition_entry.grid(row=3,
                                       column=1,
                                       padx=10,
                                       pady=10,
                                       sticky=tkinter.E)

        ok_button = tkinter.Button(master=self._user_input,
                                   text='OK',
                                   font=DEFAULT_FONT,
                                   command=self._ok_button_clicked)
        ok_button.grid(row=4,
                       columnspan=2,
                       padx=40,
                       pady=40)

        self._ok_clicked = False
        self._input_list = []

    def show(self) -> None:
        self._user_input.grab_set()
        self._user_input.wait_window()

    def ok_is_clicked(self) -> bool:
        return self._ok_clicked

    def _ok_button_clicked(self):
        self._ok_clicked = True

        row_num = self._row_num_entry.get()
        col_num = self._col_num_entry.get()
        starter = self._first_player_entry.get()
        winning = self._win_condition_entry.get()

        self._input_list.extend([row_num, col_num, starter, winning])

        self._user_input.destroy()

    def get_input_list(self) -> list:
        return self._input_list

if __name__ == '__main__':
    game = UserInterface()
    game.run()
</code>```

However when I run the UserInteface() class by assigning it to a variable, I get the following error:

```<code>Traceback (most recent call last):
  File "/Users/cagataycakiroglu/Desktop/othello_gui.py", line 166, in <module>
    game = UserInterface()
  File "/Users/cagataycakiroglu/Desktop/othello_gui.py", line 26, in __init__
    user_input = self._ask_user_input()
  File "/Users/cagataycakiroglu/Desktop/othello_gui.py", line 36, in _ask_user_input
    user_input = UserInput()
  File "/Users/cagataycakiroglu/Desktop/othello_gui.py", line 127, in __init__
    command = self._ok_button_clicked)
AttributeError: 'UserInput' object has no attribute '_ok_button_clicked'
</code>```

What am I doing wrong? Please explain as you'd explain to a Python novice without using advanced techniques like lambda or so. Thanks!

答:
You are missing self in __init__(). It should read:

```<code>def __init__(self):
</code>```

I don't know if that is your only problem because you didn't post all of the code (the snippet you gave won't run for many other reasons), but I am assuming that this is what you were looking for.

Edit

```<code>self._dialog_window.destroy()
</code>```

No definition for _dialog_window exists.

Edit 2

```<code>command = self._ok_button_clicked())
</code>```

Should read:

```<code>command = self._ok_button_clicked)
</code>```

Lists don't have a destroy method:

```<code>self._input_list.destroy()  # this will fail
</code>```

Body:
import tkinter

DEFAULT_FONT = 'Helvetica, 16'

class UserInterface:
    def __init__(self):
        self._root_window = tkinter.Tk()

        self._canvas = tkinter.Canvas(master=self._root_window,
                                      width=400,
                                      height=400,
                                      background='#2A722E')

        self._canvas.grid(row=0,
                          column=0,
                          padx=30,
                          pady=30,
                          sticky=tkinter.W + tkinter.E + tkinter.N + tkinter.S)

        self._ask_user_input()

    def run(self):
        self._root_window.mainloop()

    def _ask_user_input(self):
        user_input = UserInput()
        user_input.show()

        if user_input.ok_is_clicked():
            input_list = user_input.get_input_list()
            return input_list

class UserInput:
    def __init__(self):
        self._user_input = tkinter.Toplevel()

        row_num = tkinter.Label(master=self._user_input,
                                text='Specify a row number 4-16:',
                                font=DEFAULT_FONT)
        row_num.grid(row=0,
                     column=0,
                     padx=10,
                     pady=10,
                     sticky=tkinter.W)

        self._row_num_entry = tkinter.Entry(master=self._user_input,
                                            width=15,
                                            font=DEFAULT_FONT)
        self._row_num_entry.grid(row=0,
                                 column=1,
                                 padx=10,
                                 pady=10,
                                 sticky=tkinter.E)

        col_num = tkinter.Label(master=self._user_input,
                                text='Specify a column number 4-16:',
                                font=DEFAULT_FONT)
        col_num.grid(row=1,
                     column=0,
                     padx=10,
                     pady=10,
                     sticky=tkinter.W)

        self._col_num_entry = tkinter.Entry(master=self._user_input,
                                            width=15,
                                            font=DEFAULT_FONT)
        self._col_num_entry.grid(row=1,
                                 column=1,
                                 padx=10,
                                 pady=10, sticky=tkinter.E)

        first_player = tkinter.Label(master=self._user_input,
                                     text='Specify the first player B/W:',
                                     font=DEFAULT_FONT)
        first_player.grid(row=2,
                          column=0,
                          padx=10,
                          pady=10,
                          sticky=tkinter.W)

        self._first_player_entry = tkinter.Entry(master=self._user_input,
                                                 width=15,
                                                 font=DEFAULT_FONT)
        self._first_player_entry.grid(row=2,
                                      column=1,
                                      padx=10,
                                      pady=10,
                                      sticky=tkinter.W)

        win_condition = tkinter.Label(master=self._user_input,
                                      text='Specify a winning condition, < or >:',
                                      font=DEFAULT_FONT)
        win_condition.grid(row=3,
                           column=0,
                           padx=10,
                           pady=10,
                           sticky=tkinter.W)

        self._win_condition_entry = tkinter.Entry(master=self._user_input,
                                                  width=15,
                                                  font=DEFAULT_FONT)
        self._win_condition_entry.grid(row=3,
                                       column=1,
                                       padx=10,
                                       pady=10,
                                       sticky=tkinter.E)

        ok_button = tkinter.Button(master=self._user_input,
                                   text='OK',
                                   font=DEFAULT_FONT,
                                   command=self._ok_button_clicked)
        ok_button.grid(row=4,
                       columnspan=2,
                       padx=40,
                       pady=40)

        self._ok_clicked = False
        self._input_list = []

    def show(self) -> None:
        self._user_input.grab_set()
        self._user_input.wait_window()

    def ok_is_clicked(self) -> bool:
        return self._ok_clicked

    def _ok_button_clicked(self):
        self._ok_clicked = True

        row_num = self._row_num_entry.get()
        col_num = self._col_num_entry.get()
        starter = self._first_player_entry.get()
        winning = self._win_condition_entry.get()

        self._input_list.extend([row_num, col_num, starter, winning])

        self._user_input.destroy()

    def get_input_list(self) -> list:
        return self._input_list

if __name__ == '__main__':
    game = UserInterface()
    game.run()

However when I run the UserInteface() class by assigning it to a variable, I get the following error:

Traceback (most recent call last):
  File "/Users/cagataycakiroglu/Desktop/othello_gui.py", line 166, in <module>
    game = UserInterface()
  File "/Users/cagataycakiroglu/Desktop/othello_gui.py", line 26, in __init__
    user_input = self._ask_user_input()
  File "/Users/cagataycakiroglu/Desktop/othello_gui.py", line 36, in _ask_user_input
    user_input = UserInput()
  File "/Users/cagataycakiroglu/Desktop/othello_gui.py", line 127, in __init__
    command = self._ok_button_clicked)
AttributeError: 'UserInput' object has no attribute '_ok_button_clicked'

What am I doing wrong? Please explain as you'd explain to a Python novice without using advanced techniques like lambda or so. Thanks!

Body:
You are missing self in __init__(). It should read:

def __init__(self):

I don't know if that is your only problem because you didn't post all of the code (the snippet you gave won't run for many other reasons), but I am assuming that this is what you were looking for.

Edit

self._dialog_window.destroy()

No definition for _dialog_window exists.

Edit 2

command = self._ok_button_clicked())

Should read:

command = self._ok_button_clicked)

Lists don't have a destroy method:

self._input_list.destroy()  # this will fail


问:
How to create a Docker image for PHP and Node?
I am trying to create a Docker container for my Angular app that has a PHP file in it. Angular requires npm so I need to have Node.js installed. I don't need Apache for my project, just pure php should work fine.

My understanding is I should have a docker-compose like this:

```<code>FROM node:latest

..install php here

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app
RUN npm install

COPY . /usr/src/app
</code>```

I am not sure how to install PHP in my case, Can anyone point me to the right direction? Thanks a lot!

答:
I suggest you do it differently. Since php is longer than install, use the php image and install node.

```<code>FROM php:5.6-apache

RUN apt-get update && apt-get install -y nodejs npm
#WORKDIR is /var/www/html
COPY . /var/www/html/
RUN npm install
</code>```

And then you have apache2 provides .php files.

Update for 2021

It is recommended to use php:7.4-apache or newer.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a Docker container for my Angular app that has a PHP file in it. Angular requires npm so I need to have Node.js installed. I don't need Apache for my project, just pure php should work fine.

My understanding is I should have a docker-compose like this:

FROM node:latest

..install php here

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json /usr/src/app
RUN npm install

COPY . /usr/src/app

I am not sure how to install PHP in my case, Can anyone point me to the right direction? Thanks a lot!

Body:
I suggest you do it differently. Since php is longer than install, use the php image and install node.

FROM php:5.6-apache

RUN apt-get update && apt-get install -y nodejs npm
#WORKDIR is /var/www/html
COPY . /var/www/html/
RUN npm install

And then you have apache2 provides .php files.

Update for 2021

It is recommended to use php:7.4-apache or newer.


问:
django many to many field does not save
I have the following models:

```<code>class Offering(models.Model):
    entity = models.OneToOneField('companies.entity')
    company_type = models.ManyToManyField(CompanyTypeChoice, blank=True)

@python_2_unicode_compatible
class Tag(models.Model):
    word = models.CharField(max_length=64)

@python_2_unicode_compatible
class Entity(models.Model):
    tags = models.ManyToManyField(Tag,related_name='companies', blank=True, null=True)

class CompanyTypeChoice(models.Model):
title = models.CharField(max_length=64)
</code>```

I have the following loop that I want to create a M2M tag relation:

```<code>offerings = Offering.objects.all()
    for o in offerings:
        for ct in o.company_type.all():
            tag = Tag.objects.get(word=ct.title)
            e = Entity.objects.get(pk=o.entity.id)
            e.tags.add(tag)
</code>```

This does not save the M2M relationship. What am I doing wrong?

答: The problem was that this loop ran once and entered all of the values in.  The duplicates didn't run again and did not throw an error.</p>

Title: django many to many field does not save

Body:
I have the following models:

class Offering(models.Model):
    entity = models.OneToOneField('companies.entity')
    company_type = models.ManyToManyField(CompanyTypeChoice, blank=True)

@python_2_unicode_compatible
class Tag(models.Model):
    word = models.CharField(max_length=64)

@python_2_unicode_compatible
class Entity(models.Model):
    tags = models.ManyToManyField(Tag,related_name='companies', blank=True, null=True)

class CompanyTypeChoice(models.Model):
title = models.CharField(max_length=64)

I have the following loop that I want to create a M2M tag relation:

offerings = Offering.objects.all()
    for o in offerings:
        for ct in o.company_type.all():
            tag = Tag.objects.get(word=ct.title)
            e = Entity.objects.get(pk=o.entity.id)
            e.tags.add(tag)

This does not save the M2M relationship. What am I doing wrong?


问:
Splitting a string in java with more than one split parameter
I am working with strings and had a quick question. I have a string of text I extracted from a file and now want to create a string array with each sentence of the text, I understand I could use string.split("."); for periods but how do I add question marks and exclamation marks. I tried string.split("." + "!" + "?"); but that didn't seem to work. Any help would be appreciated!

答:
string.split(".") does not work as you expect it does...

```<code>String s = "Hello.world";
System.out.println(Arrays.toString(s.split("."))); // outputs []
</code>```

Split method takes a regex.

```<code>String s = "Hello.world";
System.out.println(Arrays.toString(s.split("\\."))); // outputs [Hello, world]
</code>```

The regex of ".!?" says "any character followed by zero or more !" (which effectively is the same result as just ".")

If you want to split on individual characters, use a character class

string.split("[.!?]")

Body:
string.split(".") does not work as you expect it does...

String s = "Hello.world";
System.out.println(Arrays.toString(s.split("."))); // outputs []

Split method takes a regex.

String s = "Hello.world";
System.out.println(Arrays.toString(s.split("\\."))); // outputs [Hello, world]

The regex of ".!?" says "any character followed by zero or more !" (which effectively is the same result as just ".")

If you want to split on individual characters, use a character class

string.split("[.!?]")