问:
Make database class
I have the following class:

```<code>public class Database  {
    private Connection connection;
    private MyApp instance = MyApp.getInstance();
    private String database, host, username, password, port;
    private Config config = new Config();

    public Connection Database() {
        database = config.get("database.database");
        host = config.get("database.host");
        username = config.get("database.username");
        password = config.get("database.password");
        port = config.get("database.port");
        try {
            connection = openConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }

    private Connection openConnection() throws SQLException, ClassNotFoundException {
        if (connection != null && !connection.isClosed()) {

        }

        synchronized (instance) {
            if (connection != null && !connection.isClosed()) {

            }
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
        }
        return connection;
    }

}
</code>```

I'd like to be able to return connection on this class so I can, in other classes, do connection = new Database(). and then Statement statement = connection.createStatement();.

This probably and feels like this isn't the best way, and I'm not sure what is a better way of creating a database class. My attempt was trying to do return connection; in the constructor but that error'd out.

How do I do this?

答:
You can try something like this :

```<code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Baza {

private static java.sql.Connection conect = null;
private static final String url = "jdbc:mysql://localhost/Application?autoReconnect=true&useSSL=false";
private static final String username = "root";
private static final String password = "";
private final String urlWithoutBase= "jdbc:mysql://localhost:3306/";

public Baza() {
    try {
        conect = DriverManager.getConnection(urlWithoutBase, username, password);
        createDataBase();
        conect.close();
        openConnection();
        createTablePeople();
        conect.close();

    } catch (SQLException ex) {
       ex.printStackTrace();
    }
}

public Connection openConnection() {
    try {
        conect = DriverManager.getConnection(url, username, password);
        return conect;
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return conect;
}

public void closeConnection() {
    try {
        conect.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

 private void createDataBase() throws SQLException {
    Statement statement = conect.createStatement();
    String query = "CREATE DATABASE IF NOT EXISTS Application;";
    statement.execute(query);
}
 private void createTablePeople() throws SQLException{
      Statement statement = conect.createStatement();
    String query = "CREATE TABLE IF NOT EXISTS Osobe("
            + "id INT NOT NULL AUTO_INCREMENT,"
            + "name VARCHAR(30) NOT NULL,"
            + "surname VARCHAR(30) NOT NULL,"
            + "date VARCHAR(30) NOT NULL,"
            + "PRIMARY KEY(id));";
    statement.execute(query);
 }
</code>```

}

Title: Make database class

Body:
I have the following class:

public class Database  {
    private Connection connection;
    private MyApp instance = MyApp.getInstance();
    private String database, host, username, password, port;
    private Config config = new Config();

    public Connection Database() {
        database = config.get("database.database");
        host = config.get("database.host");
        username = config.get("database.username");
        password = config.get("database.password");
        port = config.get("database.port");
        try {
            connection = openConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return connection;
    }

    private Connection openConnection() throws SQLException, ClassNotFoundException {
        if (connection != null && !connection.isClosed()) {

        }

        synchronized (instance) {
            if (connection != null && !connection.isClosed()) {

            }
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
        }
        return connection;
    }

}

I'd like to be able to return connection on this class so I can, in other classes, do connection = new Database(). and then Statement statement = connection.createStatement();.

This probably and feels like this isn't the best way, and I'm not sure what is a better way of creating a database class. My attempt was trying to do return connection; in the constructor but that error'd out.

How do I do this?

Body:
You can try something like this :

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

public class Baza {

private static java.sql.Connection conect = null;
private static final String url = "jdbc:mysql://localhost/Application?autoReconnect=true&useSSL=false";
private static final String username = "root";
private static final String password = "";
private final String urlWithoutBase= "jdbc:mysql://localhost:3306/";

public Baza() {
    try {
        conect = DriverManager.getConnection(urlWithoutBase, username, password);
        createDataBase();
        conect.close();
        openConnection();
        createTablePeople();
        conect.close();

    } catch (SQLException ex) {
       ex.printStackTrace();
    }
}

public Connection openConnection() {
    try {
        conect = DriverManager.getConnection(url, username, password);
        return conect;
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return conect;
}

public void closeConnection() {
    try {
        conect.close();
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
}

 private void createDataBase() throws SQLException {
    Statement statement = conect.createStatement();
    String query = "CREATE DATABASE IF NOT EXISTS Application;";
    statement.execute(query);
}
 private void createTablePeople() throws SQLException{
      Statement statement = conect.createStatement();
    String query = "CREATE TABLE IF NOT EXISTS Osobe("
            + "id INT NOT NULL AUTO_INCREMENT,"
            + "name VARCHAR(30) NOT NULL,"
            + "surname VARCHAR(30) NOT NULL,"
            + "date VARCHAR(30) NOT NULL,"
            + "PRIMARY KEY(id));";
    statement.execute(query);
 }

}


来源: stackexchange

问:
Troubles with accessing property in derivied class
I have an abstract class:

```<code>public abstract class Node
{
    protected readonly List<Node> Nodes = new List<Node>();
    public Node[] ChildNodes => Nodes.ToArray();
    ...
}
</code>```

And derived from him:

```<code>public sealed class NodeArray<T> : Node where T: Node
{
    private readonly List<T> _array = new List<T>();
    private new List<Node> Nodes => _array.Cast<Node>().ToList();
    public new Node[] ChildNodes => _array.Cast<Node>().ToArray();
    ...
}
</code>```

Node.Nodes list may contain NodeArray<Smth> through.
But, when I'm trying to recursively enumerate nodes, and I'm getting one of type NodeArray, it returns empty ChildNodes value (of base class I guess).
And when I debugged following code, Intellisense shows two identical properties with the same name and same type!

Screenshot

Loop code:

```<code>protected void LoadNode(Node node, XmlNode xmlNode)
    {
        foreach (XmlNode childNode in xmlNode.ChildNodes)
        {
            if (childNode.HasChildNodes)
            {
                var child = node.ChildNodes.First(p => p.Name == childNode.Name);  // <----- Stuck here
                if(child == null)
                    throw new Exception("Unknown child " + childNode.Name + " in Node " + node.Name);

                LoadNode(child, childNode);
            }
            else
            {
                node[childNode.Name] = childNode.Value;
            }
        }

        node.Load();
    }
</code>```

Hope you help! Sorry for bed English :)

答:
Your issue might be that you're using member hiding (with the new keyword) rather than overriding. With member hiding, the base class and the derived class contain separate definitions of the property, despite having the same name. Thus, if you create a NodeArray<T> instance, populate its _array collection, and then pass it as a Node reference, then ChildNodes property would still be returning the empty collection of the Node.Nodes base property, rather than the NodeArray<T>._array field like you'd expect.

To resolve this issue, switch to using virtual and overridden members, as shown below:

```<code>public abstract class Node
{
    protected virtual List<Node> Nodes { get; } = new List<Node>();
    public virtual Node[] ChildNodes => Nodes.ToArray();
    ...
}

public sealed class NodeArray<T> : Node where T: Node
{
    private readonly List<T> _array = new List<T>();
    protected override List<Node> Nodes => _array.Cast<Node>().ToList();
    public override Node[] ChildNodes => _array.Cast<Node>().ToArray();
    ...
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an abstract class:

public abstract class Node
{
    protected readonly List<Node> Nodes = new List<Node>();
    public Node[] ChildNodes => Nodes.ToArray();
    ...
}

And derived from him:

public sealed class NodeArray<T> : Node where T: Node
{
    private readonly List<T> _array = new List<T>();
    private new List<Node> Nodes => _array.Cast<Node>().ToList();
    public new Node[] ChildNodes => _array.Cast<Node>().ToArray();
    ...
}

Node.Nodes list may contain NodeArray<Smth> through.
But, when I'm trying to recursively enumerate nodes, and I'm getting one of type NodeArray, it returns empty ChildNodes value (of base class I guess).
And when I debugged following code, Intellisense shows two identical properties with the same name and same type!

Screenshot

Loop code:

protected void LoadNode(Node node, XmlNode xmlNode)
    {
        foreach (XmlNode childNode in xmlNode.ChildNodes)
        {
            if (childNode.HasChildNodes)
            {
                var child = node.ChildNodes.First(p => p.Name == childNode.Name);  // <----- Stuck here
                if(child == null)
                    throw new Exception("Unknown child " + childNode.Name + " in Node " + node.Name);

                LoadNode(child, childNode);
            }
            else
            {
                node[childNode.Name] = childNode.Value;
            }
        }

        node.Load();
    }

Hope you help! Sorry for bed English :)

Body:
Your issue might be that you're using member hiding (with the new keyword) rather than overriding. With member hiding, the base class and the derived class contain separate definitions of the property, despite having the same name. Thus, if you create a NodeArray<T> instance, populate its _array collection, and then pass it as a Node reference, then ChildNodes property would still be returning the empty collection of the Node.Nodes base property, rather than the NodeArray<T>._array field like you'd expect.

To resolve this issue, switch to using virtual and overridden members, as shown below:

public abstract class Node
{
    protected virtual List<Node> Nodes { get; } = new List<Node>();
    public virtual Node[] ChildNodes => Nodes.ToArray();
    ...
}

public sealed class NodeArray<T> : Node where T: Node
{
    private readonly List<T> _array = new List<T>();
    protected override List<Node> Nodes => _array.Cast<Node>().ToList();
    public override Node[] ChildNodes => _array.Cast<Node>().ToArray();
    ...
}


问:
Is Google Analytics Secure to Track Business Application Usage?
I have recently been required to implement some Usage Tracking to a web-based Business Application. Basically what needs to be tracked is what pages in the application are being used and for how long users stay on those pages. The application is hosted on the internet and is HTML/JavaScript.

I could use Google Analytics to track page views, visits and browser capabilities, but is it secure enough to use for business applications?

Does anyone else use Google Analytics to track web-based business application usage? Or do you have some thoughts on this?

Also, I couldn't find anything from Google specifically stating whether this is a good or bad thing to do.

答:
It depends what you want to be secure.

Gathered data, if you trust Google, is pretty secure.

However, Analytics data can be tampered with. Someone can read your Analytics ID from page source (or HTTP traffic) and submit fake pageviews, events, change custom variables, etc.

ContentLicense: CC BY-SA 2.5


问:
C# - Expression parameter into another Expression using lambda?
As part of a WPF application I'm building an expression tree and generating a Predicate to use as a filter. The code looks something like this:

```<code>public Expression BuildExpression(Expression parameter, string value)
{
    MethodInfo toStringMethod = new Func<Object, string>((a) => a.ToString()).Method;
    Expression lhs = Expression.Call(parameter, toStringMethod );
    ConstantExpression rhs = Expression.Constant(value);
    BinaryExpression result = Expression.Equal(lhs, rhs);
    return result;
}
</code>```

This is because the parameter is an Expression of unknown type - it might be an int, string, Guid or anything else. The problem is that it's difficult to understand what's going on here without copious comments. I'd really like to use a lambda here:

```<code>return parameter => parameter.ToString() == value;
</code>```

The problem is that this doesn't work as intended - the resulting delegate would call ToString() on the Expression instead of the value of the expression. If it helps, parameter is a MemberExpression.

答:
I was able to find a way to do this with very little extra code. The main inspiration for this solution was Mark Gravell's answer to Combining two expressions (Expression<Func<T, bool>>)

Starting from .net 4.0. There is the ExpressionVistor class which
  allows you to build expressions that are EF safe.

Expression<TDelegate> is derived from LambdaExpression (if you're interested in learning more about how these actually work I encourage you to check out the "LINQ - Expression Tree Visualizer" sample, currently located at https://code.msdn.microsoft.com/LINQ-Expression-Tree-47608cb5). This line of code:

```<code>Expression<Predicate<Object>> e1 = a => a.ToString() == "foo";
</code>```

Creates a LambdaExpression with a single ParameterExpression(Type: Object, ReturnType: Boolean, Body:(LogicalBinaryExpression)). Using a custom ExpressionVisitor we can modify the body of the Lambda to create the same result as my previous code:

```<code>public class ReplaceExpressionVisitor
    : ExpressionVisitor
{
    private readonly Expression _oldValue;
    private readonly Expression _newValue;

    public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
    {
        _oldValue = oldValue;
        _newValue = newValue;
    }

    public override Expression Visit(Expression node)
    {
        if (node == _oldValue)
            return _newValue;
        return base.Visit(node);
    }
}

// Elsewhere...
public Expression BuildExpression(Expression parameter, string value)
{
    Expression<Predicate<Object>> e1 = a => a.ToString() == value;
    return (new ReplaceExpressionVisitor(e1.Parameters[0], parameter)).Visit(e1.Body);
}
</code>```

Further cleanup is definitely possible (provide a static and/or extension method) but this meets my needs.

Body:
As part of a WPF application I'm building an expression tree and generating a Predicate to use as a filter. The code looks something like this:

public Expression BuildExpression(Expression parameter, string value)
{
    MethodInfo toStringMethod = new Func<Object, string>((a) => a.ToString()).Method;
    Expression lhs = Expression.Call(parameter, toStringMethod );
    ConstantExpression rhs = Expression.Constant(value);
    BinaryExpression result = Expression.Equal(lhs, rhs);
    return result;
}

This is because the parameter is an Expression of unknown type - it might be an int, string, Guid or anything else. The problem is that it's difficult to understand what's going on here without copious comments. I'd really like to use a lambda here:

return parameter => parameter.ToString() == value;

The problem is that this doesn't work as intended - the resulting delegate would call ToString() on the Expression instead of the value of the expression. If it helps, parameter is a MemberExpression.

Body:
I was able to find a way to do this with very little extra code. The main inspiration for this solution was Mark Gravell's answer to Combining two expressions (Expression<Func<T, bool>>)

Starting from .net 4.0. There is the ExpressionVistor class which
  allows you to build expressions that are EF safe.

Expression<TDelegate> is derived from LambdaExpression (if you're interested in learning more about how these actually work I encourage you to check out the "LINQ - Expression Tree Visualizer" sample, currently located at https://code.msdn.microsoft.com/LINQ-Expression-Tree-47608cb5). This line of code:

Expression<Predicate<Object>> e1 = a => a.ToString() == "foo";

Creates a LambdaExpression with a single ParameterExpression(Type: Object, ReturnType: Boolean, Body:(LogicalBinaryExpression)). Using a custom ExpressionVisitor we can modify the body of the Lambda to create the same result as my previous code:

public class ReplaceExpressionVisitor
    : ExpressionVisitor
{
    private readonly Expression _oldValue;
    private readonly Expression _newValue;

    public ReplaceExpressionVisitor(Expression oldValue, Expression newValue)
    {
        _oldValue = oldValue;
        _newValue = newValue;
    }

    public override Expression Visit(Expression node)
    {
        if (node == _oldValue)
            return _newValue;
        return base.Visit(node);
    }
}

// Elsewhere...
public Expression BuildExpression(Expression parameter, string value)
{
    Expression<Predicate<Object>> e1 = a => a.ToString() == value;
    return (new ReplaceExpressionVisitor(e1.Parameters[0], parameter)).Visit(e1.Body);
}

Further cleanup is definitely possible (provide a static and/or extension method) but this meets my needs.


问:
Storing class objects locally in swift 3
I've ran into a problem storing "notes" in swift.

Here is the note class

```<code>class Note {

    var title = ""
    var content = ""
    var color = UIColor()

}
</code>```

And i get the notes like this

```<code>var notes: [Note] = []
</code>```

Ive added a couple notes

```<code>    let note1 = Note()
    note1.title = "Houses"
    note1.content = "A knowledgable and experienced staff ready to help you build the… "
    note1.color = #colorLiteral(red: 0.515632689, green: 0.2357951403, blue: 0.9598689675, alpha: 1)

    let note2 = Note()
    note2.title = "Note"
    note2.content = "A beautifully redesined note app"
    note2.color = #colorLiteral(red: 0.8978558183, green: 0.7694990635, blue: 0.2824732065, alpha: 1)

    let note3 = Note()
    note3.title = "Note"
    note3.content = "A beautifully redesined note app"
    note3.color = #colorLiteral(red: 0.2296327353, green: 0.8767140508, blue: 0.5295107365, alpha: 1)

    let note4 = Note()
    note4.title = "Note"
    note4.content = "A beautifully redesined note app"
    note4.color = #colorLiteral(red: 0.8787152171, green: 0.4267094135, blue: 0.2448620498, alpha: 1)

    notes.append(note1)
    notes.append(note2)
    notes.append(note3)
    notes.append(note4)
</code>```

And now i need to save them and retrieve these notes so users can make there own notes and they will save on there device locally

Thanks for helping :)

答:
Pick a db or db equivalent and learn how to persist data.

Core data. Obviously

Realm. My preference. You've already done half the work:

```<code>import RealmSwift

class Note: Object {

    dynamic var title = ""
    dynamic var content = ""
    dynamic var color = "" // rgb value of "FF03A4", for instance
}
</code>```

Firebase. New and exciting.

It all depends on your needs. Step one: figure out what your needs are then refer to each to find its strengths. The bottom line is you've done the heavy lifting by defining your data in a way that can be retrieved (and saved). You need to master data persistence to do most useful things with your apps (remembering and customizing for your user).

Body:
I've ran into a problem storing "notes" in swift.

Here is the note class

class Note {

    var title = ""
    var content = ""
    var color = UIColor()

}

And i get the notes like this

var notes: [Note] = []

Ive added a couple notes

    let note1 = Note()
    note1.title = "Houses"
    note1.content = "A knowledgable and experienced staff ready to help you build the… "
    note1.color = #colorLiteral(red: 0.515632689, green: 0.2357951403, blue: 0.9598689675, alpha: 1)

    let note2 = Note()
    note2.title = "Note"
    note2.content = "A beautifully redesined note app"
    note2.color = #colorLiteral(red: 0.8978558183, green: 0.7694990635, blue: 0.2824732065, alpha: 1)

    let note3 = Note()
    note3.title = "Note"
    note3.content = "A beautifully redesined note app"
    note3.color = #colorLiteral(red: 0.2296327353, green: 0.8767140508, blue: 0.5295107365, alpha: 1)

    let note4 = Note()
    note4.title = "Note"
    note4.content = "A beautifully redesined note app"
    note4.color = #colorLiteral(red: 0.8787152171, green: 0.4267094135, blue: 0.2448620498, alpha: 1)

    notes.append(note1)
    notes.append(note2)
    notes.append(note3)
    notes.append(note4)

And now i need to save them and retrieve these notes so users can make there own notes and they will save on there device locally

Thanks for helping :)

Body:
Pick a db or db equivalent and learn how to persist data.

Core data. Obviously

Realm. My preference. You've already done half the work:

import RealmSwift

class Note: Object {

    dynamic var title = ""
    dynamic var content = ""
    dynamic var color = "" // rgb value of "FF03A4", for instance
}

Firebase. New and exciting.

It all depends on your needs. Step one: figure out what your needs are then refer to each to find its strengths. The bottom line is you've done the heavy lifting by defining your data in a way that can be retrieved (and saved). You need to master data persistence to do most useful things with your apps (remembering and customizing for your user).


问:
How to clear a window at runtime?
I am just learning Python.  I have a program that will choose a random image each time you click the mouse!!  How do I clear the window so images don't stack.  I am sure I am asking this question wrong because google is no help :(

Thank you and here is the code:

```<code>from graphics import*
import random
import os

win = GraphWin("My Window", 500, 500)

for x in range(5):

    cards = ["1.gif","2.gif","3.gif"]
    rand_card = random.choice(cards)
    img = Image(Point(250, 250), rand_card)

    win.setBackground('Black')
    img.draw(win)

    win.getMouse()
</code>```

答:
Based on the code at http://mcsp.wartburg.edu/zelle/python/graphics.py, the Image class has an undraw function.  You can simply add image.undraw() with a check to make sure it's not None (as it would be for the first time in the loop:

```<code>img = None
win = GraphWin("My Window", 500, 500)

for x in range(5):

    cards = ["1.gif","2.gif","3.gif"]
    rand_card = random.choice(cards)
    if img:
        img.undraw()
    img = Image(Point(250, 250), rand_card)

    win.setBackground('Black')
    img.draw(win)

    win.getMouse()
</code>```

(Note, change added based on cdlane's comment - initialize img to None so we don't get variable undefined.)

Title: How to clear a window at runtime?

Body:
I am just learning Python.  I have a program that will choose a random image each time you click the mouse!!  How do I clear the window so images don't stack.  I am sure I am asking this question wrong because google is no help :(

Thank you and here is the code:

from graphics import*
import random
import os

win = GraphWin("My Window", 500, 500)

for x in range(5):

    cards = ["1.gif","2.gif","3.gif"]
    rand_card = random.choice(cards)
    img = Image(Point(250, 250), rand_card)

    win.setBackground('Black')
    img.draw(win)

    win.getMouse()

Body:
Based on the code at http://mcsp.wartburg.edu/zelle/python/graphics.py, the Image class has an undraw function.  You can simply add image.undraw() with a check to make sure it's not None (as it would be for the first time in the loop:

img = None
win = GraphWin("My Window", 500, 500)

for x in range(5):

    cards = ["1.gif","2.gif","3.gif"]
    rand_card = random.choice(cards)
    if img:
        img.undraw()
    img = Image(Point(250, 250), rand_card)

    win.setBackground('Black')
    img.draw(win)

    win.getMouse()

(Note, change added based on cdlane's comment - initialize img to None so we don't get variable undefined.)


问:
Jenkins not reading ClearCase config spec from file
I am using the ClearCase plugin with Jenkins, and am attempting to read a config spec from a file in the ClearCase VOB. The file with the config spec is on the server which Jenkins runs on, and in the build step I ran

```<code>for /f "tokens=*" %%a in (path\to\file\configSpecTest-2.txt) do echo %%a
</code>```

which prints out the contents of a file, and it successfully prints out the text file. This proves that the path I am using is correct and the server has read access to that file.

Is this a bug with Jenkins?

EDIT: after digging into the documentation, there is a caveat that the file must be reachable by the master node. Does anybody know why this is?

答:
Generally, the master node can get the view content, and then pass the content to a slave.

Check if you can configure your Jenkins job in order to perform that step on the master, and not from a slave where the Jenkins ClearCase plugin seems to limit the config spec access.

Body:
I am using the ClearCase plugin with Jenkins, and am attempting to read a config spec from a file in the ClearCase VOB. The file with the config spec is on the server which Jenkins runs on, and in the build step I ran

for /f "tokens=*" %%a in (path\to\file\configSpecTest-2.txt) do echo %%a

which prints out the contents of a file, and it successfully prints out the text file. This proves that the path I am using is correct and the server has read access to that file.

Is this a bug with Jenkins?

EDIT: after digging into the documentation, there is a caveat that the file must be reachable by the master node. Does anybody know why this is?


问:
How to plot a single point in matplotlib
I'd like to plot a single point on my graph, but it seems like they all need to plot as either a list or equation.

I need to plot like ax.plot(x, y) and a dot will be appeared at my x, y coordinates on my graph.

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import numpy
fig = plt.figure()
plt.xlabel('Width')
plt.ylabel('Height')
ax = fig.gca()
ax.plot(105, 200)
plt.grid()
plt.show()
</code>```

答:
This worked for me:</p>
```<code>plt.plot(105,200,'ro')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'd like to plot a single point on my graph, but it seems like they all need to plot as either a list or equation.

I need to plot like ax.plot(x, y) and a dot will be appeared at my x, y coordinates on my graph.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import numpy
fig = plt.figure()
plt.xlabel('Width')
plt.ylabel('Height')
ax = fig.gca()
ax.plot(105, 200)
plt.grid()
plt.show()

Body:
This worked for me:

plt.plot(105,200,'ro')


问:
How to dynamically shrink or grow panel contents?
I have an issue with making my program panel fit into a low resolution. Like if I have a resolution of 800 x 600, and my panel is larger than that, so everything gets cut off, especially the buttons that are on the bottom of the screen.

So, I made a mock program as an example:

```<code>import wx

MAIN_FRAME_SIZE = (190, 150)

class MainFrame(wx.Frame):

    def __init__(self):

        wx.Frame.__init__(self, None, id = -1, title = 'Hello, World!', size = MAIN_FRAME_SIZE)

        vertBox = wx.BoxSizer(wx.VERTICAL)

        staticText = wx.StaticText(self, label = 'Hello, World!')

        vertBox.Add(staticText, 0, wx.ALL, 40)

        self.SetSizer(vertBox)

if __name__ == '__main__':
    app = wx.App()
    frame = MainFrame()
    frame.Show(True)
    app.MainLoop()
</code>```

So, then my question is how do I make the 'Hello, World!' text larger when the MainFrame gets larger, and how do I do the same when the MainFrame gets smaller?

Thanks.

答:
You can select your font size depending on the frame size using some heuristics or you can compute the length of your string using GetTextExtent() and find the font size for which it will be equal to what you want.

To do this dynamically when the frame is resized, you need to catch wxEVT_SIZE and change the font in its handler.

Body:
I have an issue with making my program panel fit into a low resolution. Like if I have a resolution of 800 x 600, and my panel is larger than that, so everything gets cut off, especially the buttons that are on the bottom of the screen.

So, I made a mock program as an example:

import wx

MAIN_FRAME_SIZE = (190, 150)

class MainFrame(wx.Frame):

    def __init__(self):

        wx.Frame.__init__(self, None, id = -1, title = 'Hello, World!', size = MAIN_FRAME_SIZE)

        vertBox = wx.BoxSizer(wx.VERTICAL)

        staticText = wx.StaticText(self, label = 'Hello, World!')

        vertBox.Add(staticText, 0, wx.ALL, 40)

        self.SetSizer(vertBox)

if __name__ == '__main__':
    app = wx.App()
    frame = MainFrame()
    frame.Show(True)
    app.MainLoop()

So, then my question is how do I make the 'Hello, World!' text larger when the MainFrame gets larger, and how do I do the same when the MainFrame gets smaller?

Thanks.


问:
Get generic trait from ordinal one without Self type?
I have two traits, one ordinal (Foo), another generic (TypedFoo<T>). I have several structures, each of them have both traits implemented.

Is it possible to convert from Foo to TypedFoo<T>, without converting to an intermediate structure?

```<code>trait Foo {
    fn f(&mut self);
}

trait TypedFoo<T> {
    fn get(&self) -> T;
}

#[derive(Clone)]
struct Data(i32);

impl Foo for Data {
    fn f(&mut self) {
        self.0 += 1;
    }
}

impl TypedFoo<Data> for Data {
    fn get(&self) -> Data {
        self.clone()
    }
}

//struct Data2(f64);
//impl Foo for Data2...
//impl TypedFoo<Data2> for Data2..

fn main() {
    let v: Vec<Box<Foo>> = vec![Box::new(Data(1))];
}
</code>```

I can change Foo to this:

```<code>trait Foo {
    fn f(&mut self);
    fn get_self(&self) -> &Any;
}
</code>```

Then get v[0].get_self() downcast_ref to Data, and then Data to &TypedFoo<Data>.

But is it possible to get &TypedFoo<Data> from &Foo without knowing "data type", some analog of Any but for a trait.

I imagine syntax like this:

```<code>let foo: &Foo = ...;
if let Some(typed_foo) = foo.cast::<Data>() {

}
</code>```

My question is different from Can I cast between two traits?
 because I have one generic and one ordinal trait. If I had two ordinal traits then the solution would be as simple as:

```<code>trait Foo {
    fn f(&mut self);
    fn as_typed_foo(&self) -> &TypedFoo;
}
</code>```

Since TypedFoo is generic, none of the answers in that question help me. One possible solution could be:

```<code>trait Foo {
    fn f(&mut self);
    fn cast(&mut self, type_id: ::std::any::TypeId) -> Option<*mut ::std::os::raw::c_void>;
}
</code>```

I am not sure how safe it is to cast *mut TypedFoo<T> -> *mut ::std::os::raw::c_void and then back to *mut TypedFoo<T>.

答:
The signature of the function that you want is

```<code>fn convert<T>(x: &Box<Foo>) -> &TypedFoo<T>
</code>```

To type check this signature compiler must know that the type inside Box implements TypedFoo<T> for some T. But conversion into trait-object erases information about the real type. Which means that it is impossible to statically type check signature of this function.

So we need to do it dynamically and if we want to use types a current crate doesn't know about, we'll need to resort to unsafe.

One option is to limit a set of types, which can be used in TypedFoo, and provide conversion functions in the Foo trait. This allows to avoid unsafe.

Playground link

Second option is to add to trait Foo a function, which returns a slice of pairs (TypeId, *const ()). The pointer is a type erased pointer to function, which does actual conversion. Conversion function searches required type identifier and executes corresponding function.

Playground link

For the sake of demonstration I used Vec instead of slice in conversion_registrar. But it shouldn't be too hard to change return type to &'static [(TypeId, *const ())], using lazy_static crate.

Body:
I have two traits, one ordinal (Foo), another generic (TypedFoo<T>). I have several structures, each of them have both traits implemented.

Is it possible to convert from Foo to TypedFoo<T>, without converting to an intermediate structure?

trait Foo {
    fn f(&mut self);
}

trait TypedFoo<T> {
    fn get(&self) -> T;
}

#[derive(Clone)]
struct Data(i32);

impl Foo for Data {
    fn f(&mut self) {
        self.0 += 1;
    }
}

impl TypedFoo<Data> for Data {
    fn get(&self) -> Data {
        self.clone()
    }
}

//struct Data2(f64);
//impl Foo for Data2...
//impl TypedFoo<Data2> for Data2..

fn main() {
    let v: Vec<Box<Foo>> = vec![Box::new(Data(1))];
}

I can change Foo to this:

trait Foo {
    fn f(&mut self);
    fn get_self(&self) -> &Any;
}

Then get v[0].get_self() downcast_ref to Data, and then Data to &TypedFoo<Data>.

But is it possible to get &TypedFoo<Data> from &Foo without knowing "data type", some analog of Any but for a trait.

I imagine syntax like this:

let foo: &Foo = ...;
if let Some(typed_foo) = foo.cast::<Data>() {

}

My question is different from Can I cast between two traits?
 because I have one generic and one ordinal trait. If I had two ordinal traits then the solution would be as simple as:

trait Foo {
    fn f(&mut self);
    fn as_typed_foo(&self) -> &TypedFoo;
}

Since TypedFoo is generic, none of the answers in that question help me. One possible solution could be:

trait Foo {
    fn f(&mut self);
    fn cast(&mut self, type_id: ::std::any::TypeId) -> Option<*mut ::std::os::raw::c_void>;
}

I am not sure how safe it is to cast *mut TypedFoo<T> -> *mut ::std::os::raw::c_void and then back to *mut TypedFoo<T>.

Body:
The signature of the function that you want is

fn convert<T>(x: &Box<Foo>) -> &TypedFoo<T>

To type check this signature compiler must know that the type inside Box implements TypedFoo<T> for some T. But conversion into trait-object erases information about the real type. Which means that it is impossible to statically type check signature of this function.

So we need to do it dynamically and if we want to use types a current crate doesn't know about, we'll need to resort to unsafe.

One option is to limit a set of types, which can be used in TypedFoo, and provide conversion functions in the Foo trait. This allows to avoid unsafe.

Playground link

Second option is to add to trait Foo a function, which returns a slice of pairs (TypeId, *const ()). The pointer is a type erased pointer to function, which does actual conversion. Conversion function searches required type identifier and executes corresponding function.

Playground link

For the sake of demonstration I used Vec instead of slice in conversion_registrar. But it shouldn't be too hard to change return type to &'static [(TypeId, *const ())], using lazy_static crate.


问:
what is the purpose of using <html:text instead of <input type="text" in struts?
in struts programming we use <html:text instead of <input type="text" But we can use <input type="text" and it will work also what is the specific reason for using <html:text tag?
can any one answer me please?

答:
The only reason to use

```<code><html:text
</code>```

instead of using normal

```<code><input type=text
</code>```

is the support for Internationalization. With

```<code><html:text
</code>```

we use the attribute key, which names the value to be fetched from the Resource.properties file. So for internationalization, all we have to do is change the values stored against the keys in the resource.properties file and nothing else.

Body:
The only reason to use

<html:text

instead of using normal

<input type=text

is the support for Internationalization. With

<html:text

we use the attribute key, which names the value to be fetched from the Resource.properties file. So for internationalization, all we have to do is change the values stored against the keys in the resource.properties file and nothing else.


问:
Unity WebGL build error: The name Network does not exist in the current context
I'm trying to build a multiplayer WebGL game with Unity3D, with the new UNET system. It runs perfectly in the editor, and builds perfectly for Mac and Windows, but I try to build it for WebGL it gives me this error in multiple scripts:

The name Network does not exist in the current context

It runs fine in the editor for WebGL though, the errors show when I try to build. I've been reading this documentation but cannot figure out why it's not showing. https://docs.unity3d.com/Manual/webgl-networking.html

I'm on the latest version of Unity, 5.5

答:
Network package is not part of the UNET. It's the old Unity networking system, and it's not supported by WebGL builds.

Source


问:
How do i add linting to pre-commit hook
hi everyone i have a git repo that house 3 folders (individual js projects).

here's my pre-commit hook

```<code>#!/bin/bash
echo -e "\033[1;92m Linting Staged Files . . . "

files=$(git diff --diff-filter=d --cached --name-only | grep -E '\.(js|jsx)$')
path=(${files[0]//// })

if [[ $files = "" ]] ; then
  echo -e "\033[1;31m You have no staged file, exiting . . "
  exit 1
fi

for file in $files
do
git show ":$file" | $("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")
 if [ $? -ne 0 ]; then
   echo -e "\033[1;31m ESLint failed on staged file '$file'. \n Code will not be committed, Please fix your code and try again."
exit 1
 fi
done

BRANCH=`git rev-parse --abbrev-ref HEAD`

if [[ "$BRANCH" == "master" || "$BRANCH" == "develop" ]]; then
 echo "\033[1;31m commiting to $BRANCH is illegal."
 echo "\033[1;31m If you really know what you're doing, then add the argument '-n' to skip this git hook."
 exit 1
fi

exit 0
</code>```

but it keeps failing at this line git show ":$file" | $("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")

with an error

.git/hooks/pre-commit: line 17: ./node_modules/.bin/eslint --stdin --stdin-filename sfa/src/SFAApp.js: No such file or directory

i have no idea what i'm doing wrong please help.

答:
Never Mind i fixed the problem by changing

$("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")

to

./$path/node_modules/.bin/eslint --stdin --stdin-filename $file

TODO: research what $() really means in bash.

Title: How do i add linting to pre-commit hook

Body:
hi everyone i have a git repo that house 3 folders (individual js projects).

here's my pre-commit hook

#!/bin/bash
echo -e "\033[1;92m Linting Staged Files . . . "

files=$(git diff --diff-filter=d --cached --name-only | grep -E '\.(js|jsx)$')
path=(${files[0]//// })

if [[ $files = "" ]] ; then
  echo -e "\033[1;31m You have no staged file, exiting . . "
  exit 1
fi

for file in $files
do
git show ":$file" | $("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")
 if [ $? -ne 0 ]; then
   echo -e "\033[1;31m ESLint failed on staged file '$file'. \n Code will not be committed, Please fix your code and try again."
exit 1
 fi
done

BRANCH=`git rev-parse --abbrev-ref HEAD`

if [[ "$BRANCH" == "master" || "$BRANCH" == "develop" ]]; then
 echo "\033[1;31m commiting to $BRANCH is illegal."
 echo "\033[1;31m If you really know what you're doing, then add the argument '-n' to skip this git hook."
 exit 1
fi

exit 0

but it keeps failing at this line git show ":$file" | $("./$path/node_modules/.bin/eslint --stdin --stdin-filename $file")

with an error

.git/hooks/pre-commit: line 17: ./node_modules/.bin/eslint --stdin --stdin-filename sfa/src/SFAApp.js: No such file or directory

i have no idea what i'm doing wrong please help.


问:
Redirecting to site from an existing button being clicked
I'm quite new to coding. I have a button with the ID='test'. I want to run a line of code in javascript or HTML to redirect users to a site when that button is clicked.

Button:

```<code><button id="test" type="submit" onclick="setNick(document.getElementById('nick').value); return false; return false" class="btn btn-play-guest btn-success btn-needs-server primaryButton" data-itr="play_as_guest">
</code>```

I tried running this:

```<code><script>
document.getElementById("test").onclick = window.location='http://www.google.com/'
</script>
</code>```

However, this would redirect straight away. I want it to redirect only when the button is clicked. Please help me fix this.

Many thanks.

答:
You are assigning the redirect to the button where you need to assign it to a function.

You can try something like this:

```<code>document.getElementById("test").onclick = function(){
     window.location='http://www.google.com/';
}
</code>```

Body:
I'm quite new to coding. I have a button with the ID='test'. I want to run a line of code in javascript or HTML to redirect users to a site when that button is clicked.

Button:

<button id="test" type="submit" onclick="setNick(document.getElementById('nick').value); return false; return false" class="btn btn-play-guest btn-success btn-needs-server primaryButton" data-itr="play_as_guest">

I tried running this:

However, this would redirect straight away. I want it to redirect only when the button is clicked. Please help me fix this.

Many thanks.

Body:
You are assigning the redirect to the button where you need to assign it to a function.

You can try something like this:

document.getElementById("test").onclick = function(){
     window.location='http://www.google.com/';
}


问:
What is the significance of this entry in Annex E of the ES2015 spec?
Annex E of the ES2015 spec contains the following:

19.2.3.2: In ECMAScript 2015, the [[Prototype]] internal slot of a bound function is set to the [[GetPrototypeOf]] value of its target function. In the previous edition, [[Prototype]] was always set to %FunctionPrototype%.

What is the significance of this?

Source: http://www.ecma-international.org/ecma-262/6.0/#sec-additions-and-changes-that-introduce-incompatibilities-with-prior-editions

答:
ES5 functions always had Function.prototype as their prototype, so it was only logical to have the same for bound functions.

ES6 introduced classes, where the constructors inherit from their superclass constructor, and generator functions, which have their own prototype. If you bind one of them, the bound function should reflect this:

```<code>class A {
    constructor(x) { this.x = x; }
    static example() { return "works" }
}
class B extends A {}

const a1 = new A(1) // {x: 1}
const b1 = new B(1) // {x: 1}
A.example() // "works"
B.example() // "works" - because of inheritance

const BoundA = A.bind(null, 2), BoundB = B.bind(null, 2);
const a2 = new BoundA() // {x: 2}
const b2 = new BoundB() // {x: 2}
BoundA.example() // uh, doesn't actually work
BoundB.example() // "works" - because of the change to bind
</code>```

Maybe a better use case would be testing for the type of a function (which you shouldn't do though):

```<code>const GeneratorFunction = (function*(){}).constructor;

function* example() {
    …
}

test instanceof GeneratorFunction // true
test.bind() instanceof GeneratorFunction; // true as well!
</code>```

Body:
ES5 functions always had Function.prototype as their prototype, so it was only logical to have the same for bound functions.

ES6 introduced classes, where the constructors inherit from their superclass constructor, and generator functions, which have their own prototype. If you bind one of them, the bound function should reflect this:

class A {
    constructor(x) { this.x = x; }
    static example() { return "works" }
}
class B extends A {}

const a1 = new A(1) // {x: 1}
const b1 = new B(1) // {x: 1}
A.example() // "works"
B.example() // "works" - because of inheritance

const BoundA = A.bind(null, 2), BoundB = B.bind(null, 2);
const a2 = new BoundA() // {x: 2}
const b2 = new BoundB() // {x: 2}
BoundA.example() // uh, doesn't actually work
BoundB.example() // "works" - because of the change to bind

Maybe a better use case would be testing for the type of a function (which you shouldn't do though):

const GeneratorFunction = (function*(){}).constructor;

function* example() {
    …
}

test instanceof GeneratorFunction // true
test.bind() instanceof GeneratorFunction; // true as well!


问:
Does catching and rethrowing the exact same exception mean anything?
Lately, I have been seeing a lot of (commercial) code that throws and catches the exact same exception, similar to the code below:

```<code>public class Foo {
    public void bar() throws AnException {
        // do something (1)
        try {
            // do something (2) -- able to throw AnException
        } catch (AnException ex) {
            throw ex;
        }
        // do something (3)
    }
}
</code>```

Contrast this to:

```<code>public class Foo {
    public void bar() throws AnException {
        // do something (1)
        // do something (2) -- able to throw AnException
        // do something (3)
    }
}
</code>```

Does the former actually accomplish anything, in either behavior or semantics or else? Will it have any effect on code performance (time and space) or does it help readability?

P.S. this question is very different from this question.

EDIT: The catch block in the former doesn't do anything else other than rethrowing the caught exception.

答:
There's no reason for the try/catch in the code you posted. As with @nickolay.laptev's answer, I believe that if you find this in commercial code, it's probably left over cruft from something that used to be meaningful.

Aside from some sort of partial error handling, there's another use case for simply catching and rethrowing an exception. This would be to prevent the exception from being caught by a subsequent, more general, catch clause. So, for instance, if you wanted to handle every exception other than instances of AnException, you would either have to do a type check:

```<code>try {
    // stuff
} catch (Exception ex) {
    if (ex instanceof AnException) {
        throw ex; // rethrow since we're not handling it
    } else {
        // handle all other exceptions
    }
}
</code>```

or use something like this (which, in my view, is cleaner and more readable):

```<code>try {
    // stuff
} catch (AnException) {
    throw ex;
} catch (Exception ex) {
    // handle all other exceptions
}
</code>```

Then if you later decided to not handle all those other exceptions, you'd delete the second catch clause and end up with the code you posted.

Body:
Lately, I have been seeing a lot of (commercial) code that throws and catches the exact same exception, similar to the code below:

public class Foo {
    public void bar() throws AnException {
        // do something (1)
        try {
            // do something (2) -- able to throw AnException
        } catch (AnException ex) {
            throw ex;
        }
        // do something (3)
    }
}

Contrast this to:

public class Foo {
    public void bar() throws AnException {
        // do something (1)
        // do something (2) -- able to throw AnException
        // do something (3)
    }
}

Does the former actually accomplish anything, in either behavior or semantics or else? Will it have any effect on code performance (time and space) or does it help readability?

P.S. this question is very different from this question.

EDIT: The catch block in the former doesn't do anything else other than rethrowing the caught exception.

Body:
There's no reason for the try/catch in the code you posted. As with @nickolay.laptev's answer, I believe that if you find this in commercial code, it's probably left over cruft from something that used to be meaningful.

Aside from some sort of partial error handling, there's another use case for simply catching and rethrowing an exception. This would be to prevent the exception from being caught by a subsequent, more general, catch clause. So, for instance, if you wanted to handle every exception other than instances of AnException, you would either have to do a type check:

try {
    // stuff
} catch (Exception ex) {
    if (ex instanceof AnException) {
        throw ex; // rethrow since we're not handling it
    } else {
        // handle all other exceptions
    }
}

or use something like this (which, in my view, is cleaner and more readable):

try {
    // stuff
} catch (AnException) {
    throw ex;
} catch (Exception ex) {
    // handle all other exceptions
}

Then if you later decided to not handle all those other exceptions, you'd delete the second catch clause and end up with the code you posted.


问:
Python- Multiple os.path.split()
Do you guys know a more intelligent way to do this ?

```<code>os.path.split(os.path.split(os.path.split(os.getcwd())[0])[0])[0]
</code>```

os.getcwd() is for example:

```<code>/my/path/to/my/directory
</code>```

I should get

```<code>/my/path/
</code>```

That is really an exaggeration and duplication of the os.path.split()

Thanks

答:
You can use pathlib

```<code>from pathlib import Path
path = Path('/my/path/to/my/directory').parents[2]
print(path)

>>> /my/path
</code>```

As of Python 3.4, pathlib is part of the standard libraries, but you can install in earlier versions

pip install pathlib

Title: Python- Multiple os.path.split()

Body:
Do you guys know a more intelligent way to do this ?

os.path.split(os.path.split(os.path.split(os.getcwd())[0])[0])[0]

os.getcwd() is for example:

/my/path/to/my/directory

I should get

/my/path/

That is really an exaggeration and duplication of the os.path.split()

Thanks

Body:
You can use pathlib

from pathlib import Path
path = Path('/my/path/to/my/directory').parents[2]
print(path)

>>> /my/path

As of Python 3.4, pathlib is part of the standard libraries, but you can install in earlier versions

pip install pathlib


问:
Selenium: Unable to locate requested binary
Setup

OS: Ubuntu 17

Selenium: 2.53.1

Launching with param: -Dwebdriver.firefox.bin="/home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/firefox-bin"

Firefox: 47.0.1

Install Path: /home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/

Driver: geckodriver 0.11.1

Note: I've tried using the most recent version of selenium, geckodriver, and Firefox as well as Chrome but there appears to be a compatibility issue because Selenium crashes when PHPUnit launches the browsers. [Details Here]

Issue

When initiating my tests Selenium returns the text shown below. The most relevant part appears to be WARN - Exception: 'webdriver.firefox.bin' property set, but unable to locate the requested binary: "/home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/firefox-bin"

Digging into Selenium's repo, I see here that this is an error thrown when a Java method File.Exist() does not return true. In an attempt to resolve this I executed chmod 777 on the Selenium standalone server jar as well as the Firefox directory to ensure that it could be read from.

```<code>13:53:30.688 INFO - Executing: [new session: Capabilities [{0={platform=[{value=LINUX}]}, browserName=firefox}]])
13:53:30.694 INFO - Creating a new session for Capabilities [{0={platform=[{value=LINUX}]}, browserName=firefox}]
13:53:30.698 WARN - Exception thrown
java.util.concurrent.ExecutionException: org.openqa.selenium.WebDriverException: java.lang.reflect.InvocationTargetException
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'tyler-Precision-5520', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.10.0-21-generic', java.version: '1.8.0_131'
Driver info: driver.version: unknown
        at java.util.concurrent.FutureTask.report(FutureTask.java:122)
        at java.util.concurrent.FutureTask.get(FutureTask.java:192)
        at org.openqa.selenium.remote.server.DefaultSession.execute(DefaultSession.java:183)
        at org.openqa.selenium.remote.server.DefaultSession.<init>(DefaultSession.java:119)
        at org.openqa.selenium.remote.server.DefaultSession.createSession(DefaultSession.java:95)
        at org.openqa.selenium.remote.server.DefaultDriverSessions.newSession(DefaultDriverSessions.java:124)
        at org.openqa.selenium.remote.server.handler.NewSession.handle(NewSession.java:59)
        at org.openqa.selenium.remote.server.handler.NewSession.handle(NewSession.java:1)
        at org.openqa.selenium.remote.server.rest.ResultConfig.handle(ResultConfig.java:111)
        at org.openqa.selenium.remote.server.JsonHttpCommandHandler.handleRequest(JsonHttpCommandHandler.java:79)
        at org.openqa.selenium.remote.server.DriverServlet.handleRequest(DriverServlet.java:204)
        at org.openqa.selenium.remote.server.DriverServlet.doPost(DriverServlet.java:166)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
        at org.openqa.selenium.remote.server.DriverServlet.service(DriverServlet.java:132)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.openqa.jetty.jetty.servlet.ServletHolder.handle(ServletHolder.java:428)
        at org.openqa.jetty.jetty.servlet.ServletHandler.dispatch(ServletHandler.java:680)
        at org.openqa.jetty.jetty.servlet.ServletHandler.handle(ServletHandler.java:571)
        at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1526)
        at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1479)
        at org.openqa.jetty.http.HttpServer.service(HttpServer.java:920)
        at org.openqa.jetty.http.HttpConnection.service(HttpConnection.java:820)
        at org.openqa.jetty.http.HttpConnection.handleNext(HttpConnection.java:986)
        at org.openqa.jetty.http.HttpConnection.handle(HttpConnection.java:837)
        at org.openqa.jetty.http.SocketListener.handleConnection(SocketListener.java:243)
        at org.openqa.jetty.util.ThreadedServer.handle(ThreadedServer.java:358)
        at org.openqa.jetty.util.ThreadPool$PoolThread.run(ThreadPool.java:537)
Caused by: org.openqa.selenium.WebDriverException: java.lang.reflect.InvocationTargetException
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'tyler-Precision-5520', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.10.0-21-generic', java.version: '1.8.0_131'
Driver info: driver.version: unknown
        at org.openqa.selenium.remote.server.FirefoxDriverProvider.callConstructor(FirefoxDriverProvider.java:101)
        at org.openqa.selenium.remote.server.FirefoxDriverProvider.newInstance(FirefoxDriverProvider.java:68)
        at org.openqa.selenium.remote.server.DefaultDriverFactory.newInstance(DefaultDriverFactory.java:60)
        at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:222)
        at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:1)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:176)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.server.FirefoxDriverProvider.callConstructor(FirefoxDriverProvider.java:91)
        ... 9 more
Caused by: java.lang.ExceptionInInitializerError
        at org.openqa.selenium.firefox.FirefoxBinary.<init>(FirefoxBinary.java:60)
        at org.openqa.selenium.firefox.FirefoxBinary.<init>(FirefoxBinary.java:56)
        at org.openqa.selenium.firefox.FirefoxDriver.getBinary(FirefoxDriver.java:203)
        at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:128)
        ... 14 more
Caused by: org.openqa.selenium.WebDriverException: 'webdriver.firefox.bin' property set, but unable to locate the requested binary: "/home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/firefox-bin"
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'tyler-Precision-5520', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.10.0-21-generic', java.version: '1.8.0_131'
Driver info: driver.version: FirefoxDriver
        at org.openqa.selenium.firefox.internal.Executable.locateFirefoxBinaryFromSystemProperty(Executable.java:145)
        at org.openqa.selenium.firefox.internal.Executable.<clinit>(Executable.java:45)
        ... 18 more
13:53:30.701 WARN - Exception: 'webdriver.firefox.bin' property set, but unable to locate the requested binary: "/home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/firefox-bin"
</code>```

答:
It is easier to install Firefox in the default directory so you can do:

```<code>WebDriver driver = new FirefoxDriver();
</code>```

You could also add your directory to your System's PATH variable (requires a restart).

Lastly you can define the path in code. Java Example from another Q/A on SO:

```<code>File browserAppPath = new File("/usr/bin/firefox/firefox-bin");
WebDriver driver = new FirefoxDriver( new FirefoxBinary(browserAppPath), new FirefoxProfile());
</code>```

Body:
Setup

OS: Ubuntu 17

Selenium: 2.53.1

Launching with param: -Dwebdriver.firefox.bin="/home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/firefox-bin"

Firefox: 47.0.1

Install Path: /home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/

Driver: geckodriver 0.11.1

Note: I've tried using the most recent version of selenium, geckodriver, and Firefox as well as Chrome but there appears to be a compatibility issue because Selenium crashes when PHPUnit launches the browsers. [Details Here]

Issue

When initiating my tests Selenium returns the text shown below. The most relevant part appears to be WARN - Exception: 'webdriver.firefox.bin' property set, but unable to locate the requested binary: "/home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/firefox-bin"

Digging into Selenium's repo, I see here that this is an error thrown when a Java method File.Exist() does not return true. In an attempt to resolve this I executed chmod 777 on the Selenium standalone server jar as well as the Firefox directory to ensure that it could be read from.

13:53:30.688 INFO - Executing: [new session: Capabilities [{0={platform=[{value=LINUX}]}, browserName=firefox}]])
13:53:30.694 INFO - Creating a new session for Capabilities [{0={platform=[{value=LINUX}]}, browserName=firefox}]
13:53:30.698 WARN - Exception thrown
java.util.concurrent.ExecutionException: org.openqa.selenium.WebDriverException: java.lang.reflect.InvocationTargetException
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'tyler-Precision-5520', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.10.0-21-generic', java.version: '1.8.0_131'
Driver info: driver.version: unknown
        at java.util.concurrent.FutureTask.report(FutureTask.java:122)
        at java.util.concurrent.FutureTask.get(FutureTask.java:192)
        at org.openqa.selenium.remote.server.DefaultSession.execute(DefaultSession.java:183)
        at org.openqa.selenium.remote.server.DefaultSession.<init>(DefaultSession.java:119)
        at org.openqa.selenium.remote.server.DefaultSession.createSession(DefaultSession.java:95)
        at org.openqa.selenium.remote.server.DefaultDriverSessions.newSession(DefaultDriverSessions.java:124)
        at org.openqa.selenium.remote.server.handler.NewSession.handle(NewSession.java:59)
        at org.openqa.selenium.remote.server.handler.NewSession.handle(NewSession.java:1)
        at org.openqa.selenium.remote.server.rest.ResultConfig.handle(ResultConfig.java:111)
        at org.openqa.selenium.remote.server.JsonHttpCommandHandler.handleRequest(JsonHttpCommandHandler.java:79)
        at org.openqa.selenium.remote.server.DriverServlet.handleRequest(DriverServlet.java:204)
        at org.openqa.selenium.remote.server.DriverServlet.doPost(DriverServlet.java:166)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
        at org.openqa.selenium.remote.server.DriverServlet.service(DriverServlet.java:132)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
        at org.openqa.jetty.jetty.servlet.ServletHolder.handle(ServletHolder.java:428)
        at org.openqa.jetty.jetty.servlet.ServletHandler.dispatch(ServletHandler.java:680)
        at org.openqa.jetty.jetty.servlet.ServletHandler.handle(ServletHandler.java:571)
        at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1526)
        at org.openqa.jetty.http.HttpContext.handle(HttpContext.java:1479)
        at org.openqa.jetty.http.HttpServer.service(HttpServer.java:920)
        at org.openqa.jetty.http.HttpConnection.service(HttpConnection.java:820)
        at org.openqa.jetty.http.HttpConnection.handleNext(HttpConnection.java:986)
        at org.openqa.jetty.http.HttpConnection.handle(HttpConnection.java:837)
        at org.openqa.jetty.http.SocketListener.handleConnection(SocketListener.java:243)
        at org.openqa.jetty.util.ThreadedServer.handle(ThreadedServer.java:358)
        at org.openqa.jetty.util.ThreadPool$PoolThread.run(ThreadPool.java:537)
Caused by: org.openqa.selenium.WebDriverException: java.lang.reflect.InvocationTargetException
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'tyler-Precision-5520', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.10.0-21-generic', java.version: '1.8.0_131'
Driver info: driver.version: unknown
        at org.openqa.selenium.remote.server.FirefoxDriverProvider.callConstructor(FirefoxDriverProvider.java:101)
        at org.openqa.selenium.remote.server.FirefoxDriverProvider.newInstance(FirefoxDriverProvider.java:68)
        at org.openqa.selenium.remote.server.DefaultDriverFactory.newInstance(DefaultDriverFactory.java:60)
        at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:222)
        at org.openqa.selenium.remote.server.DefaultSession$BrowserCreator.call(DefaultSession.java:1)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at org.openqa.selenium.remote.server.DefaultSession$1.run(DefaultSession.java:176)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at org.openqa.selenium.remote.server.FirefoxDriverProvider.callConstructor(FirefoxDriverProvider.java:91)
        ... 9 more
Caused by: java.lang.ExceptionInInitializerError
        at org.openqa.selenium.firefox.FirefoxBinary.<init>(FirefoxBinary.java:60)
        at org.openqa.selenium.firefox.FirefoxBinary.<init>(FirefoxBinary.java:56)
        at org.openqa.selenium.firefox.FirefoxDriver.getBinary(FirefoxDriver.java:203)
        at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:128)
        ... 14 more
Caused by: org.openqa.selenium.WebDriverException: 'webdriver.firefox.bin' property set, but unable to locate the requested binary: "/home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/firefox-bin"
Build info: version: '2.53.1', revision: 'a36b8b1', time: '2016-06-30 17:37:03'
System info: host: 'tyler-Precision-5520', ip: '127.0.1.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.10.0-21-generic', java.version: '1.8.0_131'
Driver info: driver.version: FirefoxDriver
        at org.openqa.selenium.firefox.internal.Executable.locateFirefoxBinaryFromSystemProperty(Executable.java:145)
        at org.openqa.selenium.firefox.internal.Executable.<clinit>(Executable.java:45)
        ... 18 more
13:53:30.701 WARN - Exception: 'webdriver.firefox.bin' property set, but unable to locate the requested binary: "/home/tyler/Documents/Code/dev/tests/functional/firefox-47.0.1/firefox-bin"

Body:
It is easier to install Firefox in the default directory so you can do:

WebDriver driver = new FirefoxDriver();

You could also add your directory to your System's PATH variable (requires a restart).

Lastly you can define the path in code. Java Example from another Q/A on SO:

File browserAppPath = new File("/usr/bin/firefox/firefox-bin");
WebDriver driver = new FirefoxDriver( new FirefoxBinary(browserAppPath), new FirefoxProfile());


问:
In SQL Server, how do I reset the id column of my table back to 1?
My table has an int-based identity column in SQL Server.

Since I have removed entries from this table, the id's no longer begin at 1.

How do I reset the id column of my table back to 1?

答: If you want to remove ALL entries from a table AND have the identity reset to 1 (or whatever its initial seed value is) you can do so with a TRUNCATE TABLE command instead of DELETE.</p>


问:
In python, what's the most efficient way to identify clusters of n-events t-time apart?
For example, if I have the following event data, and want to find clusters of at least 2 events that are within 1 minute of each other in which id_1, id_2, and id_3 are all the same. For reference, I have the epoch timestamp (in microseconds) in addition to the date-time timestamp.

```<code>event_id       timestamp          id_1 id_2  id_3
9442823 Jun 15, 2015 10:22 PM PDT   A   1   34567
9442821 Jun 15, 2015 10:22 PM PDT   A   2   12345
9442817 Jun 15, 2015 10:22 PM PDT   A   3   34567
9442814 Jun 15, 2015 10:22 PM PDT   A   1   12345
9442813 Jun 15, 2015 10:22 PM PDT   A   2   34567
9442810 Jun 15, 2015 10:22 PM PDT   A   3   12345
9442805 Jun 15, 2015 10:22 PM PDT   A   1   34567
9442876 Jun 15, 2015 10:23 PM PDT   A   2   12345
9442866 Jun 15, 2015 10:23 PM PDT   A   3   34567
9442858 Jun 15, 2015 10:23 PM PDT   A   1   12345
9442845 Jun 15, 2015 10:23 PM PDT   C   2   34567
9442840 Jun 15, 2015 10:23 PM PDT   C   3   12345
9442839 Jun 15, 2015 10:23 PM PDT   C   1   34567
9442838 Jun 15, 2015 10:23 PM PDT   C   2   12345
9442907 Jun 15, 2015 10:24 PM PDT   C   3   34567
9442886 Jun 15, 2015 10:24 PM PDT   C   1   12345
9442949 Jun 15, 2015 10:25 PM PDT   C   2   34567
9442934 Jun 15, 2015 10:25 PM PDT   C   3   12345
</code>```

For each cluster found, I want to return a set of (id_1, id_2, id_3, [list of event_ids], min_timestamp_of_cluster, max_timestamp_of_cluster). Additionally, if there's a cluster with (e.g.) 6 events, I'd only want to return a single result with all events, not one for each grouping of 3 events.

答:
In pure python, use a "sliding window" that encompasses all the events in a 1 minute range.

The premise is simple: maintain a queue of events that is a subsequence
of the total list, in order. The "window" (queue) should be all the events you care about. In this case, that is determined by the 60-second time gap requirement.

As you process events, add one event to the end of the queue. If the first event in the queue is more than 60 seconds from the newly-added last event, slide the window forward by dropping the first event from the front of the queue.

This is python3:

```<code>import collections
import operator
import itertools

from datetime import datetime

#### FROM HERE: vvv is just faking events. Delete or replace.

class Event(collections.namedtuple('Event', 'event_id timestamp id_1 id_2 id_3 epoch_ts')):
    def __str__(self):
        return ('{e.event_id} {e.timestamp}  {e.id_1}  {e.id_2}  {e.id_3}'
                .format(e=self))

def get_events():
    event_list = map(operator.methodcaller('strip'), '''
        9442823 Jun 15, 2015 10:22 PM PDT   A   1   34567
        9442821 Jun 15, 2015 10:22 PM PDT   A   2   12345
        9442817 Jun 15, 2015 10:22 PM PDT   A   3   34567
        9442814 Jun 15, 2015 10:22 PM PDT   A   1   12345
        9442813 Jun 15, 2015 10:22 PM PDT   A   2   34567
        9442810 Jun 15, 2015 10:22 PM PDT   A   3   12345
        9442805 Jun 15, 2015 10:22 PM PDT   A   1   34567
        9442876 Jun 15, 2015 10:23 PM PDT   A   2   12345
        9442866 Jun 15, 2015 10:23 PM PDT   A   3   34567
        9442858 Jun 15, 2015 10:23 PM PDT   A   1   12345
        9442845 Jun 15, 2015 10:23 PM PDT   C   2   34567
        9442840 Jun 15, 2015 10:23 PM PDT   C   3   12345
        9442839 Jun 15, 2015 10:23 PM PDT   C   1   34567
        9442838 Jun 15, 2015 10:23 PM PDT   C   2   12345
        9442907 Jun 15, 2015 10:24 PM PDT   C   3   34567
        9442886 Jun 15, 2015 10:24 PM PDT   C   1   12345
        9442949 Jun 15, 2015 10:25 PM PDT   C   2   34567
        9442934 Jun 15, 2015 10:25 PM PDT   C   3   12345
    '''.strip().splitlines())

    for line in event_list:
        idev, *rest = line.split()
        ts = rest[:6]
        id1, id2, id3 = rest[6:]
        id2 = int(id2)  # faster when sorting (see find_clustered_events)
        id3 = int(id3)  # faster when sorting (see find_clustered_events)
        ts_str = ' '.join(ts)
        dt = datetime.strptime(ts_str.replace('PDT', '-0700'), '%b %d, %Y %I:%M %p %z')
        epoch = dt.timestamp()
        ev = Event(idev, ts_str, id1, id2, id3, epoch)
        yield ev

#### TO HERE: ^^^  was just faking up your events. Delete or replace.

def add_cluster(key, group):
    '''Do whatever you want with the clusters. I'll print them.'''

    print('Cluster:', key)
    print('    ','\n    '.join(map(str, group)), sep='')

def find_clustered_events(events, cluster=3, gap_secs=60):
    '''Call add_cluster on clusters of events within a maximum time gap.

    Args:
        events (iterable): series of events, in chronological order
        cluster (int): minimum number of events in a cluster
        gap_secs (float): maximum time-gap from start to end of cluster

    Returns:
        None.

    '''
    window = collections.deque()
    evkey = lambda e: (e.id_1, e.id_2, e.id_3)

    for ev in events:
        window.append(ev)

        t0 = window[0].epoch_ts
        tn = window[-1].epoch_ts

        if tn - t0 < gap_secs:
            continue

        window.pop()

        for k, g in itertools.groupby(sorted(window, key=evkey), key=evkey):
            group = tuple(g)
            if len(group) >= cluster:
                add_cluster(k, group)

        window.append(ev)
        window.popleft()

# Call find_clustered with event generator, cluster args.
# Note that your data doesn't have any 3-clusters without time seconds. :-(

find_clustered_events(get_events(), cluster=2)
</code>```

The output looks like this:

```<code>$ python test.py
Cluster: ('A', 1, 34567)
    9442823 Jun 15, 2015 10:22 PM PDT  A  1  34567
    9442805 Jun 15, 2015 10:22 PM PDT  A  1  34567
Cluster: ('A', 2, 12345)
    9442821 Jun 15, 2015 10:22 PM PDT  A  2  12345
    9442876 Jun 15, 2015 10:23 PM PDT  A  2  12345
Cluster: ('A', 3, 34567)
    9442817 Jun 15, 2015 10:22 PM PDT  A  3  34567
    9442866 Jun 15, 2015 10:23 PM PDT  A  3  34567
Cluster: ('A', 1, 12345)
    9442814 Jun 15, 2015 10:22 PM PDT  A  1  12345
    9442858 Jun 15, 2015 10:23 PM PDT  A  1  12345
Cluster: ('C', 2, 34567)
    9442845 Jun 15, 2015 10:23 PM PDT  C  2  34567
    9442949 Jun 15, 2015 10:25 PM PDT  C  2  34567
</code>```

Please note: the code above doesn't try to keep track of events already in a cluster. So if you have, for example, an event type that occurs every fifteen seconds, you will have a sequence like this:

```<code> event1   t=0:00
 event2   t=0:15
 event3   t=0:30
 event4   t=0:45
 event5   t=1:00
</code>```

And you will get overlapping clusters:

```<code>event1, event2, event3 (t=0:00 .. 0:30)
event2, event3, event4 (t=0:15 .. 0:45)
event3, event4, event5 (t=0:30 .. 1:00)
</code>```

Technically, those are valid clusters, each slightly different. But you may wish to expunge previously-clustered events from the window, if you want the events to only appear in a single cluster.

Alternatively, if the chance of clustering and repetition is low, it might improve performance to implement repeat-checking in the add_cluster() function, to reduce the work done by the main loop.

A final note: this does a LOT of sorting. And the sorting is not efficient, since it gets repeated every time a new event appears. If you have a large data set, the performance will probably be bad. If your event keys are relatively few - that is, if the id1,2,3 values tend to repeat over and over again - you would be better off dynamically creating separate deques for each distinct key (id1+id2+id3) and dispatching the event to the appropriate deque, applying the same window logic, and then checking the length of the deque.

On the other hand, if you are processing something like web-server logs, where the requester is always changing, that might tend to create a memory problem with all the useless deques. So this is a memory vs. time trade-off you'll have to be aware of.

Body:
For example, if I have the following event data, and want to find clusters of at least 2 events that are within 1 minute of each other in which id_1, id_2, and id_3 are all the same. For reference, I have the epoch timestamp (in microseconds) in addition to the date-time timestamp.

event_id       timestamp          id_1 id_2  id_3
9442823 Jun 15, 2015 10:22 PM PDT   A   1   34567
9442821 Jun 15, 2015 10:22 PM PDT   A   2   12345
9442817 Jun 15, 2015 10:22 PM PDT   A   3   34567
9442814 Jun 15, 2015 10:22 PM PDT   A   1   12345
9442813 Jun 15, 2015 10:22 PM PDT   A   2   34567
9442810 Jun 15, 2015 10:22 PM PDT   A   3   12345
9442805 Jun 15, 2015 10:22 PM PDT   A   1   34567
9442876 Jun 15, 2015 10:23 PM PDT   A   2   12345
9442866 Jun 15, 2015 10:23 PM PDT   A   3   34567
9442858 Jun 15, 2015 10:23 PM PDT   A   1   12345
9442845 Jun 15, 2015 10:23 PM PDT   C   2   34567
9442840 Jun 15, 2015 10:23 PM PDT   C   3   12345
9442839 Jun 15, 2015 10:23 PM PDT   C   1   34567
9442838 Jun 15, 2015 10:23 PM PDT   C   2   12345
9442907 Jun 15, 2015 10:24 PM PDT   C   3   34567
9442886 Jun 15, 2015 10:24 PM PDT   C   1   12345
9442949 Jun 15, 2015 10:25 PM PDT   C   2   34567
9442934 Jun 15, 2015 10:25 PM PDT   C   3   12345

For each cluster found, I want to return a set of (id_1, id_2, id_3, [list of event_ids], min_timestamp_of_cluster, max_timestamp_of_cluster). Additionally, if there's a cluster with (e.g.) 6 events, I'd only want to return a single result with all events, not one for each grouping of 3 events.

Body:
In pure python, use a "sliding window" that encompasses all the events in a 1 minute range.

The premise is simple: maintain a queue of events that is a subsequence
of the total list, in order. The "window" (queue) should be all the events you care about. In this case, that is determined by the 60-second time gap requirement.

As you process events, add one event to the end of the queue. If the first event in the queue is more than 60 seconds from the newly-added last event, slide the window forward by dropping the first event from the front of the queue.

This is python3:

import collections
import operator
import itertools

from datetime import datetime

#### FROM HERE: vvv is just faking events. Delete or replace.

class Event(collections.namedtuple('Event', 'event_id timestamp id_1 id_2 id_3 epoch_ts')):
    def __str__(self):
        return ('{e.event_id} {e.timestamp}  {e.id_1}  {e.id_2}  {e.id_3}'
                .format(e=self))

def get_events():
    event_list = map(operator.methodcaller('strip'), '''
        9442823 Jun 15, 2015 10:22 PM PDT   A   1   34567
        9442821 Jun 15, 2015 10:22 PM PDT   A   2   12345
        9442817 Jun 15, 2015 10:22 PM PDT   A   3   34567
        9442814 Jun 15, 2015 10:22 PM PDT   A   1   12345
        9442813 Jun 15, 2015 10:22 PM PDT   A   2   34567
        9442810 Jun 15, 2015 10:22 PM PDT   A   3   12345
        9442805 Jun 15, 2015 10:22 PM PDT   A   1   34567
        9442876 Jun 15, 2015 10:23 PM PDT   A   2   12345
        9442866 Jun 15, 2015 10:23 PM PDT   A   3   34567
        9442858 Jun 15, 2015 10:23 PM PDT   A   1   12345
        9442845 Jun 15, 2015 10:23 PM PDT   C   2   34567
        9442840 Jun 15, 2015 10:23 PM PDT   C   3   12345
        9442839 Jun 15, 2015 10:23 PM PDT   C   1   34567
        9442838 Jun 15, 2015 10:23 PM PDT   C   2   12345
        9442907 Jun 15, 2015 10:24 PM PDT   C   3   34567
        9442886 Jun 15, 2015 10:24 PM PDT   C   1   12345
        9442949 Jun 15, 2015 10:25 PM PDT   C   2   34567
        9442934 Jun 15, 2015 10:25 PM PDT   C   3   12345
    '''.strip().splitlines())

    for line in event_list:
        idev, *rest = line.split()
        ts = rest[:6]
        id1, id2, id3 = rest[6:]
        id2 = int(id2)  # faster when sorting (see find_clustered_events)
        id3 = int(id3)  # faster when sorting (see find_clustered_events)
        ts_str = ' '.join(ts)
        dt = datetime.strptime(ts_str.replace('PDT', '-0700'), '%b %d, %Y %I:%M %p %z')
        epoch = dt.timestamp()
        ev = Event(idev, ts_str, id1, id2, id3, epoch)
        yield ev

#### TO HERE: ^^^  was just faking up your events. Delete or replace.

def add_cluster(key, group):
    '''Do whatever you want with the clusters. I'll print them.'''

    print('Cluster:', key)
    print('    ','\n    '.join(map(str, group)), sep='')

def find_clustered_events(events, cluster=3, gap_secs=60):
    '''Call add_cluster on clusters of events within a maximum time gap.

    Args:
        events (iterable): series of events, in chronological order
        cluster (int): minimum number of events in a cluster
        gap_secs (float): maximum time-gap from start to end of cluster

    Returns:
        None.

    '''
    window = collections.deque()
    evkey = lambda e: (e.id_1, e.id_2, e.id_3)

    for ev in events:
        window.append(ev)

        t0 = window[0].epoch_ts
        tn = window[-1].epoch_ts

        if tn - t0 < gap_secs:
            continue

        window.pop()

        for k, g in itertools.groupby(sorted(window, key=evkey), key=evkey):
            group = tuple(g)
            if len(group) >= cluster:
                add_cluster(k, group)

        window.append(ev)
        window.popleft()

# Call find_clustered with event generator, cluster args.
# Note that your data doesn't have any 3-clusters without time seconds. :-(

find_clustered_events(get_events(), cluster=2)

The output looks like this:

$ python test.py
Cluster: ('A', 1, 34567)
    9442823 Jun 15, 2015 10:22 PM PDT  A  1  34567
    9442805 Jun 15, 2015 10:22 PM PDT  A  1  34567
Cluster: ('A', 2, 12345)
    9442821 Jun 15, 2015 10:22 PM PDT  A  2  12345
    9442876 Jun 15, 2015 10:23 PM PDT  A  2  12345
Cluster: ('A', 3, 34567)
    9442817 Jun 15, 2015 10:22 PM PDT  A  3  34567
    9442866 Jun 15, 2015 10:23 PM PDT  A  3  34567
Cluster: ('A', 1, 12345)
    9442814 Jun 15, 2015 10:22 PM PDT  A  1  12345
    9442858 Jun 15, 2015 10:23 PM PDT  A  1  12345
Cluster: ('C', 2, 34567)
    9442845 Jun 15, 2015 10:23 PM PDT  C  2  34567
    9442949 Jun 15, 2015 10:25 PM PDT  C  2  34567

Please note: the code above doesn't try to keep track of events already in a cluster. So if you have, for example, an event type that occurs every fifteen seconds, you will have a sequence like this:

 event1   t=0:00
 event2   t=0:15
 event3   t=0:30
 event4   t=0:45
 event5   t=1:00

And you will get overlapping clusters:

event1, event2, event3 (t=0:00 .. 0:30)
event2, event3, event4 (t=0:15 .. 0:45)
event3, event4, event5 (t=0:30 .. 1:00)

Technically, those are valid clusters, each slightly different. But you may wish to expunge previously-clustered events from the window, if you want the events to only appear in a single cluster.

Alternatively, if the chance of clustering and repetition is low, it might improve performance to implement repeat-checking in the add_cluster() function, to reduce the work done by the main loop.

A final note: this does a LOT of sorting. And the sorting is not efficient, since it gets repeated every time a new event appears. If you have a large data set, the performance will probably be bad. If your event keys are relatively few - that is, if the id1,2,3 values tend to repeat over and over again - you would be better off dynamically creating separate deques for each distinct key (id1+id2+id3) and dispatching the event to the appropriate deque, applying the same window logic, and then checking the length of the deque.

On the other hand, if you are processing something like web-server logs, where the requester is always changing, that might tend to create a memory problem with all the useless deques. So this is a memory vs. time trade-off you'll have to be aware of.


问:
How to call parent window function on child window?
I want call a javascript function defined in parent on child window.
I have searched for window.opener and window.parent, but they call function on parent window not on child.
Also if it is possible by local storage.
Parent window function:

```<code>var myFunction=function download() {
        console.log("in jsp download")
        $("#btnExport").click(function(e) {
            e.preventDefault();

            //some operation
        });
    }

    window.onload = function() {
        localStorage.setItem("storageName",myfunction);

    }
</code>```

Child window

```<code><button id="exportExcel" onclick="localStorage.getItem("storageName")">Export</button>
</code>```

But this is giving error on child window

答:
When you create the function you're attaching it to the parent's scope. If the parent page opens the child (via window.open) you can access its scope through the child's window.opener object.

Parent Page

```<code>Function DoSomething(){}
</code>```

Child Page

```<code>window.opener.DoSomething()
</code>```

Body:
I want call a javascript function defined in parent on child window.
I have searched for window.opener and window.parent, but they call function on parent window not on child.
Also if it is possible by local storage.
Parent window function:

var myFunction=function download() {
        console.log("in jsp download")
        $("#btnExport").click(function(e) {
            e.preventDefault();

            //some operation
        });
    }

    window.onload = function() {
        localStorage.setItem("storageName",myfunction);

    }

Child window

<button id="exportExcel" onclick="localStorage.getItem("storageName")">Export</button>

But this is giving error on child window

Body:
When you create the function you're attaching it to the parent's scope. If the parent page opens the child (via window.open) you can access its scope through the child's window.opener object.

Parent Page

Function DoSomething(){}

Child Page

window.opener.DoSomething()


问:
Linq statements need optimizing
I have written the following code:

```<code>//get the user from the DB
var tmpuser = _db.aspnet_Users.First(q => q.UserName == user.Identity.Name);

//list the direct connections to Verbond
List<Verbond> verb1 = tmpuser.UsersVerbondens
                             .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
                             .Select(q => q.Verbond)
                             .ToList();

//list the connected Facturatieverbonden
List<FacturatieVerbonden> verb2 = tmpuser.UsersFacturatieVerbondens
                                         .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
                                         .Select(q => q.FacturatieVerbonden)
                                         .ToList();

//loop through the facturatieverbonden and add their verbonds to the first list
foreach (FacturatieVerbonden v in verb2) {
    verb1.AddRange(v.Verbonds);
}

//make a distinct list
List<Verbond> test = verb1.Distinct().ToList();
</code>```

So, Users can be connected to 0 or more facturatieverbonden and also can be connected to verbond.

A facturatieverbonden can have one or more verbond's under itself.

What I need is a list of all the verbond's the user is connected to, directly, or indirectly via the facturatieverbonden.

My code works but I don't think it's very efficient. Any hints on making it cleaner?

答:
Your query isn't very LINQy. Here's a potential improvement:

```<code>           //list the direct connections to Verbond
var test = (from q in tmpuser.UsersVerbondens
            where q.Schooljaar.Sch_Schooljaar == schooljaarparam
            select q.Verbond)
           //return distinct values
           .Union
           //list the connected Facturatieverbonden
           (from q in tmpuser.UsersFacturatieVerbondens
            where q.Schooljaar.Sch_Schooljaar == schooljaarparam
            from v in q.FacturatieVerbonden.Verbonds
            select v)
           //return a List
           .ToList();
</code>```

By making ToList the very last thing it does, the whole computation can be done in the database, avoiding all the intermediate lists.

Title: Linq statements need optimizing

Body:
I have written the following code:

//get the user from the DB
var tmpuser = _db.aspnet_Users.First(q => q.UserName == user.Identity.Name);

//list the direct connections to Verbond
List<Verbond> verb1 = tmpuser.UsersVerbondens
                             .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
                             .Select(q => q.Verbond)
                             .ToList();

//list the connected Facturatieverbonden
List<FacturatieVerbonden> verb2 = tmpuser.UsersFacturatieVerbondens
                                         .Where(q => q.Schooljaar.Sch_Schooljaar == schooljaarparam)
                                         .Select(q => q.FacturatieVerbonden)
                                         .ToList();

//loop through the facturatieverbonden and add their verbonds to the first list
foreach (FacturatieVerbonden v in verb2) {
    verb1.AddRange(v.Verbonds);
}

//make a distinct list
List<Verbond> test = verb1.Distinct().ToList();

So, Users can be connected to 0 or more facturatieverbonden and also can be connected to verbond.

A facturatieverbonden can have one or more verbond's under itself.

What I need is a list of all the verbond's the user is connected to, directly, or indirectly via the facturatieverbonden.

My code works but I don't think it's very efficient. Any hints on making it cleaner?

Body:
Your query isn't very LINQy. Here's a potential improvement:

           //list the direct connections to Verbond
var test = (from q in tmpuser.UsersVerbondens
            where q.Schooljaar.Sch_Schooljaar == schooljaarparam
            select q.Verbond)
           //return distinct values
           .Union
           //list the connected Facturatieverbonden
           (from q in tmpuser.UsersFacturatieVerbondens
            where q.Schooljaar.Sch_Schooljaar == schooljaarparam
            from v in q.FacturatieVerbonden.Verbonds
            select v)
           //return a List
           .ToList();

By making ToList the very last thing it does, the whole computation can be done in the database, avoiding all the intermediate lists.


问:
Add two quotes in JavaScript
I have a code like this :

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += event[keys[i]] + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring (0, str6.length - 2);  console.log(valeurs); ```
</div>
</div>
</p>

<p>I want to have everything between two quotes in variable <code>valeurs</code> like this:</p>

<pre class="lang-none prettyprint-override"><code>, '12 .45 ', '45 .78', 'charone', 'chartwo'
</code>```

Or, just have the character strings between two quotes:

, 12.45, 45.78, 'charone', 'chartwo'
```

I can have in my JSON other strings.

How can I do this in JavaScript?

答:
If you're using a recent version of most major browsers, you can just use Object.values():

var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

console.log(Object.values(event));```

If you really want the numbers as strings too, change the last line to console.log(Object.values(event).map(value => String(value))).

And if you need the initial comma, just add it: ', ' + Object.values(event).map(value => String(value)).

Title: Add two quotes in JavaScript

Body:
I have a code like this :

 var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

var keys = Object.keys(event);

 valeurs_d = "";
 for (var i = 0; i < keys.length -1 ; i++)
 valeurs_d += event[keys[i]] + ", ";
 var str5 = ",";
 var str6 = str5.concat(valeurs_d);
 var valeurs = str6.substring (0, str6.length - 2);  console.log(valeurs);

I want to have everything between two quotes in variable valeurs like this:

, '12 .45 ', '45 .78', 'charone', 'chartwo'

Or, just have the character strings between two quotes:

, 12.45, 45.78, 'charone', 'chartwo'

I can have in my JSON other strings.

How can I do this in JavaScript?

Body:
If you're using a recent version of most major browsers, you can just use Object.values():

var event = {
  "temperature" : 12.45,
  "humidite" : 45.78,
  "built" : "charone",
  "fire" : "chartwo",
  "topic" : "sk1_001/data"
 };

console.log(Object.values(event));

If you really want the numbers as strings too, change the last line to console.log(Object.values(event).map(value => String(value))).

And if you need the initial comma, just add it: ', ' + Object.values(event).map(value => String(value)).


问:
npm install error ( npm install -g angular-cli ) in windows 10

node -v

v4.5.0

npm -v

5.0.1

Has anyone faced this kind of issue while installing angular-cli in windows 10?

答:
Try the following:

step 0: run this command

```<code>npm uninstall -g @angular/cli
npm cache clean
</code>```

step 1: delete this folder: C:\Users\%YOUR-USERNAME%\AppData\Roaming\npm

step 2: uninstall Nodejs from Windows

step 3: restart your PC

step 4: install a fresh copy of Nodejs from here: https://nodejs.org/en/

step 5: install the CLI globally

```<code>npm install -g @angular/cli@latest
</code>```

Body:
Try the following:

step 0: run this command

npm uninstall -g @angular/cli
npm cache clean

step 1: delete this folder: C:\Users\%YOUR-USERNAME%\AppData\Roaming\npm

step 2: uninstall Nodejs from Windows

step 3: restart your PC

step 4: install a fresh copy of Nodejs from here: https://nodejs.org/en/

step 5: install the CLI globally

npm install -g @angular/cli@latest


问:
Dynamic HTML controls through jQuery?
I have the following section of javascript/jQuery trying to create a grid overlay on a picture:

```<code>var $tbl = $('<table></table>');
for (var y = 1; y <= $rows; y++) {
    var $tr = $('<tr></tr>');
    for (var x = 1; x <= $cols; x++) {
        var $td = $('<td><input class = "chkDamage" type="checkbox" /></td>'); // hidden="hidden"

        $td.css('width', $gsize + 'px').css('height', $gsize + 'px');
        $td.addClass('unselected');
        $tr.append($td);

    }
    $tbl.append($tr);
}
</code>```

What I would like to do is to dynamically have a class name or id associated with each of the td elements so that I'm able to grab which squares are checked for later usage.  Is something like that possible?

答:
You want to track the "location" of the checkboxes in grid...

I would use a data attribute.

```<code>var tbl = $('<table></table>');
for (var y = 1; y <= $rows; y++) {
  var tr = $('<tr></tr>');
  for (var x = 1; x <= $cols; x++) {
    var td = $('<td><input class="chkDamage" type="checkbox"') /></td>; // hidden="hidden"

    td.attr("data-coord", y+","+x); // Adds an attribute "data-coord" containing a string like 4,2 (row #2, cell #4)

    td.css('width', $gsize + 'px').css('height', $gsize + 'px');
    td.addClass('unselected');
    tr.append(td);

  }
  tbl.append(tr);
}
</code>```

In procuded HTML, it will look like:

<input class="chkDamage" type="checkbox" data-coord="4,2"') />

So, after user action, you can retreive data-coord values for the checked checkboxes using something like:

```<code>var coord_arr=[];
$("input[type='checkbox']:checked").each(function(){
  coord_arr.push( $(this).data("coord") );
}
</code>```

So, coord_arr will be an array of strings... Like, for example : ["4,2","6,3",10,1"]

Title: Dynamic HTML controls through jQuery?

Body:
I have the following section of javascript/jQuery trying to create a grid overlay on a picture:

var $tbl = $('

');
for (var y = 1; y <= $rows; y++) {
    var $tr = $('

');
    for (var x = 1; x <= $cols; x++) {
        var $td = $('<input class = "chkDamage" type="checkbox" />	'); // hidden="hidden"

        $td.css('width', $gsize + 'px').css('height', $gsize + 'px');
        $td.addClass('unselected');
        $tr.append($td);

    }
    $tbl.append($tr);
}

What I would like to do is to dynamically have a class name or id associated with each of the td elements so that I'm able to grab which squares are checked for later usage.  Is something like that possible?

Body:
You want to track the "location" of the checkboxes in grid...

I would use a data attribute.

var tbl = $('<table></table>');
for (var y = 1; y <= $rows; y++) {
  var tr = $('<tr></tr>');
  for (var x = 1; x <= $cols; x++) {
    var td = $('<td><input class="chkDamage" type="checkbox"') /></td>; // hidden="hidden"

    td.attr("data-coord", y+","+x); // Adds an attribute "data-coord" containing a string like 4,2 (row #2, cell #4)

    td.css('width', $gsize + 'px').css('height', $gsize + 'px');
    td.addClass('unselected');
    tr.append(td);

  }
  tbl.append(tr);
}

In procuded HTML, it will look like:

<td><input class="chkDamage" type="checkbox" data-coord="4,2"') /></td>

So, after user action, you can retreive data-coord values for the checked checkboxes using something like:

var coord_arr=[];
$("input[type='checkbox']:checked").each(function(){
  coord_arr.push( $(this).data("coord") );
}

So, coord_arr will be an array of strings... Like, for example : ["4,2","6,3",10,1"]


问:
click event to fire just once
i want the click() event to fire just once.
I can use the removeClass() but doesnt sounds good if i need it again for smthing else.

Any ideas?

答:
You can use .one() to have an event fire just once:</p>

```<code>$('#item').one('click', function() {
    alert("You'll never see me again!");
});
</code>```

Title: click event to fire just once

Body:
You can use .one() to have an event fire just once:

$('#item').one('click', function() {
    alert("You'll never see me again!");
});