问:
How to get XML String back from a javax.ws.rs.core.Response
Here is my code that works:

```<code>        Response response = target.queryParam("start", startIndex)
                .queryParam("end", end)
                .request()
                .accept(MediaType.APPLICATION_XML)
                .header(authorizationHeaderName, authorizationHeaderValue)
                .get();

        MyClass message = response.readEntity(MyClass.class);
</code>```

I want to also be able to do this:

```<code>if(loggingTurnedOn == true)
{
   logger.debug(XMLfromResponseMessage);
}
</code>```

But I don't know how to get the raw XML String from the Response.

答:
An answer from another question:
You can use Response#bufferEntity(), which will allow you to read the entity stream multiple times.</p>

```<code>Response response = ...
response.bufferEntity();
String s = response.readEntity(String.class);
MyEntity me = response.readEntity(MyEntity.class);
response.close();
</code>```

Body:
Here is my code that works:

        Response response = target.queryParam("start", startIndex)
                .queryParam("end", end)
                .request()
                .accept(MediaType.APPLICATION_XML)
                .header(authorizationHeaderName, authorizationHeaderValue)
                .get();

        MyClass message = response.readEntity(MyClass.class);

I want to also be able to do this:

if(loggingTurnedOn == true)
{
   logger.debug(XMLfromResponseMessage);
}

But I don't know how to get the raw XML String from the Response.

Body:
An answer from another question:
You can use Response#bufferEntity(), which will allow you to read the entity stream multiple times.

Response response = ...
response.bufferEntity();
String s = response.readEntity(String.class);
MyEntity me = response.readEntity(MyEntity.class);
response.close();


来源: stackexchange

问:
Select multiple columns with SELECT WHEN in spark-sql
How to get multiple columns from select when?
For example, I can get 1 column with this:

```<code>df1.alias("l")
.join(df2.alias("r"),Seq("id"))
.select(when($"l.score" > $"r.score", $"l.name").otherwise($"r.name"))
</code>```

But let's say I want to get more than 1 column (or even all attributes from a data frame), I cannot do any of these:

```<code>df1.alias("l")
.join(df2.alias("r"),Seq("id"))
.select(when($"l.score" > $"r.score", Seq($"l.id",$"l.name")).otherwise(Seq($"r.id",$"r.name")))

df1.alias("l")
.join(df2.alias("r"),Seq("id"))
.select(when($"l.score" > $"r.score", $"l.*").otherwise($"r.*"))
</code>```

any idea how to circumvent this?

答:
You can return struct:

```<code>import org.apache.spark.sql.struct

when($"l.score" > $"r.score", struct($"l.name", $"l.score"))
  .otherwise(struct($"r.name", "r.score"))
</code>```

or for all fields:

```<code>when($"l.score" > $"r.score", struct($"l.*"))
  .otherwise(struct($"r.*"))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to get multiple columns from select when?
For example, I can get 1 column with this:

df1.alias("l")
.join(df2.alias("r"),Seq("id"))
.select(when($"l.score" > $"r.score", $"l.name").otherwise($"r.name"))

But let's say I want to get more than 1 column (or even all attributes from a data frame), I cannot do any of these:

df1.alias("l")
.join(df2.alias("r"),Seq("id"))
.select(when($"l.score" > $"r.score", Seq($"l.id",$"l.name")).otherwise(Seq($"r.id",$"r.name")))

df1.alias("l")
.join(df2.alias("r"),Seq("id"))
.select(when($"l.score" > $"r.score", $"l.*").otherwise($"r.*"))

any idea how to circumvent this?

Body:
You can return struct:

import org.apache.spark.sql.struct

when($"l.score" > $"r.score", struct($"l.name", $"l.score"))
  .otherwise(struct($"r.name", "r.score"))

or for all fields:

when($"l.score" > $"r.score", struct($"l.*"))
  .otherwise(struct($"r.*"))


问:
Manipulating large files that are being used
I want to retrieve handles of very large files (hundreds GB to x TB) that are being used by some processes. I am thinking about turning off the running processes for a while then copying them to some specific location. But this approach looks clumsy for a couple of reasons.

Files are too large, so copying them from place to place takes time
on different disk types.

After the file copy process is done, I have to turn on the stopped processes. But what if my users need to load/copy other large
files whose handles the said processes are controling ? I    have to stop them again. I don't want to do this
because they have to do many critical tasks in my machine.

So I have 2 questions,

Please explain that my approach is wrong. What I say above is only
my personal idea, no coding is done yet for any of it.

Are there any methods to clone ~50 large files (1-5 TB) fast (some ten seconds or so) and silently in the background ?

答:
If the original process opens the file in non-sharing mode (seems likely for such large files) you are probably out of luck for doing this without closing that process - or at least getting it to relinquish the file. If it allows at least read sharing I would suggest you use transactional NTFS - despite the warnings on all the docs about that.

Create a KTM transaction manager (via CreateTransactionManager), create a KTM transaction (with CreateTransaction) then use CopyFileTransacted to do the actual copy. Finally commit the transaction (CommitTransaction) and then close all the handles. Doing it this way will ensure that the file is in a consistent state (no partial writes from the original process).

It may also be that the backup API can ignore share mode (I know it can ignore security checks if your process has the appropriate privileges enabled, not sure about sharing).


问:
Import Wizard only partially uploads csv table in MySQL
I'm relatively new to MySQL

I am trying to import a csv table with 25,000 rows and 37 variables into MySQL using the import wizard. The import wizard uploads successfully but only 2483 rows appear. How do I upload the entire csv file?

答: I was able to upload the entire csv file by deleting a few columns. Thank you everyone!</p>


问:
Docker service in swarm fails with error ask: non-zero exit (1)
When we run command  :

```<code>docker service create --name [name] --with-registry-auth image-name
</code>```

Services fails with Error - non-zero exit (1)

docker version - Docker version 1.12.2

答: try docker service logs [name] to get a more detailed message why your service failed.

Body:
When we run command  :

docker service create --name [name] --with-registry-auth image-name

Services fails with Error - non-zero exit (1)

docker version - Docker version 1.12.2


问:
Declarative services in OSGI
I have created a (very) simple test to determine how to send and receive events using Apache Felix.

This is my sender:

```<code>package be.pxl;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;

import java.util.HashMap;

@Component(name = "be.pxl.Publisher", immediate = true)
public class Publisher {

    EventAdmin admin;

    @Activate
    public void run(Object object) {
        System.out.println("IN PUBLISHER");
        Event event = new Event("event", new HashMap<String, Object>());
        System.out.println("\tEVENT: " + event);
        admin.postEvent(event);
        System.out.println("\tADMIN: " + admin);
    }

    @Reference(name="be.pxl.admin", service = EventAdmin.class)
    protected void setEventAdmin(EventAdmin admin) {
        this.admin = admin;
    }

}
</code>```

This is my receiver:

```<code>package be.pxl;

import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import java.util.Dictionary;
import java.util.Hashtable;

@Component(name = "be.pxl.Subscriber", immediate = true)
public class Subscriber implements EventHandler {

    private BundleContext context;

    @Activate
    public void run(Object object) {
        System.out.println("IN SUBSCRIBER");
        System.out.println("\tIN RUN METHOD");
        String[] topics = new String[]{"event"};
        Dictionary props = new Hashtable();
        props.put(EventConstants.EVENT_TOPIC, topics);
        System.out.println("\t\tCONTEXT: " + context);
        context.registerService(EventHandler.class.getName(), this, props);
        System.out.println("\t\tCONTEXT AFTER REGISTERSERVICE: " + context);
    }

    public void handleEvent(Event event) {
        System.out.println("IN SUBSCRIBER");
        String text = event.getProperty("text").toString();
        System.out.println("\tEVENT CALLED: " + text);
    }

    @Reference(name="be.pxl.context", service=BundleContext.class)
    protected void setBundleContex(BundleContext context) {
        this.context = context;
    }

}
</code>```

This is the pom of my sender:

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>be.pxl</groupId>
    <artifactId>EventSender</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.service.event</artifactId>
            <version>1.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.service.component.annotations</artifactId>
            <version>1.3.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.osgi</groupId>
            <artifactId>org.eclipse.osgi.services</artifactId>
            <version>3.2.100.v20100503</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.4.0</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-Vendor>SmartCampus</Bundle-Vendor>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Export-Package>
                            be.pxl.*;version="1.0.0"
                        </Export-Package>
                        <Import-Package>
                            org.osgi.service.component.annotations
                            org.eclipse.osgi.service
                            org.osgi.core
                            org.osgi.service.event
                        </Import-Package>
                        <_dsannotations>*</_dsannotations>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
</code>```

Everything compiles fine. I create it using mvn clean package, then I install this jar file in my apache felix container and start it. However, nothing happens. Nothing get pritns out.

Thanks in advance!

答:
You appear to be most of the way there! As you've identified, Event Admin uses a whiteboard model to receive events. The important thing is that you need to tell the whiteboard which topics you want to listen to, which you do.

%%% Update %%%

Event admin topic names use a hierarchy of tokens separated by / characters. When publishing an event you do so to a specific topic, for example foo/bar/baz. When receiving events the EventHandler will be called for topics that match its registered interest(s). These interests can either be for a specific topic, or they can end with a * to indicate a wildcard match. For example foo/bar/* would receive events sent to foo/bar/baz and events sent to foo/bar/fizzbuzz.

%%% Back to the original %%%

There are, however a couple of issues with your code:

Firstly:

```<code>@Reference(name="be.pxl.context", service=BundleContext.class)
protected void setBundleContex(BundleContext context) {
    this.context = context;
}
</code>```

This is not how you access the BundleContext for your bundle. If you do need a BundleContext then it should be injected as a parameter into your @Activate annotated method. A BundleContext should never be registered as a service (it represents your bundle's private access to the OSGi framework), and it would not surprise me to find that this reference is unsatisfied in your example. You don't actually need the BundleContext however because...

Secondly:

```<code>@Activate
public void run(Object object) {
    System.out.println("IN SUBSCRIBER");
    System.out.println("\tIN RUN METHOD");
    String[] topics = new String[]{"event"};
    Dictionary props = new Hashtable();
    props.put(EventConstants.EVENT_TOPIC, topics);
    System.out.println("\t\tCONTEXT: " + context);
    context.registerService(EventHandler.class.getName(), this, props);
    System.out.println("\t\tCONTEXT AFTER REGISTERSERVICE: " + context);
}
</code>```

This is not the right way to write an activate method (and as a result it may not be being called), nor should you be registering your component as a service here. When you make your class an @Component it will automatically be registered as a service using each directly implemented interface. This means that:

```<code>@Component(name = "be.pxl.Subscriber", immediate = true)
public class Subscriber implements EventHandler {
    ...
}
</code>```

is already an OSGi EventHandler service!

You can add service properties to your component using the @Component annotation, or from the OSGi R7 release (due in a couple of months) using Component Property annotations. In this case you want to set your event.topics property like this:

```<code>@Component(property="event.topics=event")
</code>```

You can then get rid of the activate method completely if you like.

Finally:

Event Admin is not a message queue, and your publisher is a one-shot send. Therefore if your publisher sends the event before the handler is fully registered then it will never receive the event. Consider making the publisher send periodic events, or be certain that the receiver starts before the publisher so that you see the message.

P.S.

It's not technically a problem, but I see that you're using version 2.4 of the maven-bundle-plugin. This is very old and the current released version of bnd is 3.5.0. The Bnd team have also started providing their own Maven plugins (such as the bnd-maven-plugin) that you might want to look at.

Title: Declarative services in OSGI

Body:
I have created a (very) simple test to determine how to send and receive events using Apache Felix.

This is my sender:

package be.pxl;

import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;

import java.util.HashMap;

@Component(name = "be.pxl.Publisher", immediate = true)
public class Publisher {

    EventAdmin admin;

    @Activate
    public void run(Object object) {
        System.out.println("IN PUBLISHER");
        Event event = new Event("event", new HashMap<String, Object>());
        System.out.println("\tEVENT: " + event);
        admin.postEvent(event);
        System.out.println("\tADMIN: " + admin);
    }

    @Reference(name="be.pxl.admin", service = EventAdmin.class)
    protected void setEventAdmin(EventAdmin admin) {
        this.admin = admin;
    }

}

This is my receiver:

package be.pxl;

import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import java.util.Dictionary;
import java.util.Hashtable;

@Component(name = "be.pxl.Subscriber", immediate = true)
public class Subscriber implements EventHandler {

    private BundleContext context;

    @Activate
    public void run(Object object) {
        System.out.println("IN SUBSCRIBER");
        System.out.println("\tIN RUN METHOD");
        String[] topics = new String[]{"event"};
        Dictionary props = new Hashtable();
        props.put(EventConstants.EVENT_TOPIC, topics);
        System.out.println("\t\tCONTEXT: " + context);
        context.registerService(EventHandler.class.getName(), this, props);
        System.out.println("\t\tCONTEXT AFTER REGISTERSERVICE: " + context);
    }

    public void handleEvent(Event event) {
        System.out.println("IN SUBSCRIBER");
        String text = event.getProperty("text").toString();
        System.out.println("\tEVENT CALLED: " + text);
    }

    @Reference(name="be.pxl.context", service=BundleContext.class)
    protected void setBundleContex(BundleContext context) {
        this.context = context;
    }

}

This is the pom of my sender:

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>be.pxl</groupId>
    <artifactId>EventSender</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.service.event</artifactId>
            <version>1.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
            <version>6.0.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.service.component.annotations</artifactId>
            <version>1.3.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.eclipse.osgi</groupId>
            <artifactId>org.eclipse.osgi.services</artifactId>
            <version>3.2.100.v20100503</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>2.4.0</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-Vendor>SmartCampus</Bundle-Vendor>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Export-Package>
                            be.pxl.*;version="1.0.0"
                        </Export-Package>
                        <Import-Package>
                            org.osgi.service.component.annotations
                            org.eclipse.osgi.service
                            org.osgi.core
                            org.osgi.service.event
                        </Import-Package>
                        <_dsannotations>*</_dsannotations>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

Everything compiles fine. I create it using mvn clean package, then I install this jar file in my apache felix container and start it. However, nothing happens. Nothing get pritns out.

Thanks in advance!

Body:
You appear to be most of the way there! As you've identified, Event Admin uses a whiteboard model to receive events. The important thing is that you need to tell the whiteboard which topics you want to listen to, which you do.

%%% Update %%%

Event admin topic names use a hierarchy of tokens separated by / characters. When publishing an event you do so to a specific topic, for example foo/bar/baz. When receiving events the EventHandler will be called for topics that match its registered interest(s). These interests can either be for a specific topic, or they can end with a * to indicate a wildcard match. For example foo/bar/* would receive events sent to foo/bar/baz and events sent to foo/bar/fizzbuzz.

%%% Back to the original %%%

There are, however a couple of issues with your code:

Firstly:

@Reference(name="be.pxl.context", service=BundleContext.class)
protected void setBundleContex(BundleContext context) {
    this.context = context;
}

This is not how you access the BundleContext for your bundle. If you do need a BundleContext then it should be injected as a parameter into your @Activate annotated method. A BundleContext should never be registered as a service (it represents your bundle's private access to the OSGi framework), and it would not surprise me to find that this reference is unsatisfied in your example. You don't actually need the BundleContext however because...

Secondly:

@Activate
public void run(Object object) {
    System.out.println("IN SUBSCRIBER");
    System.out.println("\tIN RUN METHOD");
    String[] topics = new String[]{"event"};
    Dictionary props = new Hashtable();
    props.put(EventConstants.EVENT_TOPIC, topics);
    System.out.println("\t\tCONTEXT: " + context);
    context.registerService(EventHandler.class.getName(), this, props);
    System.out.println("\t\tCONTEXT AFTER REGISTERSERVICE: " + context);
}

This is not the right way to write an activate method (and as a result it may not be being called), nor should you be registering your component as a service here. When you make your class an @Component it will automatically be registered as a service using each directly implemented interface. This means that:

@Component(name = "be.pxl.Subscriber", immediate = true)
public class Subscriber implements EventHandler {
    ...
}

is already an OSGi EventHandler service!

You can add service properties to your component using the @Component annotation, or from the OSGi R7 release (due in a couple of months) using Component Property annotations. In this case you want to set your event.topics property like this:

@Component(property="event.topics=event")

You can then get rid of the activate method completely if you like.

Finally:

Event Admin is not a message queue, and your publisher is a one-shot send. Therefore if your publisher sends the event before the handler is fully registered then it will never receive the event. Consider making the publisher send periodic events, or be certain that the receiver starts before the publisher so that you see the message.

P.S.

It's not technically a problem, but I see that you're using version 2.4 of the maven-bundle-plugin. This is very old and the current released version of bnd is 3.5.0. The Bnd team have also started providing their own Maven plugins (such as the bnd-maven-plugin) that you might want to look at.


问:
Not matched rows in B join with some row in A
Example data:

```<code>Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A
</code>```

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

```<code>x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1
</code>```

答:
Here is one solution. See if this helps!

```<code>WITH v_t2 AS
(SELECT y, COUNT(*) AS cnt
   FROM table2 t2
  GROUP BY t2.y
),
v_t2_null AS
(SELECT COUNT(*) AS cnt
   FROM table2 t2
  WHERE NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t1.y= t2.y)
)
SELECT t1.x. t1.y, COALESCE(t2.cnt, v_t2_null.cnt)
  FROM table1 t1 LEFT JOIN v_t2 t2
                   ON (t1.y = t2.y)
                 JOIN v_t2_null;
</code>```

Output

```<code>    x   y   cnt
    1   A   2
    1   B   0
    1   V   0
    1   NULL    1
    2   M   2
    2   N   1
</code>```

Body:
Example data:

Table1     Table2
x | y      x | y
-----      -----
1 | A      1 | A
1 | B      1 | D
1 | C      2 | M
1 | null   2 | N
2 | M      2 | M
2 | N      1 | A

I want to count number of x's in Table2 and join it with Table1. But in Table2 I can have y's which doesn't match to y's in Table1. In this case I want to join them with row with null in y column in Table1.
In an example Table2.1-D should be joined with Tabl1.1-null

For given example I expect the result:

x | y    | count
-----------------
1 | A    | 2
1 | B    | 0
1 | C    | 0
1 | null | 1 (because D doesn't match to anything else in Table1)
2 | M    | 2
2 | N    | 1

Body:
Here is one solution. See if this helps!

WITH v_t2 AS
(SELECT y, COUNT(*) AS cnt
   FROM table2 t2
  GROUP BY t2.y
),
v_t2_null AS
(SELECT COUNT(*) AS cnt
   FROM table2 t2
  WHERE NOT EXISTS (SELECT 1 FROM table1 t1 WHERE t1.y= t2.y)
)
SELECT t1.x. t1.y, COALESCE(t2.cnt, v_t2_null.cnt)
  FROM table1 t1 LEFT JOIN v_t2 t2
                   ON (t1.y = t2.y)
                 JOIN v_t2_null;

Output

    x   y   cnt
    1   A   2
    1   B   0
    1   V   0
    1   NULL    1
    2   M   2
    2   N   1


问:
load variables from in memory setting file
i have settings.py file that looks like:

```<code>DEBUG = True
CACHE_IP = '0.0.0.0'
DB_SETTINGS = {
    'SERVERS': ['127.0.0.1:80'],
    'MAX_IDLE_TIME' : 180,
}
</code>```

this file is stored at external cloud storage.

I have a process the get the url to this file, and load it into memory (not to disk). when loading it into memory it will be string type and looks like:

```<code>"DEBUG = True\n CACHE_IP = '0.0.0.0'\n DB_SETTINGS = {\n    'SERVERS': ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n"
</code>```

How for example i can get the values from this string? i mean, how can i get a dictionary where key=verb name from file, and value = value from file? is there any pythonic way for this?

so my dictionary will look like:

```<code>{'DEBUG': True, 'CACHE_IP' = '0.0.0.0', 'DB_SETTINGS': {...}}
</code>```

答:
One way is to use the eval function to execute the text.

```<code>eval("DEBUG = True\n CACHE_IP = '0.0.0.0'\n DB_SETTINGS = {\n    'SERVERS':       ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n")
settings_dict = {}
settings_dict['DEBUG'] = DEBUG
settings_dict['CACHE_IP'] = DEBUG
settings_dict['DB_SETTINGS'] = DB_SETTINGS
</code>```

I don't know of a way to 'automate' the dictionary creation.

Body:
i have settings.py file that looks like:

DEBUG = True
CACHE_IP = '0.0.0.0'
DB_SETTINGS = {
    'SERVERS': ['127.0.0.1:80'],
    'MAX_IDLE_TIME' : 180,
}

this file is stored at external cloud storage.

I have a process the get the url to this file, and load it into memory (not to disk). when loading it into memory it will be string type and looks like:

"DEBUG = True\n CACHE_IP = '0.0.0.0'\n DB_SETTINGS = {\n    'SERVERS': ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n"

How for example i can get the values from this string? i mean, how can i get a dictionary where key=verb name from file, and value = value from file? is there any pythonic way for this?

so my dictionary will look like:

{'DEBUG': True, 'CACHE_IP' = '0.0.0.0', 'DB_SETTINGS': {...}}

Body:
One way is to use the eval function to execute the text.

eval("DEBUG = True\n CACHE_IP = '0.0.0.0'\n DB_SETTINGS = {\n    'SERVERS':       ['127.0.0.1:80'],\n    'MAX_IDLE_TIME' : 180,\n}\n")
settings_dict = {}
settings_dict['DEBUG'] = DEBUG
settings_dict['CACHE_IP'] = DEBUG
settings_dict['DB_SETTINGS'] = DB_SETTINGS

I don't know of a way to 'automate' the dictionary creation.


问:
Rails has_many through with where condition
I have the following associations in my Survey model:

```<code>has_many :survey_group_lists, -> { order 'sequence ASC, group_id ASC' }
has_many :groups, through: :survey_group_lists
</code>```

I want to add where cluase to :groups association so it will return only active groups. I've tried something like this:

```<code>has_many :groups, -> { where(active: true) }, through: :survey_group_lists
</code>```

but it returns me an error:

```<code>ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "slide_groups"
</code>```

What I'm doing wrong?

Edit: I'm using Rails 5.

答:
It should be:</p>

```<code>has_many :groups, through: :survey_group_lists, -> { where(groups: { active: true } ) }
</code>```

Body:
I have the following associations in my Survey model:

has_many :survey_group_lists, -> { order 'sequence ASC, group_id ASC' }
has_many :groups, through: :survey_group_lists

I want to add where cluase to :groups association so it will return only active groups. I've tried something like this:

has_many :groups, -> { where(active: true) }, through: :survey_group_lists

but it returns me an error:

ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "slide_groups"

What I'm doing wrong?

Edit: I'm using Rails 5.

Body:
It should be:

has_many :groups, through: :survey_group_lists, -> { where(groups: { active: true } ) }


问:
Referencing Embedded resources from other resources in c#
In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using ClientScriptManager.GetWebResourceUrl(). However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.

```<code>this.drophint = document.createElement('img');
this.drophint.src = '/_layouts/images/dragdrophint.gif';
</code>```

Could become something like:

```<code>this.drophint = document.createElement('img');
this.drophint.src = '{resource:assembly.location.dragdrophint.gif}';
</code>```

答:
I don't particularly care for the exact implementation @Jon suggests, but the idea behind it is sound and I would concur that emitting these would be a good thing to do.

A slightly better implementation, though this is all subjective to some degree, would be to create a server-side model (read: C# class(es)) that represents this dictionary (or simply use an instance of Dictionary<string, string>) and serialize that to JavaScript literal object notation. That way you are not dealing with the string hacking you see in Jon's example (if that bothers you).

OwnerDisplayName: Rex M

ContentLicense: CC BY-SA 2.5

Body:
In my web application I include all of my JavaScripts as js files that are embedded resources in the assembly, and add them to the page using ClientScriptManager.GetWebResourceUrl(). However, in some of my js files, I have references to other static assets like image urls. I would like to make those assembly resources as well. Is there a way to tokenize the reference to the resource? e.g.

this.drophint = document.createElement('img');
this.drophint.src = '/_layouts/images/dragdrophint.gif';

Could become something like:

this.drophint = document.createElement('img');
this.drophint.src = '{resource:assembly.location.dragdrophint.gif}';

OwnerDisplayName: JasonBunting


问:
Preserve Line Breaks During Sort
This isn't necessarily PHP-specific, although I'm using PHP.  I guess I'm looking for a creative solution.

Say I have a list of terms in a textarea that are separated by an extra new line, for instance:

```<code>Cookie

Apple

Banana
</code>```

I want to sort() these terms and display them after page submit, so that the results look like:

```<code>Apple

Banana

Cookie
</code>```

and not like

```<code>Apple
Banana
Cookie
</code>```

(which would be preceded by two blank lines)

Anyone have any suggestions on how that might be possible?

Sorry, I should have been more clear.  The list in the textarea is entered by a user so it may or may not already contain extra newlines.

答:
Including the newlines, every array should have an odd number of elements, so the integer value of array.length / 2 should always yield the number of newlines, and should also yield the index of the first word in a 0-indexed language.

For the number of words in the array (i.e. from array.length / 2 to the end of the array, exclusive), you could print the word and print whatever is at the word's index - the array.length / 2, which should be a newline, until the last word. The newline should not be printed afterward if the index is of the last word.

Title: Preserve Line Breaks During Sort

Body:
This isn't necessarily PHP-specific, although I'm using PHP.  I guess I'm looking for a creative solution.

Say I have a list of terms in a textarea that are separated by an extra new line, for instance:

Cookie

Apple

Banana

I want to sort() these terms and display them after page submit, so that the results look like:

Apple

Banana

Cookie

and not like

Apple
Banana
Cookie

(which would be preceded by two blank lines)

Anyone have any suggestions on how that might be possible?

Sorry, I should have been more clear.  The list in the textarea is entered by a user so it may or may not already contain extra newlines.


问:
why this code doesn't work i am using python3?
I wanna delete the values of the list

```<code>lists = [12,15,15,15,3,15,1,6,4,7,888,56248]
while len(lists) is True:
    lists.pop()
print(lists)
</code>```

But i got this output :

```<code>[12, 15, 15, 15, 3, 15, 1, 6, 4, 7, 888, 56248]
</code>```

答:
If by "delete" you mean removing the element and reducing the list, you can iterate through a copy of lists with a for loop:

```<code>for n in lists[:]:
    lists.remove(n)
</code>```

If, instead, you want to have a list of None (or 0) values as long as lists, you can do it like this:

```<code>newlists = [0] * len(lists)
</code>```

As was suggested in the previous comment.

Body:
I wanna delete the values of the list

lists = [12,15,15,15,3,15,1,6,4,7,888,56248]
while len(lists) is True:
    lists.pop()
print(lists)

But i got this output :

[12, 15, 15, 15, 3, 15, 1, 6, 4, 7, 888, 56248]

Body:
If by "delete" you mean removing the element and reducing the list, you can iterate through a copy of lists with a for loop:

for n in lists[:]:
    lists.remove(n)

If, instead, you want to have a list of None (or 0) values as long as lists, you can do it like this:

newlists = [0] * len(lists)

As was suggested in the previous comment.


问:
iOS 11 presentViewController going behind presenting controller
I am having a strange issue where I am just doing a simple presenting modal view controller. MFMailComposeViewController to be exact. However, it is appearing behind the presenting controller and thus you can not send any email or type. You can see the "Cancel" button on the UINavigationBar on the mail composer, but that pops the UIAlertController behind the presenting controller. How has this happened? Is it an iOS 11 issue? I am also getting similar behaviour for UIAlertControllers too.

Also, if I press send and press my button to pop up another Composer, it works as normal. It is just the first one.

Please see attached image I got from Xcode.

```<code>MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
mailer.modalPresentationStyle = UIModalPresentationFormSheet;
[mailer setSubject:@"subject Feedback"];
[mailer setToRecipients:@[@"email address"]];
[mailer setMessageBody:@"" isHTML:NO];
[self presentViewController:mailer animated:YES completion:nil];
</code>```

Edit: Adding the controller for more information.

```<code>#import "AboutViewController.h"
#import <MessageUI/MessageUI.h>

@interface AboutViewController () <MFMailComposeViewControllerDelegate>
@property (nonatomic, strong) IBOutlet UIView *contentView;
@end

@implementation AboutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"About this app";
    _contentView.layer.cornerRadius = 10.;
    _contentView.layer.shadowColor = [UIColor blackColor].CGColor;
    _contentView.layer.shadowRadius = 3.;
    _contentView.layer.shadowOpacity = 0.4;
    _contentView.layer.shadowOffset = CGSizeMake(3., 3.);
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sendFeedbackEmail:(id)sender {
    if ([MFMailComposeViewController canSendMail]){
        dispatch_async(dispatch_get_main_queue(), ^{
            MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
            mailer.mailComposeDelegate = self;
            mailer.modalPresentationStyle = UIModalPresentationFormSheet;
            [mailer setSubject:@"Feedback"];
            [mailer setToRecipients:@[@"email@email.com"]];
            [mailer setMessageBody:@"" isHTML:NO];
            [self presentViewController:mailer animated:YES completion:nil];

        });
    } else {
        NSLog(@"Nope");
    }
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    [controller dismissViewControllerAnimated:YES completion:nil];
}
</code>```

Edit 2:

I believe I have found the answer. I hope this may help anyone who encounter the same issue. Thank you for all the replies, it helped me find the answer. Thank you @Mert Buran for the delegate idea. This showed me that it had a different transition delegate the first time and the one I wanted the second time.

The issue was that the navigationController pushed the new controller before dismissing a controller I had on top (a menu controller). A simple fix but because it is not evident at the start and no error logs, it was difficult to pin point.

答: I would try self.definesPresentationContext = YES in your viewDidLoad.  See https://developer.apple.com/documentation/uikit/uiviewcontroller/1621456-definespresentationcontext

Body:
I am having a strange issue where I am just doing a simple presenting modal view controller. MFMailComposeViewController to be exact. However, it is appearing behind the presenting controller and thus you can not send any email or type. You can see the "Cancel" button on the UINavigationBar on the mail composer, but that pops the UIAlertController behind the presenting controller. How has this happened? Is it an iOS 11 issue? I am also getting similar behaviour for UIAlertControllers too.

Also, if I press send and press my button to pop up another Composer, it works as normal. It is just the first one.

Please see attached image I got from Xcode.

MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
mailer.mailComposeDelegate = self;
mailer.modalPresentationStyle = UIModalPresentationFormSheet;
[mailer setSubject:@"subject Feedback"];
[mailer setToRecipients:@[@"email address"]];
[mailer setMessageBody:@"" isHTML:NO];
[self presentViewController:mailer animated:YES completion:nil];

Edit: Adding the controller for more information.

#import "AboutViewController.h"
#import <MessageUI/MessageUI.h>

@interface AboutViewController () <MFMailComposeViewControllerDelegate>
@property (nonatomic, strong) IBOutlet UIView *contentView;
@end

@implementation AboutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"About this app";
    _contentView.layer.cornerRadius = 10.;
    _contentView.layer.shadowColor = [UIColor blackColor].CGColor;
    _contentView.layer.shadowRadius = 3.;
    _contentView.layer.shadowOpacity = 0.4;
    _contentView.layer.shadowOffset = CGSizeMake(3., 3.);
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)sendFeedbackEmail:(id)sender {
    if ([MFMailComposeViewController canSendMail]){
        dispatch_async(dispatch_get_main_queue(), ^{
            MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
            mailer.mailComposeDelegate = self;
            mailer.modalPresentationStyle = UIModalPresentationFormSheet;
            [mailer setSubject:@"Feedback"];
            [mailer setToRecipients:@[@"email@email.com"]];
            [mailer setMessageBody:@"" isHTML:NO];
            [self presentViewController:mailer animated:YES completion:nil];

        });
    } else {
        NSLog(@"Nope");
    }
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error
{
    [controller dismissViewControllerAnimated:YES completion:nil];
}

Edit 2:

I believe I have found the answer. I hope this may help anyone who encounter the same issue. Thank you for all the replies, it helped me find the answer. Thank you @Mert Buran for the delegate idea. This showed me that it had a different transition delegate the first time and the one I wanted the second time.

The issue was that the navigationController pushed the new controller before dismissing a controller I had on top (a menu controller). A simple fix but because it is not evident at the start and no error logs, it was difficult to pin point.


问:
time complexity of two nested loops
I'm studying algorithms and I've met a problem, that I can't solve.

```<code>for(int i = 0; i < n; i++)
    for( int j = 0; j < i; j++)
        sum++;
</code>```

So, time complexity of this code is n^2. But. First loop is iterating n times and I understand that. But second one is iterating n(n+1)/2. So.. It becomes n*(n(n+1))/2. Where I went wrong?

答:
First thing you need to understand Big-O notation. It throws all lower order terms and keeps only the highest N.

Your outer loop runs N times ,so the highest term is n and what is the highest value for inner loop? It's (n-1).

So for Nth iteration of outer loop, you get n-1 iteration for inner loop which is N(N-1)  = (N^2 - N) and with big-O it's O(N^2)

Title: time complexity of two nested loops

Body:
I'm studying algorithms and I've met a problem, that I can't solve.

for(int i = 0; i < n; i++)
    for( int j = 0; j < i; j++)
        sum++;

So, time complexity of this code is n^2. But. First loop is iterating n times and I understand that. But second one is iterating n(n+1)/2. So.. It becomes n*(n(n+1))/2. Where I went wrong?


问:
Session, cookies and ids
It was suggested to me to use sessions for cross page storage, and maintain the session ID by storing it in a GET parameter or cookie.

What's the safest way to save data into a session and make it last forever (like login informations)?

答:
Not sure I entirely understand your question, but you may be mixing up two things. The sid GET parameter is used as a fallback session ID when cookies are disabled. Both the GET parameter and the cookie do the same thing, but storing the session ID in the cookie doesn't clutter the URL, which is why this is the preferred method.

When you store session data using $_SESSION in PHP, the data gets stored only internally. It is not transmitted to the user's browser. Only the cookie (or sid) containing the session ID ever leaves the server.

Title: Session, cookies and ids


问:
Delete files in a directory using Chef
I want to delete all files in a directory without deleting the directory itself.

Also, I don't want to use a execute block. If I use the following resource all the files along with the directory are deleted.

Code:

```<code>directory "/path/to/somedir/" do
      recursive true
      action :delete
end
</code>```

答: We don’t have a resource for this in Chef core. Sorry :( You can either use a ruby_block and some fancy FileUtils code or an execute.</p>

Title: Delete files in a directory using Chef

Body:
I want to delete all files in a directory without deleting the directory itself.

Also, I don't want to use a execute block. If I use the following resource all the files along with the directory are deleted.

Code:

directory "/path/to/somedir/" do
      recursive true
      action :delete
end


问:
Type lacks a call signature
I am not sure what I am missing, but I have a function that looks like this:

```<code>export default function (config: DatabaseConnections<DatabaseConnection>) {
  return DB['connect'](config, throwError)
}
</code>```

When I try to use the function (in my js test case), I would like to use it like this:

```<code>const db = require('../lib/DB')
db({
  master: {
    host: 'abc123',
    user: 'abc123',
    password: 'abc123',
    database: 'abc123'
  }
})
</code>```

However, when I do that I get the error:

Cannot invoke an expression whose type lacks a call signature.

When I call it like this db.default({...}) it works. How can I get it to export the function so I can call it like this db({...})?

答:
There are a few ways to fix this

Simple fix

You can try grabbing the default off the require:

```<code>const db = require('../lib/DB').default;
</code>```

Named Function Fixes

You could also try naming the function rather than relying on the default.

In your DB file, try:

```<code>export default function db (...)
</code>```

and then in your test file:

```<code>const db = require('../lib/DB').db;
</code>```

You can also name and export only the specific function, rather than using a default.

A la:

```<code>function db(...){ }
module.exports=db;
</code>```

And then in your test file:

```<code>const db = require('../lib/DB');
</code>```

Bonus Return Type Fix

Since the db function returns a value, you need to define a return type on the function.

```<code>export default function (config: DatabaseConnections<DatabaseConnection>):DB {
  return DB['connect'](config, throwError);
}
</code>```

Title: Type lacks a call signature

Body:
I am not sure what I am missing, but I have a function that looks like this:

export default function (config: DatabaseConnections<DatabaseConnection>) {
  return DB['connect'](config, throwError)
}

When I try to use the function (in my js test case), I would like to use it like this:

const db = require('../lib/DB')
db({
  master: {
    host: 'abc123',
    user: 'abc123',
    password: 'abc123',
    database: 'abc123'
  }
})

However, when I do that I get the error:

Cannot invoke an expression whose type lacks a call signature.

When I call it like this db.default({...}) it works. How can I get it to export the function so I can call it like this db({...})?

Body:
There are a few ways to fix this

Simple fix

You can try grabbing the default off the require:

const db = require('../lib/DB').default;

Named Function Fixes

You could also try naming the function rather than relying on the default.

In your DB file, try:

export default function db (...)

and then in your test file:

const db = require('../lib/DB').db;

You can also name and export only the specific function, rather than using a default.

A la:

function db(...){ }
module.exports=db;

And then in your test file:

const db = require('../lib/DB');

Bonus Return Type Fix

Since the db function returns a value, you need to define a return type on the function.

export default function (config: DatabaseConnections<DatabaseConnection>):DB {
  return DB['connect'](config, throwError);
}


问:
Highcharts mouse tracking/mouseover feature is slow on chrome but not slow in firefox or IE
We have a webapp built using Codeigniter and PHP which uses the Highcharts library and javascript/html on the client side and is deployed on IIS.

The Highcharts library renders various charts on a screen, 5 to be precise. Each chart renders data having not more than 1000 rows.

The charts are plotted fine, but when the mouse is hovered around the chart, the mouse over is displayed in frames(only on chrome). Please see image below showing the frame lags caused by mouse tracking.

Surprisingly this behavior is observed only on chrome but not in IE or firefox.

Can anybody help by suggesting how to overcome this bad mouse tracking on chrome. Highcharts has a mouse tracker disable option, but we loose interactivity and mouse over features if it is disabled.

Any help to overcome this or improve the mouseover frame rendering on chrome will be deeply appreciated.

Using Highcharts version 2.0.4 , Now updated to latest version 4.0.4

Tooltip code is below, using the basic tooltip option for box and area chart.

```<code>tooltip: {
            formatter: function() {
                        return 'The value for <b>' + this.x + '</b> is <b>' + this.y + '</b>, in series '+ this.series.name;
                       //return "hello";
             }
        }
</code>```

答:
This was a bug in Webkit.  Here is the official, Chromium bug report :

Bugs.Webkit : hover over table rows causes the whole table to repaint

This was fixed per the 2014-11-14 08:53:09 PST update of Webkit, as noted in the ticket above.  This is only two months after the post by the OP.

If you are still having problems, for instance with drag and drop (like I am), then look at this bug report, still active and unresolved :

Bugs.Chromium : Drag and drop performance issue when using "position:relative" style with many cells

It has been active since:  Mar 31 2014

What is the expected result?

When the dragged object is over a cell, the cell should have a red background.

What happens instead?

Drag and drop is very slow.

Cells are sometimes displayed in red, but after a few seconds.

Cursor pointer is not available during half a second after the drag end.

Body:
We have a webapp built using Codeigniter and PHP which uses the Highcharts library and javascript/html on the client side and is deployed on IIS.

The Highcharts library renders various charts on a screen, 5 to be precise. Each chart renders data having not more than 1000 rows.

The charts are plotted fine, but when the mouse is hovered around the chart, the mouse over is displayed in frames(only on chrome). Please see image below showing the frame lags caused by mouse tracking.

Surprisingly this behavior is observed only on chrome but not in IE or firefox.

Can anybody help by suggesting how to overcome this bad mouse tracking on chrome. Highcharts has a mouse tracker disable option, but we loose interactivity and mouse over features if it is disabled.

Any help to overcome this or improve the mouseover frame rendering on chrome will be deeply appreciated.

Using Highcharts version 2.0.4 , Now updated to latest version 4.0.4

Tooltip code is below, using the basic tooltip option for box and area chart.

tooltip: {
            formatter: function() {
                        return 'The value for ' + this.x + ' is ' + this.y + ', in series '+ this.series.name;
                       //return "hello";
             }
        }

ContentLicense: CC BY-SA 4.0


问:
Extract user information from the build
Jenkins ver. 2.73.3

I have a sample build task that is triggered by a commit to a Github repository. This is how the build information looks:

We need to write this username to a separate file and store it in a particular location. How can I achieve it?

**********Edit-1**********
Added a build step that executes a shell command to write the variable GIT_COMMITTER_NAME to a file. This fails(empty file) but if I write, say JENKINS_URL, it is written to the file:

答:
I guess the github plugin doesn't set, by default, the variables like GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL etc.
Taking a cue from this answer, I proceeded with using the placeholders of the 'pretty option' of git show command. I added the following command in the 'Execute Shell' build step of Jenkins job:

```<code>git show -s --pretty='GIT_AUTHOR_NAME='%aN%n'GIT_AUTHOR_EMAIL='%aE%n'GIT_COMMITTER_NAME='%cN%n'GIT_COMMITTER_EMAIL='%cE >> github.properties
</code>```

The output:

```<code>GIT_AUTHOR_NAME=LastName FirstName
GIT_AUTHOR_EMAIL=FirstName.LastName@company.com
GIT_COMMITTER_NAME=GitHub Enterprise
GIT_COMMITTER_EMAIL=noreply@github.company.com
</code>```

Title: Extract user information from the build

Body:
I guess the github plugin doesn't set, by default, the variables like GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL etc.
Taking a cue from this answer, I proceeded with using the placeholders of the 'pretty option' of git show command. I added the following command in the 'Execute Shell' build step of Jenkins job:

git show -s --pretty='GIT_AUTHOR_NAME='%aN%n'GIT_AUTHOR_EMAIL='%aE%n'GIT_COMMITTER_NAME='%cN%n'GIT_COMMITTER_EMAIL='%cE >> github.properties

The output:

GIT_AUTHOR_NAME=LastName FirstName
GIT_AUTHOR_EMAIL=FirstName.LastName@company.com
GIT_COMMITTER_NAME=GitHub Enterprise
GIT_COMMITTER_EMAIL=noreply@github.company.com


问:
Toggle QPen for selected items after QGraphicsScene selection change
How can I toggle the QPen color for the selected graphicsview items? Ideally I would like to handle this color change in the graphicsview or graphics scene objects rather than directly handling it in the main windows selection event.

Any help is appreciated. Currently it will turn the pen color white when the object is selected. I'm not sure how to turn it back avoiding looping through all objects.

Is there a way i could add a function in the MyGraphicsView class itself that would handle the color change of the pen for any and all selected items in the graph?

Update: More detailed information
Here is a list of the selection issues I'm trying to resolve:

When a user clicks and makes a selection rectangle it should deselect all items, restoring them to their default Pen color. The newly selected items should have a white Pen color. If the user is holding control it should add the newly selected items. If items are already selected and the rectangle crosses over them, it should still keep them selected.

If a user clicks in a negative area where no item appears under the cursor, it should clear the current selection.

If a user clicks on an item it should select it and make the Pen color white.

If the user is holding control it should always add to the selection.

Code

```<code>import sys
from PySide.QtGui import *
from PySide.QtCore import *
import random

class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        self.setDragMode(QGraphicsView.RubberBandDrag)
        self._isPanning = False
        self._mousePressed = False
        # self.setBackgroundBrush(QImage("C:/Users/jmartini/Desktop/Temp/images/flag_0140.jpg"))
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
        self.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff )

    def mousePressEvent(self,  event):
        if event.button() == Qt.LeftButton:
            self._mousePressed = True
            if self._isPanning:
                self.setCursor(Qt.ClosedHandCursor)
                self._dragPos = event.pos()
                event.accept()
            else:
                super(MyGraphicsView, self).mousePressEvent(event)
        elif event.button() == Qt.MiddleButton:
            self._mousePressed = True
            self._isPanning = True
            self.setCursor(Qt.ClosedHandCursor)
            self._dragPos = event.pos()
            event.accept()

    def mouseMoveEvent(self, event):
        if self._mousePressed and self._isPanning:
            newPos = event.pos()
            diff = newPos - self._dragPos
            self._dragPos = newPos
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - diff.x())
            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - diff.y())
            event.accept()
        else:
            super(MyGraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            if self._isPanning:
                self.setCursor(Qt.OpenHandCursor)
            else:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        elif event.button() == Qt.MiddleButton:
            self._isPanning = False
            self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        super(MyGraphicsView, self).mouseReleaseEvent(event)

    def mouseDoubleClickEvent(self, event):
        self.fitInView(self.sceneRect(), Qt.KeepAspectRatio)
        pass

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space and not self._mousePressed:
            self._isPanning = True
            self.setCursor(Qt.OpenHandCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Space:
            if not self._mousePressed:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def wheelEvent(self,  event):
        # zoom factor
        factor = 1.25

        # Set Anchors
        self.setTransformationAnchor(QGraphicsView.NoAnchor)
        self.setResizeAnchor(QGraphicsView.NoAnchor)

        # Save the scene pos
        oldPos = self.mapToScene(event.pos())

        # Zoom
        if event.delta() < 0:
            factor = 1.0 / factor
        self.scale(factor, factor)

        # Get the new position
        newPos = self.mapToScene(event.pos())

        # Move scene to old position
        delta = newPos - oldPos
        self.translate(delta.x(), delta.y())

class MyGraphicsScene(QGraphicsScene):
    def __init__(self,  parent):
        super(MyGraphicsScene,  self).__init__()
        self.setBackgroundBrush(QBrush(QColor(50,50,50)))
        # self.setSceneRect(50,50,0,0)

class MyMainWindow(QMainWindow):
    def __init__(self):
        super(MyMainWindow, self).__init__()
        self.setWindowTitle("Test")
        self.resize(800,600)

        self.gv = MyGraphicsView()
        self.gv.setScene(MyGraphicsScene(self))
        self.setCentralWidget(self.gv)

        self.gv.scene().selectionChanged.connect(self.selection_changed)
        self.populate()

    def populate(self):
        scene = self.gv.scene()

        for i in range(500):
            x = random.randint(0, 1000)
            y = random.randint(0, 1000)
            r = random.randint(2, 8)
            rect = scene.addEllipse(x, y, r, r, QPen(QColor(255,128,0), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin), QBrush(QColor(255,128,20,128)))
            rect.setFlag( QGraphicsItem.ItemIsSelectable )
            rect.setFlag( QGraphicsItem.ItemIsMovable )

        rect = scene.addEllipse(300, 500, 20, 20, QPen(QColor(255,128,0), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin), QBrush(QColor(255,0,0,128)))
        rect.setFlag( QGraphicsItem.ItemIsSelectable )
        rect.setFlag( QGraphicsItem.ItemIsMovable )

    def selection_changed(self):
        selection = self.gv.scene().selectedItems()
        print 'Selected:', len(selection)
        for i in selection:
            i.setPen(QPen(QColor(255,255,255), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))

def main():
    app = QApplication(sys.argv)
    ex = MyMainWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

答:
It should be possible to get the required behaviour by caching the last selection and then clearing it before making the new selection:

```<code>class MyGraphicsView(QGraphicsView):
    def __init__(self):
        ...
        self.setScene(MyGraphicsScene(self))
        self.scene().selectionChanged.connect(self.selection_changed)
        self._current_selection = []

    def select_items(self, items, on):
        pen = QPen(QColor(255, 255, 255) if on else QColor(255, 128, 0),
                   0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
        for item in items:
            item.setPen(pen)

    def selection_changed(self):
        try:
            self.select_items(self._current_selection, False)
            self._current_selection = self.scene().selectedItems()
            self.select_items(self._current_selection, True)
        except RuntimeError:
            pass
</code>```

Here is the complete script:

```<code>import sys
from PySide.QtGui import *
from PySide.QtCore import *
import random

class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        self.setDragMode(QGraphicsView.RubberBandDrag)
        self._isPanning = False
        self._mousePressed = False
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
        self.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
        self.setScene(MyGraphicsScene(self))
        self.scene().selectionChanged.connect(self.selection_changed)
        self._current_selection = []

    def select_items(self, items, on):
        pen = QPen(QColor(255, 255, 255) if on else QColor(255, 128, 0),
                   0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
        for item in items:
            item.setPen(pen)

    def selection_changed(self):
        try:
            self.select_items(self._current_selection, False)
            self._current_selection = self.scene().selectedItems()
            self.select_items(self._current_selection, True)
        except RuntimeError:
            pass

    def mousePressEvent(self,  event):
        if event.button() == Qt.LeftButton:
            self._mousePressed = True
            if self._isPanning:
                self.setCursor(Qt.ClosedHandCursor)
                self._dragPos = event.pos()
                event.accept()
            else:
                super(MyGraphicsView, self).mousePressEvent(event)
        elif event.button() == Qt.MiddleButton:
            self._mousePressed = True
            self._isPanning = True
            self.setCursor(Qt.ClosedHandCursor)
            self._dragPos = event.pos()
            event.accept()

    def mouseMoveEvent(self, event):
        if self._mousePressed and self._isPanning:
            newPos = event.pos()
            diff = newPos - self._dragPos
            self._dragPos = newPos
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - diff.x())
            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - diff.y())
            event.accept()
        else:
            super(MyGraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            if self._isPanning:
                self.setCursor(Qt.OpenHandCursor)
            else:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        elif event.button() == Qt.MiddleButton:
            self._isPanning = False
            self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        super(MyGraphicsView, self).mouseReleaseEvent(event)

    def mouseDoubleClickEvent(self, event):
        self.fitInView(self.sceneRect(), Qt.KeepAspectRatio)
        pass

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space and not self._mousePressed:
            self._isPanning = True
            self.setCursor(Qt.OpenHandCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Space:
            if not self._mousePressed:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def wheelEvent(self,  event):
        # zoom factor
        factor = 1.25

        # Set Anchors
        self.setTransformationAnchor(QGraphicsView.NoAnchor)
        self.setResizeAnchor(QGraphicsView.NoAnchor)

        # Save the scene pos
        oldPos = self.mapToScene(event.pos())

        # Zoom
        if event.delta() < 0:
            factor = 1.0 / factor
        self.scale(factor, factor)

        # Get the new position
        newPos = self.mapToScene(event.pos())

        # Move scene to old position
        delta = newPos - oldPos
        self.translate(delta.x(), delta.y())

class MyGraphicsScene(QGraphicsScene):
    def __init__(self,  parent):
        super(MyGraphicsScene,  self).__init__()
        self.setBackgroundBrush(QBrush(QColor(50,50,50)))
        # self.setSceneRect(50,50,0,0)

class MyMainWindow(QMainWindow):
    def __init__(self):
        super(MyMainWindow, self).__init__()
        self.setWindowTitle("Test")
        self.resize(800,600)
        self.gv = MyGraphicsView()
        self.setCentralWidget(self.gv)
        self.populate()

    def populate(self):
        scene = self.gv.scene()
        for i in range(500):
            x = random.randint(0, 1000)
            y = random.randint(0, 1000)
            r = random.randint(2, 8)
            rect = scene.addEllipse(x, y, r, r, QPen(QColor(255,128,0), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin), QBrush(QColor(255,128,20,128)))
            rect.setFlag( QGraphicsItem.ItemIsSelectable )
            rect.setFlag( QGraphicsItem.ItemIsMovable )

        rect = scene.addEllipse(300, 500, 20, 20, QPen(QColor(255,128,0), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin), QBrush(QColor(255,0,0,128)))
        rect.setFlag( QGraphicsItem.ItemIsSelectable )
        rect.setFlag( QGraphicsItem.ItemIsMovable )

def main():
    app = QApplication(sys.argv)
    ex = MyMainWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()
</code>```

Body:
How can I toggle the QPen color for the selected graphicsview items? Ideally I would like to handle this color change in the graphicsview or graphics scene objects rather than directly handling it in the main windows selection event.

Any help is appreciated. Currently it will turn the pen color white when the object is selected. I'm not sure how to turn it back avoiding looping through all objects.

Is there a way i could add a function in the MyGraphicsView class itself that would handle the color change of the pen for any and all selected items in the graph?

Update: More detailed information
Here is a list of the selection issues I'm trying to resolve:

When a user clicks and makes a selection rectangle it should deselect all items, restoring them to their default Pen color. The newly selected items should have a white Pen color. If the user is holding control it should add the newly selected items. If items are already selected and the rectangle crosses over them, it should still keep them selected.

If a user clicks in a negative area where no item appears under the cursor, it should clear the current selection.

If a user clicks on an item it should select it and make the Pen color white.

If the user is holding control it should always add to the selection.

Code

import sys
from PySide.QtGui import *
from PySide.QtCore import *
import random

class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        self.setDragMode(QGraphicsView.RubberBandDrag)
        self._isPanning = False
        self._mousePressed = False
        # self.setBackgroundBrush(QImage("C:/Users/jmartini/Desktop/Temp/images/flag_0140.jpg"))
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
        self.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff )

    def mousePressEvent(self,  event):
        if event.button() == Qt.LeftButton:
            self._mousePressed = True
            if self._isPanning:
                self.setCursor(Qt.ClosedHandCursor)
                self._dragPos = event.pos()
                event.accept()
            else:
                super(MyGraphicsView, self).mousePressEvent(event)
        elif event.button() == Qt.MiddleButton:
            self._mousePressed = True
            self._isPanning = True
            self.setCursor(Qt.ClosedHandCursor)
            self._dragPos = event.pos()
            event.accept()

    def mouseMoveEvent(self, event):
        if self._mousePressed and self._isPanning:
            newPos = event.pos()
            diff = newPos - self._dragPos
            self._dragPos = newPos
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - diff.x())
            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - diff.y())
            event.accept()
        else:
            super(MyGraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            if self._isPanning:
                self.setCursor(Qt.OpenHandCursor)
            else:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        elif event.button() == Qt.MiddleButton:
            self._isPanning = False
            self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        super(MyGraphicsView, self).mouseReleaseEvent(event)

    def mouseDoubleClickEvent(self, event):
        self.fitInView(self.sceneRect(), Qt.KeepAspectRatio)
        pass

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space and not self._mousePressed:
            self._isPanning = True
            self.setCursor(Qt.OpenHandCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Space:
            if not self._mousePressed:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def wheelEvent(self,  event):
        # zoom factor
        factor = 1.25

        # Set Anchors
        self.setTransformationAnchor(QGraphicsView.NoAnchor)
        self.setResizeAnchor(QGraphicsView.NoAnchor)

        # Save the scene pos
        oldPos = self.mapToScene(event.pos())

        # Zoom
        if event.delta() < 0:
            factor = 1.0 / factor
        self.scale(factor, factor)

        # Get the new position
        newPos = self.mapToScene(event.pos())

        # Move scene to old position
        delta = newPos - oldPos
        self.translate(delta.x(), delta.y())

class MyGraphicsScene(QGraphicsScene):
    def __init__(self,  parent):
        super(MyGraphicsScene,  self).__init__()
        self.setBackgroundBrush(QBrush(QColor(50,50,50)))
        # self.setSceneRect(50,50,0,0)

class MyMainWindow(QMainWindow):
    def __init__(self):
        super(MyMainWindow, self).__init__()
        self.setWindowTitle("Test")
        self.resize(800,600)

        self.gv = MyGraphicsView()
        self.gv.setScene(MyGraphicsScene(self))
        self.setCentralWidget(self.gv)

        self.gv.scene().selectionChanged.connect(self.selection_changed)
        self.populate()

    def populate(self):
        scene = self.gv.scene()

        for i in range(500):
            x = random.randint(0, 1000)
            y = random.randint(0, 1000)
            r = random.randint(2, 8)
            rect = scene.addEllipse(x, y, r, r, QPen(QColor(255,128,0), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin), QBrush(QColor(255,128,20,128)))
            rect.setFlag( QGraphicsItem.ItemIsSelectable )
            rect.setFlag( QGraphicsItem.ItemIsMovable )

        rect = scene.addEllipse(300, 500, 20, 20, QPen(QColor(255,128,0), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin), QBrush(QColor(255,0,0,128)))
        rect.setFlag( QGraphicsItem.ItemIsSelectable )
        rect.setFlag( QGraphicsItem.ItemIsMovable )

    def selection_changed(self):
        selection = self.gv.scene().selectedItems()
        print 'Selected:', len(selection)
        for i in selection:
            i.setPen(QPen(QColor(255,255,255), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))

def main():
    app = QApplication(sys.argv)
    ex = MyMainWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Body:
It should be possible to get the required behaviour by caching the last selection and then clearing it before making the new selection:

class MyGraphicsView(QGraphicsView):
    def __init__(self):
        ...
        self.setScene(MyGraphicsScene(self))
        self.scene().selectionChanged.connect(self.selection_changed)
        self._current_selection = []

    def select_items(self, items, on):
        pen = QPen(QColor(255, 255, 255) if on else QColor(255, 128, 0),
                   0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
        for item in items:
            item.setPen(pen)

    def selection_changed(self):
        try:
            self.select_items(self._current_selection, False)
            self._current_selection = self.scene().selectedItems()
            self.select_items(self._current_selection, True)
        except RuntimeError:
            pass

Here is the complete script:

import sys
from PySide.QtGui import *
from PySide.QtCore import *
import random

class MyGraphicsView(QGraphicsView):
    def __init__(self):
        super(MyGraphicsView, self).__init__()
        self.setDragMode(QGraphicsView.RubberBandDrag)
        self._isPanning = False
        self._mousePressed = False
        self.setCacheMode(QGraphicsView.CacheBackground)
        self.setHorizontalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
        self.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff )
        self.setScene(MyGraphicsScene(self))
        self.scene().selectionChanged.connect(self.selection_changed)
        self._current_selection = []

    def select_items(self, items, on):
        pen = QPen(QColor(255, 255, 255) if on else QColor(255, 128, 0),
                   0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
        for item in items:
            item.setPen(pen)

    def selection_changed(self):
        try:
            self.select_items(self._current_selection, False)
            self._current_selection = self.scene().selectedItems()
            self.select_items(self._current_selection, True)
        except RuntimeError:
            pass

    def mousePressEvent(self,  event):
        if event.button() == Qt.LeftButton:
            self._mousePressed = True
            if self._isPanning:
                self.setCursor(Qt.ClosedHandCursor)
                self._dragPos = event.pos()
                event.accept()
            else:
                super(MyGraphicsView, self).mousePressEvent(event)
        elif event.button() == Qt.MiddleButton:
            self._mousePressed = True
            self._isPanning = True
            self.setCursor(Qt.ClosedHandCursor)
            self._dragPos = event.pos()
            event.accept()

    def mouseMoveEvent(self, event):
        if self._mousePressed and self._isPanning:
            newPos = event.pos()
            diff = newPos - self._dragPos
            self._dragPos = newPos
            self.horizontalScrollBar().setValue(self.horizontalScrollBar().value() - diff.x())
            self.verticalScrollBar().setValue(self.verticalScrollBar().value() - diff.y())
            event.accept()
        else:
            super(MyGraphicsView, self).mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.LeftButton:
            if self._isPanning:
                self.setCursor(Qt.OpenHandCursor)
            else:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        elif event.button() == Qt.MiddleButton:
            self._isPanning = False
            self.setCursor(Qt.ArrowCursor)
            self._mousePressed = False
        super(MyGraphicsView, self).mouseReleaseEvent(event)

    def mouseDoubleClickEvent(self, event):
        self.fitInView(self.sceneRect(), Qt.KeepAspectRatio)
        pass

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space and not self._mousePressed:
            self._isPanning = True
            self.setCursor(Qt.OpenHandCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Space:
            if not self._mousePressed:
                self._isPanning = False
                self.setCursor(Qt.ArrowCursor)
        else:
            super(MyGraphicsView, self).keyPressEvent(event)

    def wheelEvent(self,  event):
        # zoom factor
        factor = 1.25

        # Set Anchors
        self.setTransformationAnchor(QGraphicsView.NoAnchor)
        self.setResizeAnchor(QGraphicsView.NoAnchor)

        # Save the scene pos
        oldPos = self.mapToScene(event.pos())

        # Zoom
        if event.delta() < 0:
            factor = 1.0 / factor
        self.scale(factor, factor)

        # Get the new position
        newPos = self.mapToScene(event.pos())

        # Move scene to old position
        delta = newPos - oldPos
        self.translate(delta.x(), delta.y())

class MyGraphicsScene(QGraphicsScene):
    def __init__(self,  parent):
        super(MyGraphicsScene,  self).__init__()
        self.setBackgroundBrush(QBrush(QColor(50,50,50)))
        # self.setSceneRect(50,50,0,0)

class MyMainWindow(QMainWindow):
    def __init__(self):
        super(MyMainWindow, self).__init__()
        self.setWindowTitle("Test")
        self.resize(800,600)
        self.gv = MyGraphicsView()
        self.setCentralWidget(self.gv)
        self.populate()

    def populate(self):
        scene = self.gv.scene()
        for i in range(500):
            x = random.randint(0, 1000)
            y = random.randint(0, 1000)
            r = random.randint(2, 8)
            rect = scene.addEllipse(x, y, r, r, QPen(QColor(255,128,0), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin), QBrush(QColor(255,128,20,128)))
            rect.setFlag( QGraphicsItem.ItemIsSelectable )
            rect.setFlag( QGraphicsItem.ItemIsMovable )

        rect = scene.addEllipse(300, 500, 20, 20, QPen(QColor(255,128,0), 0.5, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin), QBrush(QColor(255,0,0,128)))
        rect.setFlag( QGraphicsItem.ItemIsSelectable )
        rect.setFlag( QGraphicsItem.ItemIsMovable )

def main():
    app = QApplication(sys.argv)
    ex = MyMainWindow()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()


问:
Sklearn: .predict returns an error Python
I installed sklearn with pip and when I use the function .predict it returns me this error:

```<code>Traceback (most recent call last):
   File "C:/Users/Roberto/PycharmProjects/AI projects/New.py", line 8, in <module>
print(clf.predict([150, 0]))
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\tree\tree.py", line 412, in predict
X = self._validate_X_predict(X, check_input)
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\tree\tree.py", line 373, in _validate_X_predict
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\utils\validation.py", line 441, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[ 150.    0.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
</code>```

And my code is:

```<code>from sklearn import tree
features = [[140, 1], [130, 1], [150, 0], [170, 0]]
labels = [0, 0, 1, 1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(features, labels)
print(clf.predict([150, 0]))
</code>```

What's wrong with this?

答:
The problem is that you are passing a single sample, if you pass [[150,0]] there will be no problem, like this:</p>

```<code>print(clf.predict([[150, 0]]))
</code>```

Body:
I installed sklearn with pip and when I use the function .predict it returns me this error:

Traceback (most recent call last):
   File "C:/Users/Roberto/PycharmProjects/AI projects/New.py", line 8, in <module>
print(clf.predict([150, 0]))
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-packages\sklearn\tree\tree.py", line 412, in predict
X = self._validate_X_predict(X, check_input)
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\tree\tree.py", line 373, in _validate_X_predict
X = check_array(X, dtype=DTYPE, accept_sparse="csr")
File "C:\Users\Roberto\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\sklearn\utils\validation.py", line 441, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[ 150.    0.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

And my code is:

from sklearn import tree
features = [[140, 1], [130, 1], [150, 0], [170, 0]]
labels = [0, 0, 1, 1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(features, labels)
print(clf.predict([150, 0]))

What's wrong with this?

Body:
The problem is that you are passing a single sample, if you pass [[150,0]] there will be no problem, like this:

print(clf.predict([[150, 0]]))


问:
Is there a SQL Server collation option that will allow matching different apostrophes?
I'm currently using SQL Server 2016 with SQL_Latin1_General_CP1_CI_AI collation.  As expected, queries with the letter e will match values with the letters e, è, é, ê, ë, etc because of the accent insensitive option of the collation.  However, queries with a ' (U+0027) do not match values containing a ’ (U+2019). I would like to know if such a collation exists where this case would match, since it's easier to type ' than it is to know that ’ is keystroke Alt-0146.</p>

答:
I'm confident in saying no. The main thing, here, is that the two characters are different (although similar). With accents, e and ê are still both an e (just one has an accent). This enables you  (for example) to do searches for things like SELECT * FROM Games WHERE [Name] LIKE 'Pokémon%'; and still have rows containing Pokemon return (because people haven't used the accent :P).

The best thing I could suggest would be to use REPLACE (at least in your WHERE clause) so that both rows are returned. That is, however, likely going to get expensive.

If you know what columns are going to be a problem, you could, therefore, add a PERSISTED Computed Column to that table. Then you could use that column in your WHERE clause, but display the one the original one. Something like:

```<code>USE Sandbox;
--Create Sample table and data
CREATE TABLE Sample (String varchar(500));

INSERT INTO Sample
VALUES ('This is a string that does not contain either apostrophe'),
       ('Where as this string, isn''t without at least one'),
       ('’I have one of them as well’'),
       ('’Well, I''m going to use both’');
GO
--First attempt (without the column)
SELECT String
FROM Sample
WHERE String LIKE '%''%'; --Only returns 2 of the rows
GO
--Create a PERSISTED Column
ALTER TABLE Sample ADD StringRplc AS REPLACE(String,'’','''') PERSISTED;
GO
--Second attempt
SELECT String
FROM Sample
WHERE StringRplc LIKE '%''%'; --Returns 3 rows
GO
--Clean up
DROP TABLE Sample;
GO
</code>```

Body:
I'm confident in saying no. The main thing, here, is that the two characters are different (although similar). With accents, e and ê are still both an e (just one has an accent). This enables you  (for example) to do searches for things like SELECT * FROM Games WHERE [Name] LIKE 'Pokémon%'; and still have rows containing Pokemon return (because people haven't used the accent :P).

The best thing I could suggest would be to use REPLACE (at least in your WHERE clause) so that both rows are returned. That is, however, likely going to get expensive.

If you know what columns are going to be a problem, you could, therefore, add a PERSISTED Computed Column to that table. Then you could use that column in your WHERE clause, but display the one the original one. Something like:

USE Sandbox;
--Create Sample table and data
CREATE TABLE Sample (String varchar(500));

INSERT INTO Sample
VALUES ('This is a string that does not contain either apostrophe'),
       ('Where as this string, isn''t without at least one'),
       ('’I have one of them as well’'),
       ('’Well, I''m going to use both’');
GO
--First attempt (without the column)
SELECT String
FROM Sample
WHERE String LIKE '%''%'; --Only returns 2 of the rows
GO
--Create a PERSISTED Column
ALTER TABLE Sample ADD StringRplc AS REPLACE(String,'’','''') PERSISTED;
GO
--Second attempt
SELECT String
FROM Sample
WHERE StringRplc LIKE '%''%'; --Returns 3 rows
GO
--Clean up
DROP TABLE Sample;
GO


问:
calling servlet from applet?
i am trying to call servlet from applet below is the calling code

```<code>ObjectOutputStream outputToServlet = null;
            try {
                //String xmlToSign = this.getParameter("xmltosign");
                String xmlToSign ="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <root> <name> hello world</name></root> ";
                URL signServlet = new URL("http://localhost:8084/SignXMLDemo/mtservlet");
                URLConnection servletConnection = signServlet.openConnection();
                servletConnection.setDoInput(false);
                servletConnection.setDoOutput(true);
                servletConnection.setUseCaches(false);
                servletConnection.setDefaultUseCaches(false);
                servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
                outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
                String encodedValue = new BASE64Encoder().encode(xmlToSign.getBytes());
                outputToServlet.writeObject(encodedValue);
                outputToServlet.flush();
                outputToServlet.close();
                JOptionPane.showMessageDialog(this, "XML successfully signed and sent to server.");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            } finally {
                try {
                    outputToServlet.close();
                } catch (IOException ex) {
                    Logger.getLogger(SignApplet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
</code>```

the issue with the code is that servlet in not being called can any one help in this what i am missing in the code. The URL is correct as it can be called from browser i am using ie 9 windows 7 machine.

Abdul Khaliq

答: the server side code does not get called until we read bytes from the opened stream</p>

Title: calling servlet from applet?

Body:
i am trying to call servlet from applet below is the calling code

ObjectOutputStream outputToServlet = null;
            try {
                //String xmlToSign = this.getParameter("xmltosign");
                String xmlToSign ="<?xml version=\"1.0\" encoding=\"UTF-8\"?> <root> <name> hello world</name></root> ";
                URL signServlet = new URL("http://localhost:8084/SignXMLDemo/mtservlet");
                URLConnection servletConnection = signServlet.openConnection();
                servletConnection.setDoInput(false);
                servletConnection.setDoOutput(true);
                servletConnection.setUseCaches(false);
                servletConnection.setDefaultUseCaches(false);
                servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
                outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
                String encodedValue = new BASE64Encoder().encode(xmlToSign.getBytes());
                outputToServlet.writeObject(encodedValue);
                outputToServlet.flush();
                outputToServlet.close();
                JOptionPane.showMessageDialog(this, "XML successfully signed and sent to server.");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, ex.getMessage());
            } finally {
                try {
                    outputToServlet.close();
                } catch (IOException ex) {
                    Logger.getLogger(SignApplet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

the issue with the code is that servlet in not being called can any one help in this what i am missing in the code. The URL is correct as it can be called from browser i am using ie 9 windows 7 machine.

Abdul Khaliq


问:
ReferenceError: angular is not defined index.js
I have looked at just about every answer to this question on SO but I can not find anything to fix the error in my case. I'm receiving it on startup of my application. I am using nodejs.

index.html

```<code><!doctype html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="utf-8">
<title>ITSC</title>

<!-- scripts -->
<script type="text/javascript" src="../node_modules/angular/angular.min.js">
</script>
<script type="text/javascript" src="../node_modules/angular-route/angular-route.min.js"></script>
<script type="text/javascript" src="../index.js"></script>
</head>
<body>
<header></header>
<div class="page" ng-controller="appController">
    <main class="cf">
      {{ message }}
</main>
</div>
</body>
</html>
</code>```

index.js

```<code>var express = require('express');
var path = require('path');
var port = process.env.PORT || 8080;
var router = require('./public/js/routes')
var app = express();

app.use('/', router);
app.use(express.static(__dirname + '/public'));
app.listen(port, function () {
    console.log('app started');
});

var myApp = angular.module('myApp', []);

myApp.controller('appController',['$scope', function($scope){
    $scope.message="Welcome to the app!!";

}]);
</code>```

答:
First of all, write your angular code in separate file, lets name if app.js.

Second you can't address angular like this ../node_modules/angular/angular.min.js, its better to use tools like webpack or browserify to make a bundle. but for you test you can copy these file into your public folder. /angular.min.js

```<code><!-- scripts -->
<script type="text/javascript" src="/angular.min.js">
</script>
<script type="text/javascript" src="/angular-route.min.js"></script>
<script type="text/javascript" src="/app.js"></script>
</code>```

public/app.js

```<code>var myApp = angular.module('myApp', []);

myApp.controller('appController',['$scope', function($scope){
    $scope.message="Welcome to the app!!";

}]);
</code>```

Body:
I have looked at just about every answer to this question on SO but I can not find anything to fix the error in my case. I'm receiving it on startup of my application. I am using nodejs.

index.html

<!doctype html>

<meta charset="utf-8">
<title>ITSC</title>

      {{ message }}

index.js

var express = require('express');
var path = require('path');
var port = process.env.PORT || 8080;
var router = require('./public/js/routes')
var app = express();

app.use('/', router);
app.use(express.static(__dirname + '/public'));
app.listen(port, function () {
    console.log('app started');
});

var myApp = angular.module('myApp', []);

myApp.controller('appController',['$scope', function($scope){
    $scope.message="Welcome to the app!!";

}]);

Body:
First of all, write your angular code in separate file, lets name if app.js.

Second you can't address angular like this ../node_modules/angular/angular.min.js, its better to use tools like webpack or browserify to make a bundle. but for you test you can copy these file into your public folder. /angular.min.js

<!-- scripts -->
<script type="text/javascript" src="/angular.min.js">
</script>
<script type="text/javascript" src="/angular-route.min.js"></script>
<script type="text/javascript" src="/app.js"></script>

public/app.js

var myApp = angular.module('myApp', []);

myApp.controller('appController',['$scope', function($scope){
    $scope.message="Welcome to the app!!";

}]);