问:
Python - how to return list items from multiple lists of possible different lengths but get only non-matching pairs?
I have a multi line string as follows:

```<code>mystr = """
ACTIVE     3/1.1
IDLE       3/1.1
IDLE       3/1.2
IDLE       3/1.2
ACTIVE     3/1.3
IDLE       3/1.3
ACTIVE     3/1.4
IDLE       3/1.4
ACTIVE     3/1.5
ACTIVE     3/1.6
IDLE       3/1.6
ACTIVE     3/1.7
IDLE       3/1.7
ACTIVE     3/1.8
IDLE       3/1.8
ACTIVE     3/1.9
IDLE       3/1.9
IDLE       3/1.10
"""
</code>```

or with a list, it would be:

```<code>mylist = ['ACTIVE     3/1.1 ', 'IDLE       3/1.1 ', 'IDLE       3/1.2 ', 'IDLE       3/1.2 ', 'ACTIVE     3/1.3 ', 'IDLE       3/1.3 ', 'ACTIVE     3/1.4 ', 'IDLE       3/1.4 ', 'ACTIVE     3/1.5 ', 'ACTIVE     3/1.6 ', 'IDLE       3/1.6 ', 'ACTIVE     3/1.7 ', 'IDLE       3/1.7 ', 'ACTIVE     3/1.8 ', 'IDLE       3/1.8 ', 'ACTIVE     3/1.9 ', 'IDLE       3/1.9 ', 'IDLE       3/1.10 ']
</code>```

My goal is this...

for every pair of "x/y.z", such as 3/1.1 or 3/1.2, etc, there should be a matching ACTIVE and IDLE pairing.

In the event there is NO "ACTIVE" or NO "IDLE" pairing, then check if the pair shows both as IDLE. If yes, return it.
If there is no pair, then regardless if it shows as ACTIVE or IDLE, return the value as well.

I got this to work by doing the following:

this var is used to compare against some values of x/y.z, where "z" could be any value from 1 to 10. However, the pairing only matches on the "x/y." part:

```<code>lc = ['3/1.', '3/2.', '3/3.', '3/7.', '3/8.', '4/1.', '4/5.', '4/6.', '4/7.', '5/3.', '5/4.', '5/5.', '6/1.', '6/2.', '6/3.', '6/7.', '6/8.', '7/1.']
</code>```

then rest of my script has:

```<code>outputsum = ""
pri_list = []
sec_list = []
stable_list = []

for intf in mylist:
  for g60 in lc:
    if g60 in intf:
      if "ACTIVE" in intf:
        pri_list.append(intf)
      if "IDLE" in intf.text:
        sec_list.append(intf)

for p in pri_list:
  t1 = p[p.find("ACTIVE")+11:]
  for s in sec_list:
    t2 = s[s.find("IDLE")+11:]
    if t1 == t2:
      print "Found matching pair!"
      if "ACTIVE" in p and "IDLE" in s:
        print "Putting valid ACTIVE/IDLE pairs into stable_list."
        stable_list.append(p)
        stable_list.append(s)

for pair in stable_list:
  for p1 in pri_list:
    if p1 == pair:
      pri_list.pop(pri_list.index(p1))
  for s1 in sec_list:
    if s1 == pair:
      sec_list.pop(sec_list.index(s1))

for i in pri_list:
  outputsum += i + "\n"

for i in sec_list:
  outputsum += i + "\n"

print outputsum
ACTIVE     3/1.5
IDLE       3/1.2
IDLE       3/1.2
IDLE       3/1.10
</code>```

The output from "print outputsum" is what I expect to get, but doing all the above seems long/complex.

Is there an easier/better/faster way of doing this?

I checked many different threads and examples, tried with sets, intersections and differences, and a mix with other loops, but I couldn't get the results I wanted. After a few days playing with this, I finally came up with the above working example. But I'm sure there's a better way than how I did it above.

any thoughts?

答:
you can use dastaframe groupby function. </p>

```<code>import pandas as pd
mylist = ['ACTIVE     3/1.1 ', 'IDLE       3/1.1 ', 'IDLE       3/1.2 ', 'IDLE       3/1.2 ', 'ACTIVE     3/1.3 ', 'IDLE       3/1.3 ', 'ACTIVE     3/1.4 ', 'IDLE       3/1.4 ', 'ACTIVE     3/1.5 ', 'ACTIVE     3/1.6 ', 'IDLE       3/1.6 ', 'ACTIVE     3/1.7 ', 'IDLE       3/1.7 ', 'ACTIVE     3/1.8 ', 'IDLE       3/1.8 ', 'ACTIVE     3/1.9 ', 'IDLE       3/1.9 ', 'IDLE       3/1.10 ']
df= pd.DataFrame(mylist,columns =['one'])
df = pd.DataFrame(df.one.str.split(' ',1).tolist())
df.columns = [ 'act','num']
res = [ item for item in df.set_index('num').groupby( lambda x:x.strip()[:6]) if len(item[1]) >1 ]
</code>```

Body:
I have a multi line string as follows:

mystr = """
ACTIVE     3/1.1
IDLE       3/1.1
IDLE       3/1.2
IDLE       3/1.2
ACTIVE     3/1.3
IDLE       3/1.3
ACTIVE     3/1.4
IDLE       3/1.4
ACTIVE     3/1.5
ACTIVE     3/1.6
IDLE       3/1.6
ACTIVE     3/1.7
IDLE       3/1.7
ACTIVE     3/1.8
IDLE       3/1.8
ACTIVE     3/1.9
IDLE       3/1.9
IDLE       3/1.10
"""

or with a list, it would be:

mylist = ['ACTIVE     3/1.1 ', 'IDLE       3/1.1 ', 'IDLE       3/1.2 ', 'IDLE       3/1.2 ', 'ACTIVE     3/1.3 ', 'IDLE       3/1.3 ', 'ACTIVE     3/1.4 ', 'IDLE       3/1.4 ', 'ACTIVE     3/1.5 ', 'ACTIVE     3/1.6 ', 'IDLE       3/1.6 ', 'ACTIVE     3/1.7 ', 'IDLE       3/1.7 ', 'ACTIVE     3/1.8 ', 'IDLE       3/1.8 ', 'ACTIVE     3/1.9 ', 'IDLE       3/1.9 ', 'IDLE       3/1.10 ']

My goal is this...

for every pair of "x/y.z", such as 3/1.1 or 3/1.2, etc, there should be a matching ACTIVE and IDLE pairing.

In the event there is NO "ACTIVE" or NO "IDLE" pairing, then check if the pair shows both as IDLE. If yes, return it.
If there is no pair, then regardless if it shows as ACTIVE or IDLE, return the value as well.

I got this to work by doing the following:

this var is used to compare against some values of x/y.z, where "z" could be any value from 1 to 10. However, the pairing only matches on the "x/y." part:

lc = ['3/1.', '3/2.', '3/3.', '3/7.', '3/8.', '4/1.', '4/5.', '4/6.', '4/7.', '5/3.', '5/4.', '5/5.', '6/1.', '6/2.', '6/3.', '6/7.', '6/8.', '7/1.']

then rest of my script has:

outputsum = ""
pri_list = []
sec_list = []
stable_list = []

for intf in mylist:
  for g60 in lc:
    if g60 in intf:
      if "ACTIVE" in intf:
        pri_list.append(intf)
      if "IDLE" in intf.text:
        sec_list.append(intf)

for p in pri_list:
  t1 = p[p.find("ACTIVE")+11:]
  for s in sec_list:
    t2 = s[s.find("IDLE")+11:]
    if t1 == t2:
      print "Found matching pair!"
      if "ACTIVE" in p and "IDLE" in s:
        print "Putting valid ACTIVE/IDLE pairs into stable_list."
        stable_list.append(p)
        stable_list.append(s)

for pair in stable_list:
  for p1 in pri_list:
    if p1 == pair:
      pri_list.pop(pri_list.index(p1))
  for s1 in sec_list:
    if s1 == pair:
      sec_list.pop(sec_list.index(s1))

for i in pri_list:
  outputsum += i + "\n"

for i in sec_list:
  outputsum += i + "\n"

print outputsum
ACTIVE     3/1.5
IDLE       3/1.2
IDLE       3/1.2
IDLE       3/1.10

The output from "print outputsum" is what I expect to get, but doing all the above seems long/complex.

Is there an easier/better/faster way of doing this?

I checked many different threads and examples, tried with sets, intersections and differences, and a mix with other loops, but I couldn't get the results I wanted. After a few days playing with this, I finally came up with the above working example. But I'm sure there's a better way than how I did it above.

any thoughts?

Body:
you can use dastaframe groupby function.

import pandas as pd
mylist = ['ACTIVE     3/1.1 ', 'IDLE       3/1.1 ', 'IDLE       3/1.2 ', 'IDLE       3/1.2 ', 'ACTIVE     3/1.3 ', 'IDLE       3/1.3 ', 'ACTIVE     3/1.4 ', 'IDLE       3/1.4 ', 'ACTIVE     3/1.5 ', 'ACTIVE     3/1.6 ', 'IDLE       3/1.6 ', 'ACTIVE     3/1.7 ', 'IDLE       3/1.7 ', 'ACTIVE     3/1.8 ', 'IDLE       3/1.8 ', 'ACTIVE     3/1.9 ', 'IDLE       3/1.9 ', 'IDLE       3/1.10 ']
df= pd.DataFrame(mylist,columns =['one'])
df = pd.DataFrame(df.one.str.split(' ',1).tolist())
df.columns = [ 'act','num']
res = [ item for item in df.set_index('num').groupby( lambda x:x.strip()[:6]) if len(item[1]) >1 ]


来源: stackexchange

问:
java.lang.ClassNotFoundException: org.sqlite.JDBC IntelliJ + Maven
I'm trying to connect my java application to my sqlite database but I'm getting this good old error. I'm using Maven and my setup looks like this:

project structure

I'm using IntelliJ and as far as I know Maven is well integrated. I'd like to know If I need to add the library somewhere else or put the jar file on the classpath.

I also leave here my pom.xml file with project definitions

```<code><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>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.16.1</version>
        </dependency>
    </dependencies>

</project>
</code>```

This is my connection class:

```<code>package database;

import java.io.File;
import java.io.FileNotFoundException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Created by luiscosta on 3/29/17.
 */
public class DBConnection {

    private Connection conn;
    private String dbPath;

    /**
     * Constructor
     */
    public DBConnection(String name, String folder) throws FileNotFoundException {

        File dbDir = new File(folder);

        if (dbDir.isDirectory() && dbDir.exists()) { //confirms the database directory exists
            if (folder.charAt(folder.length() - 1) == '/') { //checks if the directory ends in /
                this.dbPath = folder + name;

            } else {
                this.dbPath = folder + '/' + name; //if not adds it in the end of the folder pah
            }

            //Connection

            try {
                Class.forName("org.sqlite.JDBC");

                System.out.println("db Path" + this.dbPath);
                this.conn = DriverManager.getConnection("jdbc:sqlite:ChunkMetaData");

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new FileNotFoundException("Directory not found!");
        }
    }

}
</code>```

答:
You will have to add sqlite-jdbc-3.16.1.jar into classpath. In Intellij, going to module settings you can add.  You can download from : https://bitbucket.org/xerial/sqlite-jdbc/downloads/

I tried the below code and worked fine.

```<code>public class SqliteConnectionTry {

   public static void main(String[] args) {
      connect();
  }

   public static void connect() {
      Connection conn = null;
      try {
          // db parameters
           String url = "jdbc:sqlite::memory";
          // create a connection to the database
           conn = DriverManager.getConnection(url);

           System.out.println("Connected!!");

         } catch (SQLException e) {
            System.out.println(e.getMessage());
         } finally {
            try {
               if (conn != null) {
                  conn.close();
               }
         } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
}
</code>```

}

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to connect my java application to my sqlite database but I'm getting this good old error. I'm using Maven and my setup looks like this:

project structure

I'm using IntelliJ and as far as I know Maven is well integrated. I'd like to know If I need to add the library somewhere else or put the jar file on the classpath.

I also leave here my pom.xml file with project definitions

<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>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>Maven Quick Start Archetype</name>
<url>http://maven.apache.org</url>

    <dependencies>
        <dependency>
            <groupId>org.xerial</groupId>
            <artifactId>sqlite-jdbc</artifactId>
            <version>3.16.1</version>
        </dependency>
    </dependencies>

</project>

This is my connection class:

package database;

import java.io.File;
import java.io.FileNotFoundException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Created by luiscosta on 3/29/17.
 */
public class DBConnection {

    private Connection conn;
    private String dbPath;

    /**
     * Constructor
     */
    public DBConnection(String name, String folder) throws FileNotFoundException {

        File dbDir = new File(folder);

        if (dbDir.isDirectory() && dbDir.exists()) { //confirms the database directory exists
            if (folder.charAt(folder.length() - 1) == '/') { //checks if the directory ends in /
                this.dbPath = folder + name;

            } else {
                this.dbPath = folder + '/' + name; //if not adds it in the end of the folder pah
            }

            //Connection

            try {
                Class.forName("org.sqlite.JDBC");

                System.out.println("db Path" + this.dbPath);
                this.conn = DriverManager.getConnection("jdbc:sqlite:ChunkMetaData");

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new FileNotFoundException("Directory not found!");
        }
    }

}

Body:
You will have to add sqlite-jdbc-3.16.1.jar into classpath. In Intellij, going to module settings you can add.  You can download from : https://bitbucket.org/xerial/sqlite-jdbc/downloads/

I tried the below code and worked fine.

public class SqliteConnectionTry {

   public static void main(String[] args) {
      connect();
  }

   public static void connect() {
      Connection conn = null;
      try {
          // db parameters
           String url = "jdbc:sqlite::memory";
          // create a connection to the database
           conn = DriverManager.getConnection(url);

           System.out.println("Connected!!");

         } catch (SQLException e) {
            System.out.println(e.getMessage());
         } finally {
            try {
               if (conn != null) {
                  conn.close();
               }
         } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

}


问:
How to work with files which belong to the subuser namespace under Linux?
I am using docker on ubuntu 16.04 with user id mapping (user namepsaces) enabled. I have following settings:

/etc/passwd

myusername:x:1000:1000:,,,:/home/myusername:/bin/bash

/etc/subuid

myusername:100000:65536

/etc/subguid

myusername:100000:65536

When I start a container the files are being correctly mapped from 0 (root) to my subuid 100000.

host

-rw-r--r-- 1 100000 100000 0 Mär 30 13:05 testfile

container

rw-r--r-- 1 root root 0 Mar 30 13:05 testfile

I can read the file on the host machine, but I cannot edit it. My assumption was that 100000 is "my" subuid, so I can edit those files. How can I achieve that those files are accessible by myusername without sudo?

答:
I'm not sure how to fix this with user namespace mapping but you can work around it with ACL's.

If you don't mind leaking some UID information into the container, you can add an ACL to the directory for your host user. ACL's sit on top of the standard POSIX permissions.

To set a default ACL on the parent directory, that new entries inherit:

```<code>setfacl -d -m u:1000:rwx volume_dir/
</code>```

To set the ACL on all existing files and directories in a directory:

```<code>setfacl -R -m u:1000:rwX volume_dir/
</code>```

The X auto detects directories and sets them to executable but skips making files executable. Unfortunately this type of differentiation is not available on the default ACL.

Body:
I'm not sure how to fix this with user namespace mapping but you can work around it with ACL's.

If you don't mind leaking some UID information into the container, you can add an ACL to the directory for your host user. ACL's sit on top of the standard POSIX permissions.

To set a default ACL on the parent directory, that new entries inherit:

setfacl -d -m u:1000:rwx volume_dir/

To set the ACL on all existing files and directories in a directory:

setfacl -R -m u:1000:rwX volume_dir/

The X auto detects directories and sets them to executable but skips making files executable. Unfortunately this type of differentiation is not available on the default ACL.


问:
Change react router route params programmatically
Is there any simple and convenient way to navigate to same route with different params?

for ex. I'm right now on /profile/idan and I wish to change the param of idan to something else, instantly without dealing with the static part of the route.

答:
If your question is about v3 of the API, the react-router library introduces a router context. If you declare that in your contextTypes, you'll have access to a push and replace method. Example:

```<code>import React, { Component, PropTypes } from 'react';
import { PropTypes as RouterPropTypes } from 'react-router';

class MyComponent extends Component {
  // ...
  handleSomeEvent() {
    this.context.router.push('/some/url');
  }
}

MyComponent.contextTypes = {
  router: RouterPropTypes.routerShape
};

export default MyComponent;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If your question is about v3 of the API, the react-router library introduces a router context. If you declare that in your contextTypes, you'll have access to a push and replace method. Example:

import React, { Component, PropTypes } from 'react';
import { PropTypes as RouterPropTypes } from 'react-router';

class MyComponent extends Component {
  // ...
  handleSomeEvent() {
    this.context.router.push('/some/url');
  }
}

MyComponent.contextTypes = {
  router: RouterPropTypes.routerShape
};

export default MyComponent;


问:
looking for a text pattern in all the files
We have got lot of files with the text like:

create user user_name

identified by crsny

tablespace tab1

Is there anyway to search for   identified by **** /n
and then replace with somethingelse in Notepad++.

答:
Open the Find in Files tab (CTRL + SHIFT + F)

Check the Regular Expression option (bottom of this window)

Fill the directory path of your files on Directory field

Check "In All sub-folders" option (if the path have subdirectories)

Fill the field "Find what" with: identified\s+by\s+.+

Fill the field "Replace with" with: somethingelse

To be sure that it is right click on "Find All" button

At last, click on "Replace in files"

Post note, if you are sure of the wanted text identified by.... case, just mark the "Match Case" option


问:
Parsing a JSON date into a C# DateTime
i have an API that get information from targetProcess and put that information in sql tables.

the issue comes when a targetProcess field is date because i recieved it as json date "/Date(1409202000000-0500 )/".

How can i convert this json date to Datetime in c#?

i have been trying add extra quotes like the asnwer in this StackOverflow Post but it doesnt work.

i tried replace the the word Date for only use 1409202000000-0500 in

```<code>DateTime dotNetDate = new DateTime(1970, 1, 1);
dotNetDate = dotNetDate.AddMilliseconds(Convert.ToInt64(1409202000000-0500)
</code>```

i use too JSON.NET as bellow

```<code>string sa = "/Date(1409202000000-0500 )/"
DateTime dt = new DateTime();
dt = JsonConvert.DeserializeObject<DateTime>(sa);
</code>```

but it doesnt work too,

so the question is....How can i convert this json date to Datetime in c#?

答:
You need to manually wrap your string "programatically" in quotes to ensure that it properly formatted correctly:

```<code>string sa = @"""" + "/Date(1409202000000-0500 )/" + @"""";
DateTime dt = JsonConvert.DeserializeObject<DateTime>(sa);
</code>```

If you need to call it multiple times (which it seems like you do), just move the wrapping responsibility to a method:

```<code>public string WrapStringInQuotes(string input)
{
    return @"""" + input + @"""";
}
</code>```

Title: Parsing a JSON date into a C# DateTime

Body:
i have an API that get information from targetProcess and put that information in sql tables.

the issue comes when a targetProcess field is date because i recieved it as json date "/Date(1409202000000-0500 )/".

How can i convert this json date to Datetime in c#?

i have been trying add extra quotes like the asnwer in this StackOverflow Post but it doesnt work.

i tried replace the the word Date for only use 1409202000000-0500 in

DateTime dotNetDate = new DateTime(1970, 1, 1);
dotNetDate = dotNetDate.AddMilliseconds(Convert.ToInt64(1409202000000-0500)

i use too JSON.NET as bellow

string sa = "/Date(1409202000000-0500 )/"
DateTime dt = new DateTime();
dt = JsonConvert.DeserializeObject<DateTime>(sa);

but it doesnt work too,

so the question is....How can i convert this json date to Datetime in c#?

Body:
You need to manually wrap your string "programatically" in quotes to ensure that it properly formatted correctly:

string sa = @"""" + "/Date(1409202000000-0500 )/" + @"""";
DateTime dt = JsonConvert.DeserializeObject<DateTime>(sa);

If you need to call it multiple times (which it seems like you do), just move the wrapping responsibility to a method:

public string WrapStringInQuotes(string input)
{
    return @"""" + input + @"""";
}


问:
Find the smallest area rectangle covering a query point
I'm working on a personal project to do with computational geometry. The question in the title is an abstraction of one of the small subproblems that I am trying, but struggling, to solve efficiently. Hopefully it's general enough to maybe be of use of more than just me!

The problem

Imagine we have a set S of rectangles in the plane, all of which have edges parallel to the coordinate axes (no rotations). For my problem we'll assume that rectangle intersections are very common. But they are also very nice: If two rectangles intersect, we can assume one of them always completely contains the other. So there's no "partial" overlaps.

I want to store these rectangles in a way that:

We can efficiently add new rectangles.

Given a query point (x,y) we can efficiently report back the
rectangle of smallest area that contains the point.

The illustration provides the motivation for the latter. We always want to find the most deeply nested rectangle that contains the query point, so that's always the one of smallest area.

My thoughts

So I know that both R-Trees and Quad-Trees are often used for spatial indexing problems, and indeed both can work well in some cases. The problem with R-Trees is that they can degrade to linear performance in the worst case.

I thought about building a set of balanced binary trees based on nestedness. The left subtree of node r contains all the rectangles that are inside rectangle r. The right subtree contains all the rectangles that r is inside of. The illustrated example would have three trees.

But what if none of the rectangles are nested? Then you need O(n) trees of 1 element and again we have something that performs just as poorly as a linear scan through the boxes.

How could I solve this in  a way that we have asymptotically sub linear time in the worst case? Even if that means sacrificing some performance in the best cases or storage requirements. (I assume for a problem like this, there may be a need to maintain two data structures and that's cool)

I am certain that the very specific way in which rectangles are allowed to intersect should help make this problem possible. In fact, it looks like a candidate for logarithmic performance to me but I'm just not getting anywhere.

Thanks in advance for any ideas you have!

答:
You can partition the area from xMin to xMax and yMin to yMax along the edges of the rectangles. This gives at most (2n - 1)^2 fields. Each of the fields is either completely empty or occupied by the visible (part of a) single rectangle. Now you can easily create a tree structure with links to the top rectangle (e.g. count the number of partitions in x and y direction, where there are more divide in the middle and create a node... proceed recursively). So the lookup will take O(log n^2) which is sub linear. And the data structure takes O(n^2) space.

Here is a better implementation in terms of complexity, because the search of the indices can be separated the search for the rectangle on top is only O(log n) no matter how the configuration of the rectangles is and fairly simple to implement:

```<code>private int[] x, y;
private Rectangle[][] r;

public RectangleFinder(Rectangle[] rectangles) {
    Set<Integer> xPartition = new HashSet<>(), yPartition = new HashSet<>();
    for (int i = 0; i < rectangles.length; i++) {
        xPartition.add(rectangles[i].getX());
        yPartition.add(rectangles[i].getY());
        xPartition.add(rectangles[i].getX() + rectangles[i].getWidth());
        yPartition.add(rectangles[i].getY() + rectangles[i].getHeight());
    }
    x = new int[xPartition.size()];
    y = new int[yPartition.size()];
    r = new Rectangle[x.length][y.length];
    int c = 0;
    for (Iterator<Integer> itr = xPartition.iterator(); itr.hasNext();)
        x[c++] = itr.next();
    c = 0;
    for (Iterator<Integer> itr = yPartition.iterator(); itr.hasNext();)
        y[c++] = itr.next();
    Arrays.sort(x);
    Arrays.sort(y);
    for (int i = 0; i < x.length; i++)
        for (int j = 0; j < y.length; j++)
            r[i][j] = rectangleOnTop(x[i], y[j]);
}

public Rectangle find(int x, int y) {
    return r[getIndex(x, this.x, 0, this.x.length)][getIndex(y, this.y, 0, this.y.length)];
}

private int getIndex(int n, int[] arr, int start, int len) {
    if (len <= 1)
        return start;
    int mid = start + len / 2;
    if (n < arr[mid])
        return getIndex(n, arr, start, len / 2);
    else
        return getIndex(n, arr, mid, len - len / 2);
}
</code>```

Body:
You can partition the area from xMin to xMax and yMin to yMax along the edges of the rectangles. This gives at most (2n - 1)^2 fields. Each of the fields is either completely empty or occupied by the visible (part of a) single rectangle. Now you can easily create a tree structure with links to the top rectangle (e.g. count the number of partitions in x and y direction, where there are more divide in the middle and create a node... proceed recursively). So the lookup will take O(log n^2) which is sub linear. And the data structure takes O(n^2) space.

Here is a better implementation in terms of complexity, because the search of the indices can be separated the search for the rectangle on top is only O(log n) no matter how the configuration of the rectangles is and fairly simple to implement:

private int[] x, y;
private Rectangle[][] r;

public RectangleFinder(Rectangle[] rectangles) {
    Set<Integer> xPartition = new HashSet<>(), yPartition = new HashSet<>();
    for (int i = 0; i < rectangles.length; i++) {
        xPartition.add(rectangles[i].getX());
        yPartition.add(rectangles[i].getY());
        xPartition.add(rectangles[i].getX() + rectangles[i].getWidth());
        yPartition.add(rectangles[i].getY() + rectangles[i].getHeight());
    }
    x = new int[xPartition.size()];
    y = new int[yPartition.size()];
    r = new Rectangle[x.length][y.length];
    int c = 0;
    for (Iterator<Integer> itr = xPartition.iterator(); itr.hasNext();)
        x[c++] = itr.next();
    c = 0;
    for (Iterator<Integer> itr = yPartition.iterator(); itr.hasNext();)
        y[c++] = itr.next();
    Arrays.sort(x);
    Arrays.sort(y);
    for (int i = 0; i < x.length; i++)
        for (int j = 0; j < y.length; j++)
            r[i][j] = rectangleOnTop(x[i], y[j]);
}

public Rectangle find(int x, int y) {
    return r[getIndex(x, this.x, 0, this.x.length)][getIndex(y, this.y, 0, this.y.length)];
}

private int getIndex(int n, int[] arr, int start, int len) {
    if (len <= 1)
        return start;
    int mid = start + len / 2;
    if (n < arr[mid])
        return getIndex(n, arr, start, len / 2);
    else
        return getIndex(n, arr, mid, len - len / 2);
}


问:
Need help using a while statement and getting the math right
I'm still very new to coding.  My teacher is very hard to understand so I need online help.  For this, I need to find the value in a savings account after months of compounding interest. I know that my math is wrong but I don't know how to fix this, and I've never written a while statement.  Please help me out.

From my prompt:

"Suppose you save $100 each month into the savings account and the
  annual interest rate is 5%.   So, the monthly interest rate is 0.05/12
  = 0.00417.   After the first month, the value in the account becomes 100* (1 + 0.00417) = $100.417    After the second month, the value in
  the account becomes (100 + 100.417) * (1 + 0.00417) = $201.252 After
  the third month, the value in the account becomes
         (100 + 201.252) * (1 + 0.00417) = $302.507 and so on."

```<code>double initialSavings;
System.out.print("How much money would you like to save each month? $");
initialSavings = userInput.nextDouble();

double annualInterest;
System.out.print("What is the annual interest rate for your savings account? (Example, 2.5) ");
annualInterest = userInput.nextDouble();

int months;
System.out.print("How many months would you like to keep saving? ");
months = userInput.nextInt();

double monthlyInterest;
monthlyInterest = annualInterest / 12;

int count = 1;

while (count <= months) {

count++;

double result;

result = initialSavings * count * (1 + monthlyInterest);

}

System.out.println("You will have $"+ result "after "+ months "months.");
}
}
</code>```

答:
I suppose the calculation is wrong.
Second month interest should be calculated with concerning
 initialSavings + first month interest.

this is a common formula used for interest calculation.

```<code>A = amount
P = principal
R = monthly rate
n = months

 A=P(1+R)^n
</code>```

try like this

```<code>  double initialSavings = 100;
  int months= 5;
  double rate = 0.00417;

  System.out.printf("Inital Savings: %.2f \n", initialSavings);
  System.out.println("Months: " + months);
  System.out.println("Monthy Interest rate: " + rate);

  System.out.println("Total amount componded over the " + months+ " months:"     );
  for(int x = 1; x <= months; x++) {
     double amount = initialSavings* Math.pow(1+ rate, x);
     System.out.printf("Month" + x + ": %.2f \n" , amount);
  }
</code>```

Body:
I'm still very new to coding.  My teacher is very hard to understand so I need online help.  For this, I need to find the value in a savings account after months of compounding interest. I know that my math is wrong but I don't know how to fix this, and I've never written a while statement.  Please help me out.

From my prompt:

"Suppose you save $100 each month into the savings account and the
  annual interest rate is 5%.   So, the monthly interest rate is 0.05/12
  = 0.00417.   After the first month, the value in the account becomes 100* (1 + 0.00417) = $100.417    After the second month, the value in
  the account becomes (100 + 100.417) * (1 + 0.00417) = $201.252 After
  the third month, the value in the account becomes
         (100 + 201.252) * (1 + 0.00417) = $302.507 and so on."

double initialSavings;
System.out.print("How much money would you like to save each month? $");
initialSavings = userInput.nextDouble();

double annualInterest;
System.out.print("What is the annual interest rate for your savings account? (Example, 2.5) ");
annualInterest = userInput.nextDouble();

int months;
System.out.print("How many months would you like to keep saving? ");
months = userInput.nextInt();

double monthlyInterest;
monthlyInterest = annualInterest / 12;

int count = 1;

while (count <= months) {

count++;

double result;

result = initialSavings * count * (1 + monthlyInterest);

}

System.out.println("You will have $"+ result "after "+ months "months.");
}
}

Body:
I suppose the calculation is wrong.
Second month interest should be calculated with concerning
 initialSavings + first month interest.

this is a common formula used for interest calculation.

A = amount
P = principal
R = monthly rate
n = months

 A=P(1+R)^n

try like this

  double initialSavings = 100;
  int months= 5;
  double rate = 0.00417;

  System.out.printf("Inital Savings: %.2f \n", initialSavings);
  System.out.println("Months: " + months);
  System.out.println("Monthy Interest rate: " + rate);

  System.out.println("Total amount componded over the " + months+ " months:"     );
  for(int x = 1; x <= months; x++) {
     double amount = initialSavings* Math.pow(1+ rate, x);
     System.out.printf("Month" + x + ": %.2f \n" , amount);
  }


问:
Updating EF6 code first entities from REST service
I'm using EF6 code first and I have a service layer where AutoMapper maps a DTO to an Entity type (this is an update so the object with the same ID already exists in the database). I would like to have the changes persisted to the database. Is it possible to perform the update with this completely new object which EF has no knowledge of or do I have to copy the property values over to the object which EF holds a reference to? What is the best practice for doing this? And what about the navigation properties? Do these have to be done the same way?</p>

答:
If you want to specifically mark an object as updated and not added (which is what EF would do by default if you just added it to the context), you can do that - context.Entry(entity).State = EntityState.Modified. You'd need to do it appropriately for associated entities as well and it can get a bit messy, but it would save you a query to the database to get the original entity.

I don't think there's one answer that fits all scenarios; one solution I worked on was to specify up-front the rules that would make entities be marked as updated or added (usually based on the autoincremented primary key being 0 or not). In another case with a highly relational model it was easier to query for the original object (including all the relationships inferred from the updated copy) and copy updated properties and relationships (again according to some rules).


问:
Worksheet Change add Now() without Automatically updating
Hello I am very new to VBA but I was hoping someone can help. I am trying to create a timestamp using the code below. But I can't figure out how to copy it for the next row.

```<code> Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 1 And Target.Row = 2 Then
    If Target.Value = "" Then
      Cells(2, 4).Value = ""
    Else
      Cells(2, 4).Value = Format(Now, "H:mm:ss AM/PM")
    End If
  End If
End Sub
</code>```

It works fine for that 1 cell. But how can I repeat this when I enter something in A3,A4..so on. This is probably a very basic question but I am a total newbie!

答:
Remove the check for row 2 and use Target.Row:</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 1  Then
    If Target.Value = "" Then
      Cells(Target.Row, 4).Value = ""
    Else
      Cells(Target.Row, 4).Value = Format(Now, "H:mm:ss AM/PM")
    End If
  End If
End Sub
</code>```

Body:
Hello I am very new to VBA but I was hoping someone can help. I am trying to create a timestamp using the code below. But I can't figure out how to copy it for the next row.

 Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 1 And Target.Row = 2 Then
    If Target.Value = "" Then
      Cells(2, 4).Value = ""
    Else
      Cells(2, 4).Value = Format(Now, "H:mm:ss AM/PM")
    End If
  End If
End Sub

It works fine for that 1 cell. But how can I repeat this when I enter something in A3,A4..so on. This is probably a very basic question but I am a total newbie!

Body:
Remove the check for row 2 and use Target.Row:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 1  Then
    If Target.Value = "" Then
      Cells(Target.Row, 4).Value = ""
    Else
      Cells(Target.Row, 4).Value = Format(Now, "H:mm:ss AM/PM")
    End If
  End If
End Sub


问:
How to save Date Time without the time?
How would i save the date time, with no time or preferably with a time stamp of 12:00, no matter what the time is at that moment?

I dont want to use .ToString("dd/MM/yyyy");, because it will open up a whole lot of new  possible errors.

答:
As other posters have said

```<code>DateTime.Now.Date
</code>```

is the way to go.  However it is also worth thinking about whether you want to strip out timezone information to prevent problems occurring across different TZ on client\server machines.

You can use

```<code>var dateTime = new DateTime(DateTime.Now.Date.Ticks, DateTimeKind.Unspecified);
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to save Date Time without the time?

Body:
As other posters have said

DateTime.Now.Date

is the way to go.  However it is also worth thinking about whether you want to strip out timezone information to prevent problems occurring across different TZ on client\server machines.

You can use

var dateTime = new DateTime(DateTime.Now.Date.Ticks, DateTimeKind.Unspecified);


答:
This should do it,

```<code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A2:A99999")) Is Nothing Then
        If Target.Value = "" Then
            Cells(2, 4).Value = ""
        Else
            Cells(2, 4).Value = Format(Now, "H:mm:ss AM/PM")
        End If
    End If
End Sub
</code>```

Or else you wanna add on every offset cell

```<code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A2:A99999")) Is Nothing Then
        If Target.Value = "" Then
            Target.Offset(0, 3).Value = ""
        Else
            Target.Offset(0, 3) = Format(Now, "H:mm:ss AM/PM")
        End If
    End If
End Sub
</code>```

Worksheet.Change Event (Excel)

Range.Offset Property (Excel)

Title: Worksheet Change add Now() without Automatically updating

Body:
This should do it,

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A2:A99999")) Is Nothing Then
        If Target.Value = "" Then
            Cells(2, 4).Value = ""
        Else
            Cells(2, 4).Value = Format(Now, "H:mm:ss AM/PM")
        End If
    End If
End Sub

Or else you wanna add on every offset cell

Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A2:A99999")) Is Nothing Then
        If Target.Value = "" Then
            Target.Offset(0, 3).Value = ""
        Else
            Target.Offset(0, 3) = Format(Now, "H:mm:ss AM/PM")
        End If
    End If
End Sub

Worksheet.Change Event (Excel)

Range.Offset Property (Excel)


问:
Read text file in pyspark and sparksubmit
Assuming I run a python shell (file1.py) which take a text file as a parameter. that I run it as the following:

```<code>python file1.py textfile1.txt
</code>```

Inside file1.py the following code

```<code>from pyspark import SparkContext
....

#I can read the file using the follwoing command
sc = SparkContext()
inputfile= sc.textFile(sys.argv[1])
</code>```

What is the required modifications I must do to make file1.py run without problems?

But pyspark doesn't work with me, usually, I am using spark-submit!so it give me the following error when run using spark-submit in local mode

```<code>Traceback (most recent call last):
  File "/home/noorhadoop/Desktop/folder1/file1.py", line 4, in <module>
    from pyspark import SparkContext
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/__init__.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/context.py", line 33, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/java_gateway.py", line 25, in <module>
  File "/usr/lib/python3.6/platform.py", line 909, in <module>
    "system node release version machine processor")
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 21, in <module>
    from urllib.request import urlopen
  File "/usr/lib/python3.6/urllib/request.py", line 88, in <module>
    import http.client
  File "/usr/lib/python3.6/http/client.py", line 71, in <module>
    import email.parser
  File "/usr/lib/python3.6/email/parser.py", line 12, in <module>
    from email.feedparser import FeedParser, BytesFeedParser
  File "/usr/lib/python3.6/email/feedparser.py", line 27, in <module>
    from email._policybase import compat32
  File "/usr/lib/python3.6/email/_policybase.py", line 9, in <module>
    from email.utils import _has_surrogates
  File "/usr/lib/python3.6/email/utils.py", line 31, in <module>
    import urllib.parse
  File "/usr/lib/python3.6/urllib/parse.py", line 227, in <module>
    _DefragResultBase = namedtuple('DefragResult', 'url fragment')
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'

Original exception was:
Traceback (most recent call last):
  File "/home/noorhadoop/Desktop/folder1/file1.py", line 4, in <module>
    from pyspark import SparkContext
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/__init__.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/context.py", line 33, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/java_gateway.py", line 25, in <module>
  File "/usr/lib/python3.6/platform.py", line 909, in <module>
    "system node release version machine processor")
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'
hduser@noorhadoop-virtual-machine:/usr/local/spark$ ./bin/spark-submit --master local[3] /home/noorhadoop/Desktop/folder1/file1.py  /home/noorhadoop/Desktop/folder1/simple1.txt
Traceback (most recent call last):
  File "/home/noorhadoop/Desktop/folder1/file1.py", line 4, in <module>
    from pyspark import SparkContext
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/__init__.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/context.py", line 33, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/java_gateway.py", line 25, in <module>
  File "/usr/lib/python3.6/platform.py", line 909, in <module>
    "system node release version machine processor")
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 21, in <module>
    from urllib.request import urlopen
  File "/usr/lib/python3.6/urllib/request.py", line 88, in <module>
    import http.client
  File "/usr/lib/python3.6/http/client.py", line 71, in <module>
    import email.parser
  File "/usr/lib/python3.6/email/parser.py", line 12, in <module>
    from email.feedparser import FeedParser, BytesFeedParser
  File "/usr/lib/python3.6/email/feedparser.py", line 27, in <module>
    from email._policybase import compat32
  File "/usr/lib/python3.6/email/_policybase.py", line 9, in <module>
    from email.utils import _has_surrogates
  File "/usr/lib/python3.6/email/utils.py", line 31, in <module>
    import urllib.parse
  File "/usr/lib/python3.6/urllib/parse.py", line 227, in <module>
    _DefragResultBase = namedtuple('DefragResult', 'url fragment')
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'

Original exception was:
Traceback (most recent call last):
  File "/home/noorhadoop/Desktop/folder1/file1.py", line 4, in <module>
    from pyspark import SparkContext
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/__init__.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/context.py", line 33, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/java_gateway.py", line 25, in <module>
  File "/usr/lib/python3.6/platform.py", line 909, in <module>
    "system node release version machine processor")
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'
</code>```

Thanks,

答:
You didnt post error messages, so it hard to know exact but sc.textFile expects full path of file either on HDFS or local file system.

for example, if you are running spark in local mode , you will have to pass arguments with spark-submit as -

```<code>spark-submit \
--master local[*] \
--/path/to/file1.py \
"file://path/to/textfile1.txt"
</code>```

or if you are running on cluster, give full hdfs path as argument

```<code>spark-submit \
--master spark://localhost:7077 \
--/path/to/file1.py \
"hdfs://localhost:9000/path/to/textfile1.txt"
</code>```

Body:
Assuming I run a python shell (file1.py) which take a text file as a parameter. that I run it as the following:

python file1.py textfile1.txt

Inside file1.py the following code

from pyspark import SparkContext
....

#I can read the file using the follwoing command
sc = SparkContext()
inputfile= sc.textFile(sys.argv[1])

What is the required modifications I must do to make file1.py run without problems?

But pyspark doesn't work with me, usually, I am using spark-submit!so it give me the following error when run using spark-submit in local mode

Traceback (most recent call last):
  File "/home/noorhadoop/Desktop/folder1/file1.py", line 4, in <module>
    from pyspark import SparkContext
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/__init__.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/context.py", line 33, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/java_gateway.py", line 25, in <module>
  File "/usr/lib/python3.6/platform.py", line 909, in <module>
    "system node release version machine processor")
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 21, in <module>
    from urllib.request import urlopen
  File "/usr/lib/python3.6/urllib/request.py", line 88, in <module>
    import http.client
  File "/usr/lib/python3.6/http/client.py", line 71, in <module>
    import email.parser
  File "/usr/lib/python3.6/email/parser.py", line 12, in <module>
    from email.feedparser import FeedParser, BytesFeedParser
  File "/usr/lib/python3.6/email/feedparser.py", line 27, in <module>
    from email._policybase import compat32
  File "/usr/lib/python3.6/email/_policybase.py", line 9, in <module>
    from email.utils import _has_surrogates
  File "/usr/lib/python3.6/email/utils.py", line 31, in <module>
    import urllib.parse
  File "/usr/lib/python3.6/urllib/parse.py", line 227, in <module>
    _DefragResultBase = namedtuple('DefragResult', 'url fragment')
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'

Original exception was:
Traceback (most recent call last):
  File "/home/noorhadoop/Desktop/folder1/file1.py", line 4, in <module>
    from pyspark import SparkContext
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/__init__.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/context.py", line 33, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/java_gateway.py", line 25, in <module>
  File "/usr/lib/python3.6/platform.py", line 909, in <module>
    "system node release version machine processor")
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'
hduser@noorhadoop-virtual-machine:/usr/local/spark$ ./bin/spark-submit --master local[3] /home/noorhadoop/Desktop/folder1/file1.py  /home/noorhadoop/Desktop/folder1/simple1.txt
Traceback (most recent call last):
  File "/home/noorhadoop/Desktop/folder1/file1.py", line 4, in <module>
    from pyspark import SparkContext
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/__init__.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/context.py", line 33, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/java_gateway.py", line 25, in <module>
  File "/usr/lib/python3.6/platform.py", line 909, in <module>
    "system node release version machine processor")
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/apport_python_hook.py", line 63, in apport_excepthook
    from apport.fileutils import likely_packaged, get_recent_crashes
  File "/usr/lib/python3/dist-packages/apport/__init__.py", line 5, in <module>
    from apport.report import Report
  File "/usr/lib/python3/dist-packages/apport/report.py", line 21, in <module>
    from urllib.request import urlopen
  File "/usr/lib/python3.6/urllib/request.py", line 88, in <module>
    import http.client
  File "/usr/lib/python3.6/http/client.py", line 71, in <module>
    import email.parser
  File "/usr/lib/python3.6/email/parser.py", line 12, in <module>
    from email.feedparser import FeedParser, BytesFeedParser
  File "/usr/lib/python3.6/email/feedparser.py", line 27, in <module>
    from email._policybase import compat32
  File "/usr/lib/python3.6/email/_policybase.py", line 9, in <module>
    from email.utils import _has_surrogates
  File "/usr/lib/python3.6/email/utils.py", line 31, in <module>
    import urllib.parse
  File "/usr/lib/python3.6/urllib/parse.py", line 227, in <module>
    _DefragResultBase = namedtuple('DefragResult', 'url fragment')
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'

Original exception was:
Traceback (most recent call last):
  File "/home/noorhadoop/Desktop/folder1/file1.py", line 4, in <module>
    from pyspark import SparkContext
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/__init__.py", line 44, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/context.py", line 33, in <module>
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 646, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 616, in _load_backward_compatible
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/java_gateway.py", line 25, in <module>
  File "/usr/lib/python3.6/platform.py", line 909, in <module>
    "system node release version machine processor")
  File "/usr/local/spark/python/lib/pyspark.zip/pyspark/serializers.py", line 381, in namedtuple
TypeError: namedtuple() missing 3 required keyword-only arguments: 'verbose', 'rename', and 'module'

Thanks,

Body:
You didnt post error messages, so it hard to know exact but sc.textFile expects full path of file either on HDFS or local file system.

for example, if you are running spark in local mode , you will have to pass arguments with spark-submit as -

spark-submit \
--master local[*] \
--/path/to/file1.py \
"file://path/to/textfile1.txt"

or if you are running on cluster, give full hdfs path as argument

spark-submit \
--master spark://localhost:7077 \
--/path/to/file1.py \
"hdfs://localhost:9000/path/to/textfile1.txt"


问:
Develop/Organize a node module in TypeScript
I want to develop a node module in TypeScript, but I'm having some problems with all the possible options to require, import, etc.

What I'm doing right now is having every class and interface in it's own file. So I would need to require all the dependencies which is kind of stupid, because I'm typing the class name twice, like this:

```<code>import Target = require('./Target');

export interface IFace {

    getTarget(): Target.Target
}
</code>```

I could write import t = require('./Target'); instead but then I need to write t.Target which I think is also pretty ugly.

And also I can't give it a module name (like FaceApp), because when I need to import two files, there's a naming conflict.

Obviously that would not be needed if everything would live in one file, but this is far from optimal I think.

So how do you guys organize your node module in TypeScript? I'd be happy to hear your suggestions.

答:
The way recommended by TypeScript is to do

```<code>export default class Target {}
</code>```

and then you can do a true typescript import with

```<code>import Target from './Target'
</code>```

alternatively, you can rename it

```<code>import NewName from './Target'
</code>```

Also note that you can export multiple things from a file if they are related

```<code>export class SomeClass {}
export class OtherClass {}
</code>```

And that on import, you can change the names

```<code>import { SomeClass as MySomeClass, OtherClass as MyOtherClass } from './Target'
</code>```

Body:
I want to develop a node module in TypeScript, but I'm having some problems with all the possible options to require, import, etc.

What I'm doing right now is having every class and interface in it's own file. So I would need to require all the dependencies which is kind of stupid, because I'm typing the class name twice, like this:

import Target = require('./Target');

export interface IFace {

    getTarget(): Target.Target
}

I could write import t = require('./Target'); instead but then I need to write t.Target which I think is also pretty ugly.

And also I can't give it a module name (like FaceApp), because when I need to import two files, there's a naming conflict.

Obviously that would not be needed if everything would live in one file, but this is far from optimal I think.

So how do you guys organize your node module in TypeScript? I'd be happy to hear your suggestions.

Body:
The way recommended by TypeScript is to do

export default class Target {}

and then you can do a true typescript import with

import Target from './Target'

alternatively, you can rename it

import NewName from './Target'

Also note that you can export multiple things from a file if they are related

export class SomeClass {}
export class OtherClass {}

And that on import, you can change the names

import { SomeClass as MySomeClass, OtherClass as MyOtherClass } from './Target'


答:
You can use defaultdict, see below

```<code># Clean up the data
j = [i.split('     ') for i in mylist]
j[:] = [[jj[0], jj[1].strip()] for jj in j]

# Make a list of idle/active for each key of "x/y.z"
from collections import defaultdict
d = defaultdict(list)
for i in j:
    d[i[1]].append(i[0])

# use some if/else to find pairing

for k,j in d.items():
    if j == ['IDLE']:
        print 'IDLE at {}'.format(k)
    elif j == ['ACTIVE']:
        print 'ACTIVE at {}'.format(k)
    elif (j == ['ACTIVE', 'IDLE']) or (j == ['IDLE', 'ACTIVE']):
        print 'ACTIVE and IDLE at {}'.format(k)
</code>```

results in

```<code>IDLE at 3/1.10
ACTIVE and IDLE at 3/1.1
ACTIVE and IDLE at 3/1.3
ACTIVE and IDLE at 3/1.4
ACTIVE at 3/1.5
ACTIVE and IDLE at 3/1.6
ACTIVE and IDLE at 3/1.7
ACTIVE and IDLE at 3/1.8
ACTIVE and IDLE at 3/1.9
</code>```

Title: Python - how to return list items from multiple lists of possible different lengths but get only non-matching pairs?

Body:
I have a multi line string as follows:

mystr = """
ACTIVE     3/1.1
IDLE       3/1.1
IDLE       3/1.2
IDLE       3/1.2
ACTIVE     3/1.3
IDLE       3/1.3
ACTIVE     3/1.4
IDLE       3/1.4
ACTIVE     3/1.5
ACTIVE     3/1.6
IDLE       3/1.6
ACTIVE     3/1.7
IDLE       3/1.7
ACTIVE     3/1.8
IDLE       3/1.8
ACTIVE     3/1.9
IDLE       3/1.9
IDLE       3/1.10
"""

or with a list, it would be:

mylist = ['ACTIVE     3/1.1 ', 'IDLE       3/1.1 ', 'IDLE       3/1.2 ', 'IDLE       3/1.2 ', 'ACTIVE     3/1.3 ', 'IDLE       3/1.3 ', 'ACTIVE     3/1.4 ', 'IDLE       3/1.4 ', 'ACTIVE     3/1.5 ', 'ACTIVE     3/1.6 ', 'IDLE       3/1.6 ', 'ACTIVE     3/1.7 ', 'IDLE       3/1.7 ', 'ACTIVE     3/1.8 ', 'IDLE       3/1.8 ', 'ACTIVE     3/1.9 ', 'IDLE       3/1.9 ', 'IDLE       3/1.10 ']

My goal is this...

for every pair of "x/y.z", such as 3/1.1 or 3/1.2, etc, there should be a matching ACTIVE and IDLE pairing.

In the event there is NO "ACTIVE" or NO "IDLE" pairing, then check if the pair shows both as IDLE. If yes, return it.
If there is no pair, then regardless if it shows as ACTIVE or IDLE, return the value as well.

I got this to work by doing the following:

this var is used to compare against some values of x/y.z, where "z" could be any value from 1 to 10. However, the pairing only matches on the "x/y." part:

lc = ['3/1.', '3/2.', '3/3.', '3/7.', '3/8.', '4/1.', '4/5.', '4/6.', '4/7.', '5/3.', '5/4.', '5/5.', '6/1.', '6/2.', '6/3.', '6/7.', '6/8.', '7/1.']

then rest of my script has:

outputsum = ""
pri_list = []
sec_list = []
stable_list = []

for intf in mylist:
  for g60 in lc:
    if g60 in intf:
      if "ACTIVE" in intf:
        pri_list.append(intf)
      if "IDLE" in intf.text:
        sec_list.append(intf)

for p in pri_list:
  t1 = p[p.find("ACTIVE")+11:]
  for s in sec_list:
    t2 = s[s.find("IDLE")+11:]
    if t1 == t2:
      print "Found matching pair!"
      if "ACTIVE" in p and "IDLE" in s:
        print "Putting valid ACTIVE/IDLE pairs into stable_list."
        stable_list.append(p)
        stable_list.append(s)

for pair in stable_list:
  for p1 in pri_list:
    if p1 == pair:
      pri_list.pop(pri_list.index(p1))
  for s1 in sec_list:
    if s1 == pair:
      sec_list.pop(sec_list.index(s1))

for i in pri_list:
  outputsum += i + "\n"

for i in sec_list:
  outputsum += i + "\n"

print outputsum
ACTIVE     3/1.5
IDLE       3/1.2
IDLE       3/1.2
IDLE       3/1.10

The output from "print outputsum" is what I expect to get, but doing all the above seems long/complex.

Is there an easier/better/faster way of doing this?

I checked many different threads and examples, tried with sets, intersections and differences, and a mix with other loops, but I couldn't get the results I wanted. After a few days playing with this, I finally came up with the above working example. But I'm sure there's a better way than how I did it above.

any thoughts?

Body:
You can use defaultdict, see below

# Clean up the data
j = [i.split('     ') for i in mylist]
j[:] = [[jj[0], jj[1].strip()] for jj in j]

# Make a list of idle/active for each key of "x/y.z"
from collections import defaultdict
d = defaultdict(list)
for i in j:
    d[i[1]].append(i[0])

# use some if/else to find pairing

for k,j in d.items():
    if j == ['IDLE']:
        print 'IDLE at {}'.format(k)
    elif j == ['ACTIVE']:
        print 'ACTIVE at {}'.format(k)
    elif (j == ['ACTIVE', 'IDLE']) or (j == ['IDLE', 'ACTIVE']):
        print 'ACTIVE and IDLE at {}'.format(k)

results in

IDLE at 3/1.10
ACTIVE and IDLE at 3/1.1
ACTIVE and IDLE at 3/1.3
ACTIVE and IDLE at 3/1.4
ACTIVE at 3/1.5
ACTIVE and IDLE at 3/1.6
ACTIVE and IDLE at 3/1.7
ACTIVE and IDLE at 3/1.8
ACTIVE and IDLE at 3/1.9


问:
Can I call a webhook from IBM Watsons conversational interface like API.ai
I'm familiar with using API.ai in a situation where an intent triggers an action which triggers a webhook that reaches out to an endpoint, then returns some info to API and then he client.

I'm wondering if the same is possible through Ibm Watson ( the GUI ), can't seem to find an example of the same scenario ... also, if this is possible, are there time restrictions ? For instance, in API, you must return from the request in 5 seconds .

答: You will have to handle it in application code by passing the context to the code.</p>


答:
I cleaned it up for you using tuples</p>

```<code>mylist = ['ACTIVE     3/1.1 ', 'IDLE       3/1.1 ', 'IDLE       3/1.2 ', 'IDLE       3/1.2 ', 'ACTIVE     3/1.3 ', 'IDLE       3/1.3 ', 'ACTIVE     3/1.4 ', 'IDLE       3/1.4 ', 'ACTIVE     3/1.5 ', 'ACTIVE     3/1.6 ', 'IDLE       3/1.6 ', 'ACTIVE     3/1.7 ', 'IDLE       3/1.7 ', 'ACTIVE     3/1.8 ', 'IDLE       3/1.8 ', 'ACTIVE     3/1.9 ', 'IDLE       3/1.9 ', 'IDLE       3/1.10 ']

version_map = {}
for status,version in (a.split() for a in mylist):
  if (version in version_map):
    version_map[version] = version_map[version] + (status,);
  else:
    version_map[version] = (status,);

allowed_combos = [('ACTIVE',),('IDLE',),('IDLE','IDLE')];
for versions,statuses in version_map.iteritems():
    if (statuses in allowed_combos):
      print versions,statuses;
</code>```

Body:
I cleaned it up for you using tuples

mylist = ['ACTIVE     3/1.1 ', 'IDLE       3/1.1 ', 'IDLE       3/1.2 ', 'IDLE       3/1.2 ', 'ACTIVE     3/1.3 ', 'IDLE       3/1.3 ', 'ACTIVE     3/1.4 ', 'IDLE       3/1.4 ', 'ACTIVE     3/1.5 ', 'ACTIVE     3/1.6 ', 'IDLE       3/1.6 ', 'ACTIVE     3/1.7 ', 'IDLE       3/1.7 ', 'ACTIVE     3/1.8 ', 'IDLE       3/1.8 ', 'ACTIVE     3/1.9 ', 'IDLE       3/1.9 ', 'IDLE       3/1.10 ']

version_map = {}
for status,version in (a.split() for a in mylist):
  if (version in version_map):
    version_map[version] = version_map[version] + (status,);
  else:
    version_map[version] = (status,);

allowed_combos = [('ACTIVE',),('IDLE',),('IDLE','IDLE')];
for versions,statuses in version_map.iteritems():
    if (statuses in allowed_combos):
      print versions,statuses;


问:
Accessing innermost map in a map of maps of maps C++
```<code>using namespace std;
typedef map<string, map<string, map<string, int> > > MY_MAP3;
</code>```

The above code is a snippet of a program I'm writing for a homework assignment. I basically want to to access the innermost map, and I need to do so with iterators.

The code below is what I am using to access the innermost map, but when I compile my program it throws a bunch "no viable conversion" errors.

```<code>MY_MAP3::iterator ptr = data2.find(sentence[0]);
map<string, map<string, int> >::iterator ptr2 = ptr->second;
map<string, int>::iterator ptr3 = ptr2->second;
</code>```

How would I access the innermost map in this triply nested map? Thanks.

For further clarification, the line

```<code>data2.find(sentence[0])
</code>```

is for returning an iterator for the outermost string. sentence is a vector and I'm searching for the frontmost word.

答:
Let's start with a simpler map:

```<code>std::map<std::string, int>
</code>```

An iterator for this map will have a first of std::string, and a second of int. Can't be any simpler than that.

And all maps work exactly the same way. Therefore, when your map is a

```<code>map<string, map<string, map<string, int> > >
</code>```

This means that the iterator for this map will refer to a first of a string, and a second of a map<string, map<string, int> >. Because that's what you have in your map.

```<code>map<string, map<string, int> >::iterator ptr2 = ptr->second;
</code>```

No. As you should now understand, your second is a  map<string, map<string, int> >. It is not an iterator of any kind. This can only be:

```<code>map<string, map<string, int> > &map2 = ptr->second;
</code>```

At this point if you want to continue drilling down into the second level map, you need to find() something first, in there.

Oh, and it also wouldn't hurt for you to check if your find() returned the end()ing iterator value, before attempting to do anything with it.

Body:
using namespace std;
typedef map<string, map<string, map<string, int> > > MY_MAP3;

The above code is a snippet of a program I'm writing for a homework assignment. I basically want to to access the innermost map, and I need to do so with iterators.

The code below is what I am using to access the innermost map, but when I compile my program it throws a bunch "no viable conversion" errors.

MY_MAP3::iterator ptr = data2.find(sentence[0]);
map<string, map<string, int> >::iterator ptr2 = ptr->second;
map<string, int>::iterator ptr3 = ptr2->second;

How would I access the innermost map in this triply nested map? Thanks.

For further clarification, the line

data2.find(sentence[0])

is for returning an iterator for the outermost string. sentence is a vector and I'm searching for the frontmost word.

Body:
Let's start with a simpler map:

std::map<std::string, int>

An iterator for this map will have a first of std::string, and a second of int. Can't be any simpler than that.

And all maps work exactly the same way. Therefore, when your map is a

map<string, map<string, map<string, int> > >

This means that the iterator for this map will refer to a first of a string, and a second of a map<string, map<string, int> >. Because that's what you have in your map.

map<string, map<string, int> >::iterator ptr2 = ptr->second;

No. As you should now understand, your second is a  map<string, map<string, int> >. It is not an iterator of any kind. This can only be:

map<string, map<string, int> > &map2 = ptr->second;

At this point if you want to continue drilling down into the second level map, you need to find() something first, in there.

Oh, and it also wouldn't hurt for you to check if your find() returned the end()ing iterator value, before attempting to do anything with it.


问:
TensorFlow: InternalError: Blas SGEMM launch failed
When I run sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) I get InternalError: Blas SGEMM launch failed. Here is the full error and stack trace:

```<code>InternalErrorTraceback (most recent call last)
<ipython-input-9-a3261a02bdce> in <module>()
      1 batch_xs, batch_ys = mnist.train.next_batch(100)
----> 2 sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    338     try:
    339       result = self._run(None, fetches, feed_dict, options_ptr,
--> 340                          run_metadata_ptr)
    341       if run_metadata:
    342         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    562     try:
    563       results = self._do_run(handle, target_list, unique_fetches,
--> 564                              feed_dict_string, options, run_metadata)
    565     finally:
    566       # The movers are no longer used. Delete them.

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
    635     if handle is None:
    636       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
--> 637                            target_list, options, run_metadata)
    638     else:
    639       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
    657       # pylint: disable=protected-access
    658       raise errors._make_specific_exception(node_def, op, error_message,
--> 659                                             e.code)
    660       # pylint: enable=protected-access
    661

InternalError: Blas SGEMM launch failed : a.shape=(100, 784), b.shape=(784, 10), m=100, n=10, k=784
     [[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_4, Variable/read)]]
Caused by op u'MatMul', defined at:
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 596, in launch_instance
    app.start()
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 442, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 162, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 883, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 391, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 199, in do_execute
    shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2723, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2825, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-d7414c4b6213>", line 4, in <module>
    y = tf.nn.softmax(tf.matmul(x, W) + b)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 1036, in matmul
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 911, in _mat_mul
    transpose_b=transpose_b, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2154, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1154, in __init__
    self._traceback = _extract_stack()
</code>```

Stack: EC2 g2.8xlarge machine, Ubuntu 14.04

答:
I encountered this problem and solved it by setting allow_soft_placement=True and gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3), which specifically define the fraction of memory of GPU been used. I guess this has helped to avoid two tensorflow processes competing for the GPU memory.

```<code>gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
sess = tf.Session(config=tf.ConfigProto(
  allow_soft_placement=True, log_device_placement=True))
</code>```

Body:
When I run sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) I get InternalError: Blas SGEMM launch failed. Here is the full error and stack trace:

InternalErrorTraceback (most recent call last)
<ipython-input-9-a3261a02bdce> in <module>()
      1 batch_xs, batch_ys = mnist.train.next_batch(100)
----> 2 sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in run(self, fetches, feed_dict, options, run_metadata)
    338     try:
    339       result = self._run(None, fetches, feed_dict, options_ptr,
--> 340                          run_metadata_ptr)
    341       if run_metadata:
    342         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _run(self, handle, fetches, feed_dict, options, run_metadata)
    562     try:
    563       results = self._do_run(handle, target_list, unique_fetches,
--> 564                              feed_dict_string, options, run_metadata)
    565     finally:
    566       # The movers are no longer used. Delete them.

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
    635     if handle is None:
    636       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
--> 637                            target_list, options, run_metadata)
    638     else:
    639       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.pyc in _do_call(self, fn, *args)
    657       # pylint: disable=protected-access
    658       raise errors._make_specific_exception(node_def, op, error_message,
--> 659                                             e.code)
    660       # pylint: enable=protected-access
    661

InternalError: Blas SGEMM launch failed : a.shape=(100, 784), b.shape=(784, 10), m=100, n=10, k=784
     [[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/gpu:0"](_recv_Placeholder_0/_4, Variable/read)]]
Caused by op u'MatMul', defined at:
  File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
    "__main__", fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "/usr/local/lib/python2.7/dist-packages/traitlets/config/application.py", line 596, in launch_instance
    app.start()
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelapp.py", line 442, in start
    ioloop.IOLoop.instance().start()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/ioloop.py", line 162, in start
    super(ZMQIOLoop, self).start()
  File "/usr/local/lib/python2.7/dist-packages/tornado/ioloop.py", line 883, in start
    handler_func(fd_obj, events)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "/usr/local/lib/python2.7/dist-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/tornado/stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/kernelbase.py", line 391, in execute_request
    user_expressions, allow_stdin)
  File "/usr/local/lib/python2.7/dist-packages/ipykernel/ipkernel.py", line 199, in do_execute
    shell.run_cell(code, store_history=store_history, silent=silent)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2723, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2825, in run_ast_nodes
    if self.run_code(code, result):
  File "/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.py", line 2885, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-4-d7414c4b6213>", line 4, in <module>
    y = tf.nn.softmax(tf.matmul(x, W) + b)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 1036, in matmul
    name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 911, in _mat_mul
    transpose_b=transpose_b, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 655, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2154, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1154, in __init__
    self._traceback = _extract_stack()

Stack: EC2 g2.8xlarge machine, Ubuntu 14.04

Body:
I encountered this problem and solved it by setting allow_soft_placement=True and gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3), which specifically define the fraction of memory of GPU been used. I guess this has helped to avoid two tensorflow processes competing for the GPU memory.

gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
sess = tf.Session(config=tf.ConfigProto(
  allow_soft_placement=True, log_device_placement=True))


问:
css position:fixed

```

I can add anything inside that div tag and it will rise above the top and stay fixed to the bottom left, but the javascript file will just stay where I've placed it within the webpage as if it can't be bothered to adhere to the .css rule.

I was wondering how I could get around this. Thank you for all your help.

答:
So, after much toying around, we figured out that viewing the source code for my website, we could see the javascript output. The .js file showed id's and we made a .css portion of the code to show the outputted information like so:

css

```<code>nav, #gblearn_message_holder {
position: fixed;
bottom: 0;
left: 0;
width: auto;
}
</code>```

html

```<code><div id="gblearn_message_holder">
<a title="Validate this page" href="javascript:void(0)" onclick="GBLEARN_TESTER.validatePage(this.form)">
<img src="http://my.gblearn.com/img/HTML5_Logo_2561.png" alt="html5 validator">
</a><a href="http://jigsaw.w3.org/css-validator/check/referer">
<img style="border:0;width:99px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!"></a>
<br>This page was last modified on 3/29/2017, 7:17:04 PM</div>
</code>```

Title: css position:fixed <script> tag within does not stay fixed

Body:
I'm having an issue trying to get a .js validation script to stay in a fixed location within a webpage.

My code for the css is:

div.fixed {
position: fixed;
bottom: 0;
left: 0;
}

HTML

I can add anything inside that div tag and it will rise above the top and stay fixed to the bottom left, but the javascript file will just stay where I've placed it within the webpage as if it can't be bothered to adhere to the .css rule.

I was wondering how I could get around this. Thank you for all your help.

Body:
So, after much toying around, we figured out that viewing the source code for my website, we could see the javascript output. The .js file showed id's and we made a .css portion of the code to show the outputted information like so:

css

nav, #gblearn_message_holder {
position: fixed;
bottom: 0;
left: 0;
width: auto;
}

html

<div id="gblearn_message_holder">
<a title="Validate this page" href="javascript:void(0)" onclick="GBLEARN_TESTER.validatePage(this.form)">
<img src="http://my.gblearn.com/img/HTML5_Logo_2561.png" alt="html5 validator">
</a><a href="http://jigsaw.w3.org/css-validator/check/referer">
<img style="border:0;width:99px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS!"></a>
<br>This page was last modified on 3/29/2017, 7:17:04 PM</div>


问:
Modal dialog closing immediately
I'm having a problem with the modal dialog, it activates when the user push and input button, then the modal dialog shows, and disappears immediately without do it anything.

The code:

```<code>$('form').submit(function(e) {
    var dialog = $("#dialog");
    if ($("#dialog").length == 0) {
        dialog = $('<div id="dialog" style="display:hidden"> Los datos ingresados son:</div>').appendTo('body');
    }
    dialog.load(
        $("#dialog").dialog({
            close: function(event, ui) {
                dialog.remove();
            },
            resizable: false,
            //height: 140,
            //width: 460
            modal: true,
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        })
    );
    return true;
});
</code>```

Besides, how can I make that, when the user push ok in the modal dialog, the event continues?

答:
I had both bootstrap files at the end of my code:

```<code><script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap.js"></script>
</code>```

Then I removed bootsrap.min.js and it worked, also I included at the end:

```<code><script>
    $(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
     });
</script>
</code>```

Title: Modal dialog closing immediately

Body:
I'm having a problem with the modal dialog, it activates when the user push and input button, then the modal dialog shows, and disappears immediately without do it anything.

The code:

$('form').submit(function(e) {
    var dialog = $("#dialog");
    if ($("#dialog").length == 0) {
        dialog = $('
 Los datos ingresados son:
').appendTo('body');
    }
    dialog.load(
        $("#dialog").dialog({
            close: function(event, ui) {
                dialog.remove();
            },
            resizable: false,
            //height: 140,
            //width: 460
            modal: true,
            buttons: {
                "Ok": function() {
                    $(this).dialog("close");
                },
                Cancel: function() {
                    $(this).dialog("close");
                }
            }
        })
    );
    return true;
});

Besides, how can I make that, when the user push ok in the modal dialog, the event continues?

Body:
I had both bootstrap files at the end of my code:

<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap.js"></script>

Then I removed bootsrap.min.js and it worked, also I included at the end:

<script>
    $(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
     });
</script>


问:
Nested Excel.Run() throws exception
I have an app in the Store which works in 2016, Online and Mac. However, today Excel Online stopped working while 2016 and Mac are fine. Hard to track down as calls to Excel.Run() just throw "General Exception" but it seems to be when I call nested Excel.Run(). So like

```<code>Excel.run(function (ctx) {
  var worksheets = ctx.workbook.worksheets.load("name");
  return ctx.sync()
     .then(function () {
     ...
     anotherfunction()
</code>```

and in anotherfunction() it calls Excel.run() again but then throws an exception.

** added **
if I call anotherfunction() outside of the first Excel.run() then it works.

Again, the code all worked a few days ago and still works on 2016 and Mac, but not in Excel Online. Any chance Excel Online was updated cause it seems weird and hard to debug. I'm using Office 365 at office.com.

Sorry, spent all afternoon looking at this and have run out of ideas.

Jon

* added complete snippet below *

```<code>(function () {

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {

        $(document).ready(function () {
        })
    }

})();

function allSheetsClick() {
    Excel.run(function (ctx) {
        var worksheets = ctx.workbook.worksheets.load("name");
        return ctx.sync()
            .then(function () {
                for (var i = 0; i < worksheets.items.length; i++) {
                    getSheetRange(worksheets.items[i].name);
                }
            });
    }).catch(function (error) {
        console.log("ERROR-" + error)
    });
}

function oneSheetClick() {
    getSheetRange("Sheet1");
}

function getSheetRange(sheetname) {

    var myRange = "$A$1:$Z$100";

    var bindingid = "MyBinding" + sheetname;
    var sheetrange = sheetname + "!" + myRange;
    // add binding
    Office.context.document.bindings.addFromNamedItemAsync(sheetrange, "matrix", { id: bindingid }, function (asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
            console.log("Binding added.");
        } else {
            console.log("ERROR addBinding() - " + error);
        }
    });

    Excel.run(function (ctx) {
        var cells = ctx.workbook.worksheets.getItem(sheetname).getRange(myRange).load(["values", "formulasR1C1"]);
        return ctx.sync()
            .then(function () {
                console.log("Got range. # rows - " + cells.values.length);
            });
    }).catch(function (error) {
        console.log("ERROR getRange() - " + error)
    });
}
</code>```

The problem turns out to be if I add a binding this causes an exception to be thrown in the later Excel.Run(). So in Excel Online it hits the line "console.log("ERROR getRange() - " + error)". If I comment out the binding add then it all works.

Is there a better way to structure this so I don't have to call Excel.Run() twice? But notice the second one is in a function which sometimes gets called directly.

Again, this works in Excel 2016 but started to fail in Excel Online recently (like a few days ago). Let me if you need anything else I have sample site if you need to test it.

答:
I can pass this on to the Excel Online team, but it would help to have a complete snippet.

That being said, doing nested Excel.run-s is inherently very dangerous, and can lead to a bunch of timing issues.  It also short-changes the benefits that you'd get with true batching.  What exactly are you trying to accomplish, that couldn't be part of a single Excel.run?

Title: Nested Excel.Run() throws exception

Body:
I have an app in the Store which works in 2016, Online and Mac. However, today Excel Online stopped working while 2016 and Mac are fine. Hard to track down as calls to Excel.Run() just throw "General Exception" but it seems to be when I call nested Excel.Run(). So like

Excel.run(function (ctx) {
  var worksheets = ctx.workbook.worksheets.load("name");
  return ctx.sync()
     .then(function () {
     ...
     anotherfunction()

and in anotherfunction() it calls Excel.run() again but then throws an exception.

** added **
if I call anotherfunction() outside of the first Excel.run() then it works.

Again, the code all worked a few days ago and still works on 2016 and Mac, but not in Excel Online. Any chance Excel Online was updated cause it seems weird and hard to debug. I'm using Office 365 at office.com.

Sorry, spent all afternoon looking at this and have run out of ideas.

Jon

* added complete snippet below *

(function () {

    // The initialize function must be run each time a new page is loaded.
    Office.initialize = function (reason) {

        $(document).ready(function () {
        })
    }

})();

function allSheetsClick() {
    Excel.run(function (ctx) {
        var worksheets = ctx.workbook.worksheets.load("name");
        return ctx.sync()
            .then(function () {
                for (var i = 0; i < worksheets.items.length; i++) {
                    getSheetRange(worksheets.items[i].name);
                }
            });
    }).catch(function (error) {
        console.log("ERROR-" + error)
    });
}

function oneSheetClick() {
    getSheetRange("Sheet1");
}

function getSheetRange(sheetname) {

    var myRange = "$A$1:$Z$100";

    var bindingid = "MyBinding" + sheetname;
    var sheetrange = sheetname + "!" + myRange;
    // add binding
    Office.context.document.bindings.addFromNamedItemAsync(sheetrange, "matrix", { id: bindingid }, function (asyncResult) {
        if (asyncResult.status === Office.AsyncResultStatus.Succeeded) {
            console.log("Binding added.");
        } else {
            console.log("ERROR addBinding() - " + error);
        }
    });

    Excel.run(function (ctx) {
        var cells = ctx.workbook.worksheets.getItem(sheetname).getRange(myRange).load(["values", "formulasR1C1"]);
        return ctx.sync()
            .then(function () {
                console.log("Got range. # rows - " + cells.values.length);
            });
    }).catch(function (error) {
        console.log("ERROR getRange() - " + error)
    });
}

The problem turns out to be if I add a binding this causes an exception to be thrown in the later Excel.Run(). So in Excel Online it hits the line "console.log("ERROR getRange() - " + error)". If I comment out the binding add then it all works.

Is there a better way to structure this so I don't have to call Excel.Run() twice? But notice the second one is in a function which sometimes gets called directly.

Again, this works in Excel 2016 but started to fail in Excel Online recently (like a few days ago). Let me if you need anything else I have sample site if you need to test it.


问:
How to specify a size for google pie charts?
I'm having trouble changing the size of a google pie chart that I have made. I'm trying to draw multiple pie charts with the size of each chart proportional to the total amount of data that I'm feeding it. I am aware that we are able to change the size of the div container of the chart by adding options to the chart like as follows:

```<code>var options = {width: 400, height: 300};
</code>```

However, what I'm interested in, is not changing the size of the div, but of the actual pie chart itself.

Is there any way I can change the radius of the pie chart?

I've searched around and wasn't able to find anything. Here is quick paint of what I mean:

As you can see, what I would like is for the div to remain on the same size but the size of the circle to change, depending on what value I feed it.

Any help is appreciated

答:
try the option for chartArea

e.g.

chartArea: {width: 400, height: 300}

Body:
I'm having trouble changing the size of a google pie chart that I have made. I'm trying to draw multiple pie charts with the size of each chart proportional to the total amount of data that I'm feeding it. I am aware that we are able to change the size of the div container of the chart by adding options to the chart like as follows:

var options = {width: 400, height: 300};

However, what I'm interested in, is not changing the size of the div, but of the actual pie chart itself.

Is there any way I can change the radius of the pie chart?

I've searched around and wasn't able to find anything. Here is quick paint of what I mean:

As you can see, what I would like is for the div to remain on the same size but the size of the circle to change, depending on what value I feed it.

Any help is appreciated