问:
Implementing DAO on a project where concrete class requires database connection
I'm trying to implement DAO pattern on my code,however I need mysql and sqlite connections in my concrete class since I do logic operations that require database entries. After creating this concrete class, I used it again to call these methods and use them, however it doesn't make any sense I guess since I created an interface for this, and should use it somehow.Should I also pass connections through my interface method-contracts?Please note that this works but I feel like I have done something redundant, so I'm asking for help.

I have a POJO class that I'm not going to post here,contains too much stuff and it's just a pojo class and has nothing to do with my question.

My DAO interface:

```<code>public interface AlarmDAO {

public List<Alarm> getAlarmList(String timestamp) throws SQLException, ParseException;
public void insertAlarm(byte[] backlog_id, Date timestamp) throws SQLException;}
</code>```

And my concrete class:

```<code>public class AlarmConcrete implements AlarmDAO {
private SQLiteJDBC sqLiteJDBC;
private Utility utility;
private MysqlConnection mysqlConnection;
private Connection connection;
Statement stmt;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public AlarmConcrete(MysqlConnection mysqlConnection,SQLiteJDBC sqLiteJDBC){
    this.sqLiteJDBC = sqLiteJDBC;
    this.mysqlConnection = mysqlConnection;
}

/**
 * @param timestamp
 * @return
 * @throws SQLException
 * @throws ParseException
 */
public List<Alarm> getAlarmList(String timestamp) throws SQLException, ParseException {
    List<Alarm> alarmList = new ArrayList<Alarm>();
    ResultSet rs = null;
    try {
        connection = mysqlConnection.getConnection();
        stmt = connection.createStatement();
        String modifiedStamp = "?"+timestamp+"?";
        String tokenize = modifiedStamp.replace("?","'");
        String query = "select * FROM alarm WHERE `timestamp` >= " + tokenize+ " ORDER BY `timestamp` ASC";
        rs = stmt.executeQuery(query);
        while (rs.next()) {
            Alarm alarmObject = new Alarm();
            alarmObject.setBacklogId(rs.getBytes("backlog_id"));
            Date date  = format.parse(rs.getString("timestamp"));
            alarmObject.setTimestamp(date);
            alarmObject.setEventId(rs.getBytes("event_id"));
            alarmList.add(alarmObject);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return alarmList;
}

/**
 * @param backlog_id
 * @param timestamp
 * @throws SQLException
 */
public void insertAlarm(byte[] backlog_id, Date timestamp) throws SQLException {
    try{
        Statement statement=null;
        Connection conn = sqLiteJDBC.getLiteConnection();
        String modTime = "'"+format.format(timestamp)+"'";
        System.out.println("Database opened");
        System.out.println("VALUES ("+backlog_id+","+timestamp+")");
        statement =conn.createStatement();
        String sql = "INSERT INTO `alarm_entries` (`backlog_id`,`timestamp`)" + "VALUES (X'"+Utility.bytesToHex(backlog_id)+"'," +
                ""+modTime+")";
        statement.executeUpdate(sql);

        statement.close();
    }catch (Exception e){
        System.out.println("Couldn't insert latest alarm");
    }

    System.out.println("Records created");
}
</code>```

}

I used it like this:

```<code>public ScheduledTask(MysqlConnection mysqlConnection,SQLiteJDBC conn) throws SQLException, ParseException, IOException {
    this.mysqlConnection = mysqlConnection;
    this.lastAlarm = new Alarm();
    this.dbUtil = new DBUtil(mysqlConnection);
    this.conn = conn;
    this.commandLineArgs = new CommandLineArgs();
    this.alarmEntryList = new AlarmConcrete(mysqlConnection,conn);
}...{....alarmEntryList.insertAlarm(lastAlarm.getBacklogId(), lastAlarm.getTimestamp());}
</code>```

In last piece of code I initialized my concrete class in constructor of another class and used it in one of its methods, but again, why did I use interface in the first place?Many thanks

答:
1) Remove throws SQLException from interface. Don't tall anyone, except DAO-layer, which DB you are using. Create and throw more high-level exceptions, like EAlreadyExist, EDisconnected, etc. Even ParseException is bad idea, because its mean that "user" can screw up your query. Use only valid sql-query's and put data into them over prepared statements.

2) Use try-with-resources statement, instead of manually closing. Statement wouldn't be closed, if occurred  exception. By the way, clean up mess in fields. Why there is Statement and other "local" objects?

3) I would have created some IDBCore and place there all DB-connections. Easiest approach is to provide Statement IDBCore.createStatement(string sql) and use it in all other classes. It will divide DAO into low-level DAO, which know all about DB, and hi-level DAO, that only provide SQL and logic.

- why did I use interface in the first place?

On DAO-layer level they are kinda useless, because all know about all others, but upper levels will/must know only about interfaces, not about classes.

Body:
I'm trying to implement DAO pattern on my code,however I need mysql and sqlite connections in my concrete class since I do logic operations that require database entries. After creating this concrete class, I used it again to call these methods and use them, however it doesn't make any sense I guess since I created an interface for this, and should use it somehow.Should I also pass connections through my interface method-contracts?Please note that this works but I feel like I have done something redundant, so I'm asking for help.

I have a POJO class that I'm not going to post here,contains too much stuff and it's just a pojo class and has nothing to do with my question.

My DAO interface:

public interface AlarmDAO {

public List<Alarm> getAlarmList(String timestamp) throws SQLException, ParseException;
public void insertAlarm(byte[] backlog_id, Date timestamp) throws SQLException;}

And my concrete class:

public class AlarmConcrete implements AlarmDAO {
private SQLiteJDBC sqLiteJDBC;
private Utility utility;
private MysqlConnection mysqlConnection;
private Connection connection;
Statement stmt;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public AlarmConcrete(MysqlConnection mysqlConnection,SQLiteJDBC sqLiteJDBC){
    this.sqLiteJDBC = sqLiteJDBC;
    this.mysqlConnection = mysqlConnection;
}

/**
 * @param timestamp
 * @return
 * @throws SQLException
 * @throws ParseException
 */
public List<Alarm> getAlarmList(String timestamp) throws SQLException, ParseException {
    List<Alarm> alarmList = new ArrayList<Alarm>();
    ResultSet rs = null;
    try {
        connection = mysqlConnection.getConnection();
        stmt = connection.createStatement();
        String modifiedStamp = "?"+timestamp+"?";
        String tokenize = modifiedStamp.replace("?","'");
        String query = "select * FROM alarm WHERE `timestamp` >= " + tokenize+ " ORDER BY `timestamp` ASC";
        rs = stmt.executeQuery(query);
        while (rs.next()) {
            Alarm alarmObject = new Alarm();
            alarmObject.setBacklogId(rs.getBytes("backlog_id"));
            Date date  = format.parse(rs.getString("timestamp"));
            alarmObject.setTimestamp(date);
            alarmObject.setEventId(rs.getBytes("event_id"));
            alarmList.add(alarmObject);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return alarmList;
}

/**
 * @param backlog_id
 * @param timestamp
 * @throws SQLException
 */
public void insertAlarm(byte[] backlog_id, Date timestamp) throws SQLException {
    try{
        Statement statement=null;
        Connection conn = sqLiteJDBC.getLiteConnection();
        String modTime = "'"+format.format(timestamp)+"'";
        System.out.println("Database opened");
        System.out.println("VALUES ("+backlog_id+","+timestamp+")");
        statement =conn.createStatement();
        String sql = "INSERT INTO `alarm_entries` (`backlog_id`,`timestamp`)" + "VALUES (X'"+Utility.bytesToHex(backlog_id)+"'," +
                ""+modTime+")";
        statement.executeUpdate(sql);

        statement.close();
    }catch (Exception e){
        System.out.println("Couldn't insert latest alarm");
    }

    System.out.println("Records created");
}

}

I used it like this:

public ScheduledTask(MysqlConnection mysqlConnection,SQLiteJDBC conn) throws SQLException, ParseException, IOException {
    this.mysqlConnection = mysqlConnection;
    this.lastAlarm = new Alarm();
    this.dbUtil = new DBUtil(mysqlConnection);
    this.conn = conn;
    this.commandLineArgs = new CommandLineArgs();
    this.alarmEntryList = new AlarmConcrete(mysqlConnection,conn);
}...{....alarmEntryList.insertAlarm(lastAlarm.getBacklogId(), lastAlarm.getTimestamp());}

In last piece of code I initialized my concrete class in constructor of another class and used it in one of its methods, but again, why did I use interface in the first place?Many thanks


来源: stackexchange

问:
Why i cant join string with first value of dictionary?
I would like to ask that why cant i join the string with the first value of the dictionary?

```<code>Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat", 0},
    {"dog", 1},
    {"llama", 2},
    {"iguana", 3}
};

string z = string.Join("Test_", d.Select(x => x.Value + "\n"));
</code>```

These are the value of Z now

```<code>0
Test_1
Test_2
Test_3
</code>```

答:
The string.Join method puts the separator between the elements of your sequence, not in front of each of them. So, for example

```<code>string[] values = new[] { "one", "two" };
string x = string.Join(" and ", values);
</code>```

will produce "one and two", not "and one and two".

ContentLicense: CC BY-SA 3.0

Body:
I would like to ask that why cant i join the string with the first value of the dictionary?

Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat", 0},
    {"dog", 1},
    {"llama", 2},
    {"iguana", 3}
};

string z = string.Join("Test_", d.Select(x => x.Value + "\n"));

These are the value of Z now

0
Test_1
Test_2
Test_3

Body:
The string.Join method puts the separator between the elements of your sequence, not in front of each of them. So, for example

string[] values = new[] { "one", "two" };
string x = string.Join(" and ", values);

will produce "one and two", not "and one and two".


问:
Is there a way to constraint the together value in Serializer?
I have a EmailCreateSerializer, I can let creator pass receive_group id or receive_user id to send an email to them:

```<code>class EmailCreateSerializer(Serializer):
    receive_group = serializers.IntegerField(allow_null=True)
    receive_user = serializers.IntegerField(allow_null=True)
</code>```

Either pass the receive_group (send to a group), or receive_user (send to a single user).

But I want to have a constraint, that both of them (receive_group, receive_user) cannot be null.

Is there a way to do this in Serializer class?

答:
You can override Serializer's validate() method to check this:

```<code>class EmailCreateSerializer(Serializer):
    receive_group = serializers.IntegerField(allow_null=True)
    receive_user = serializers.IntegerField(allow_null=True)

    def validate(self, data):
        if data['receive_group'] is None and data['receive_user'] is None:
            raise serializers.ValidationError("Group or User cannot be empty, pass information for at least one of those.")
        return data
</code>```

Documentation: http://www.django-rest-framework.org/api-guide/serializers/#object-level-validation

Body:
I have a EmailCreateSerializer, I can let creator pass receive_group id or receive_user id to send an email to them:

class EmailCreateSerializer(Serializer):
    receive_group = serializers.IntegerField(allow_null=True)
    receive_user = serializers.IntegerField(allow_null=True)

Either pass the receive_group (send to a group), or receive_user (send to a single user).

But I want to have a constraint, that both of them (receive_group, receive_user) cannot be null.

Is there a way to do this in Serializer class?

Body:
You can override Serializer's validate() method to check this:

class EmailCreateSerializer(Serializer):
    receive_group = serializers.IntegerField(allow_null=True)
    receive_user = serializers.IntegerField(allow_null=True)

    def validate(self, data):
        if data['receive_group'] is None and data['receive_user'] is None:
            raise serializers.ValidationError("Group or User cannot be empty, pass information for at least one of those.")
        return data

Documentation: http://www.django-rest-framework.org/api-guide/serializers/#object-level-validation


问:
How to get back Kafka producer and consumer configuration (Java API)?
The use case is following.
I am passing producer or consumer reference over many objects instances in Java code.
At some of them I would like to do some checks for the Kafka configuration.
It means I would like to get back, what effective configuration  is stored in Kafka Producer/Consumer (including defaults).
I do not see anthing explicit in java docs:

KafkaProducer

KafkaConsumer

So, how to get back Kafka producer and consumer configuration?

答:
Unfortunately it's not possible. I have to admit it could be a useful feature for showing the "core" configuration properties at least (avoiding the possibility to get the "secrets" for authentication stuff for example).
The only solution that I see today for you is to have a link between the consumer/producer instance and the related properties bag used for setting the client configuration. I understand it's a waste of memory because such configuration is internally in the client but you need to keep your properties bag for having it.</p>


问:
make CSS corner style
I am confused, how to make the design of display options like this with css :

how to make corner style like this picture ... please help me. thanks

答:
https://jsfiddle.net/pksdhofc/1/

```<code><div class='arrow'></div>

.arrow{
  width: 30px;
  height: 80px;
  background-color: #999;
  -webkit-clip-path: polygon(0 50%, 100% 0, 100% 100%, 0 50%);
  clip-path: polygon(0 50%, 100% 0, 100% 100%, 0 50%);
}
</code>```

clip-path uses multiple X and Y coords to create an svg. You can minipulate as you like but that kinda makes what you need.

Title: make CSS corner style

Body:
https://jsfiddle.net/pksdhofc/1/

<div class='arrow'></div>

.arrow{
  width: 30px;
  height: 80px;
  background-color: #999;
  -webkit-clip-path: polygon(0 50%, 100% 0, 100% 100%, 0 50%);
  clip-path: polygon(0 50%, 100% 0, 100% 100%, 0 50%);
}

clip-path uses multiple X and Y coords to create an svg. You can minipulate as you like but that kinda makes what you need.


问:
Expanding specific JTree Node with FileTree as TreeModel
I am trying to build JTree based file browser and trying to navigate to particular path using setSelectionPath with DefaultMutableTreeNode.

I have taken the reference of the code from here

```<code>import java.io.File;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import static javax.management.Query.value;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class FileSysBrowser extends JFrame {

    public JTree fileTree;
    private FileSystemModel fileSystemModel;
    static String REPO = "repo/dinesh/trunk";
    static String[] REPO_PATH = REPO.split("/", -1);
    static int repoPathIdx = 0;
    private JTextArea fileDetailsTextArea = new JTextArea();

    public FileSysBrowser(String directory) {
        System.out.println(Arrays.toString(REPO_PATH));
        setTitle("FileSysBrowser");
        fileDetailsTextArea.setEditable(false);
        fileSystemModel = new FileSystemModel(new File(directory));
        fileTree = new JTree(fileSystemModel);
        fileTree.setEditable(true);
        fileTree.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent event) {
//                System.out.println(fileTree.getLastSelectedPathComponent());
//                File file = (File) fileTree.getLastSelectedPathComponent();
//                fileDetailsTextArea.setText(getFileDetails(file));
            }
        });
        getContentPane().add(new JScrollPane(fileTree));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(640, 480);
        setVisible(true);
    }

    private DefaultMutableTreeNode buildNodeFromString(String path) {
        String[] s = path.split("/");
        File myFilePath = new File(path);

        DefaultMutableTreeNode node, lastNode = null, root = null;
        for (String str : s) {
            if (str.indexOf(":") != -1) {
                str = str.substring(0, str.indexOf(":"));
            }
            node = new DefaultMutableTreeNode(str);
            if (root == null) {
                root = node;
            }
            if (lastNode != null) {
                lastNode.add(node);
            }
            lastNode = node;
        }
        return root;
    }

    public static void main(String args[]) {

        FileSysBrowser fileSysBrowser = new FileSysBrowser("/");

        JTree jt = fileSysBrowser.fileTree;

//        jt.expandRow(21);
//        jt.expandRow(32);
//        TreePath pathForRow = jt.getPathForRow(4);
//        System.out.println(pathForRow);
        DefaultMutableTreeNode node = fileSysBrowser.buildNodeFromString("repo/dinesh/trunk");

        TreePath pathForRow = new TreePath(node.getLastLeaf().getPath());
        System.out.println("pathForRow : " + pathForRow);
        jt.setSelectionPath(pathForRow);
    }
}

class FileSystemModel implements TreeModel {

    private File root;

    private final Vector listeners = new Vector();

    public FileSystemModel(File rootDirectory) {
        root = rootDirectory;
    }

    @Override
    public Object getRoot() {
        return root;
    }

    @Override
    public Object getChild(Object parent, int index) {
        File directory = (File) parent;
        String[] children = directory.list();
        Arrays.sort(children);
        String currentChild = children[index];
        return new TreeFile(directory, currentChild);
    }

    @Override
    public int getChildCount(Object parent) {
        File file = (File) parent;
        if (file.isDirectory()) {
            String[] fileList = file.list();
            if (fileList != null) {
                return file.list().length;
            }
        }
        return 0;
    }

    @Override
    public boolean isLeaf(Object node) {
        if (node.getClass() == DefaultMutableTreeNode.class) {
            DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) node;
            System.out.println("chidcount ->" + dmtn.getChildCount());
            System.out.println(dmtn.getChildCount()==0);
            return dmtn.getChildCount() == 0;
        } else {
            File file = (File) node;
            return file.isFile();
        }
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        File directory = (File) parent;
        File file = (File) child;
        String[] children = directory.list();
        for (int i = 0; i < children.length; i++) {
            if (file.getName().equals(children[i])) {
                return i;
            }
        }
        return -1;

    }

    @Override
    public void valueForPathChanged(TreePath path, Object value) {
        File oldFile = (File) path.getLastPathComponent();
        String fileParentPath = oldFile.getParent();
        String newFileName = (String) value;
        File targetFile = new File(fileParentPath, newFileName);
        oldFile.renameTo(targetFile);
        File parent = new File(fileParentPath);
        int[] changedChildrenIndices = {getIndexOfChild(parent, targetFile)};
        Object[] changedChildren = {targetFile};
        fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);

    }

    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
        TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
        Iterator iterator = listeners.iterator();
        TreeModelListener listener = null;
        while (iterator.hasNext()) {
            listener = (TreeModelListener) iterator.next();
            listener.treeNodesChanged(event);
        }
    }

    @Override
    public void addTreeModelListener(TreeModelListener listener) {
        listeners.add(listener);
    }

    @Override
    public void removeTreeModelListener(TreeModelListener listener) {
        listeners.remove(listener);
    }

    private class TreeFile extends File {

        public TreeFile(File parent, String child) {
            super(parent, child);
        }

        @Override
        public String toString() {
            return getName();
        }
    }
}
</code>```

I have just included check in the isLeaf alone. As of now, it is not expanding the path.

With expandRow only, I am able to achieve the node expansion.

What should I do to make it work with setSelectionPath ?

答:
After exploring about TreeModel, I found a solution. I have extended the DefaultMutableTreeNode as FileMutuableTreeNode and wherever DefaultMutableTreeNode is used with TreeModel, I have replaced it with FileMutuableTreeNode. Hope it is useful for those who are reading this in near future.

The actual question is based on the below reference link.

Reference : http://www.javaprogrammingforums.com/java-swing-tutorials/7944-how-use-jtree-create-file-system-viewer-tree.html

FileSysBrowser.java

```<code>//Reference : http://www.javaprogrammingforums.com/java-swing-tutorials/7944-how-use-jtree-create-file-system-viewer-tree.html
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class FileSysBrowser extends JFrame {

    public JTree fileTree;
    private FileSystemModel fileSystemModel;

    public FileSysBrowser(String directory) {
//        System.out.println("REPO : " + Arrays.toString(REPO_PATH));
        setTitle("FileSysBrowser");
        fileSystemModel = new FileSystemModel(new FileMutableTreeNode(new File(directory)));
        fileTree = new JTree(fileSystemModel);
        fileTree.setEditable(false);
        JPanel pnlMain = new JPanel(new BorderLayout(5, 5));
        pnlMain.add(new JScrollPane(fileTree), BorderLayout.CENTER);
        final JButton btn = new JButton("click");
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Thread() {
                    @Override
                    public void run() {
                        btn.setEnabled(false);
                        expandNodePath("/repo/dinesh/trunk/Design/");
                        btn.setEnabled(true);
                    }
                }.start();

            }
        });
        pnlMain.add(btn, BorderLayout.PAGE_END);
        getContentPane().add(pnlMain);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(640, 480);
        setVisible(true);
    }
//Reference : https://stackoverflow.com/questions/8210630/how-to-search-a-particular-node-in-jtree-and-make-that-node-expanded
//Thanks to 'trashgod' for the answer
    private FileMutableTreeNode findNode(FileMutableTreeNode root, String s) {
        @SuppressWarnings("unchecked")
        Enumeration<FileMutableTreeNode> e = root.depthFirstEnumeration();
        while (e.hasMoreElements()) {
            FileMutableTreeNode node = e.nextElement();
            if (node.toString().equals(s)) {
//                return new TreePath(node.getPath());
                return node;
            }
        }
        return null;
    }

    private void expandNodePath(String filePath) {
        if(filePath.startsWith("/")) {
            filePath = filePath.replaceFirst("/", "");
        }
        String[] files = filePath.split("/");
        //Initializing the parent node as 'root'
        FileMutableTreeNode parentNode = fileSystemModel.getRoot();
        for (String file : files) {
            FileMutableTreeNode childNode = findNode(parentNode, file);
            fileTree.expandPath(new TreePath(childNode.getPath()));
            // Then setting the current 'child' node as parent node
            // for the next iteration
            parentNode = childNode;
        }

//  The below code is what the expansion of above for loop code.
//  For ease of understanding, I have kept it for others.
//        FileMutableTreeNode repoNode = findNode(fileSystemModel.getRoot(), "repo");
//        fileTree.expandPath(new TreePath(repoNode.getPath()));
//        FileMutableTreeNode dineshNode = findNode(repoNode, "dinesh");
//        fileTree.expandPath(new TreePath(dineshNode.getPath()));

    }

    public static void main(String args[]) {
//        System.out.println(new File("/").getName());

        FileSysBrowser fileSysBrowser = new FileSysBrowser("/");

        JTree jt = fileSysBrowser.fileTree;

        jt.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                TreePath tp = e.getNewLeadSelectionPath();
                if (tp != null) {
                    System.out.println(tp);
//                    System.out.println(tp.getLastPathComponent());
                }
            }
        });
    }
}

class FileSystemModel implements TreeModel {

//    private File root;
    private FileMutableTreeNode root;

    private final Vector listeners = new Vector();

    public FileSystemModel(FileMutableTreeNode rootDirectory) {
        root = rootDirectory;
    }

    @Override
    public FileMutableTreeNode getRoot() {
        return root;
    }

    @Override
    public Object getChild(Object parent, int index) {

        FileMutableTreeNode parentNode = (FileMutableTreeNode) parent;
        File directory = parentNode.getFileNode();
        String[] children = directory.list();
        Arrays.sort(children);
        String currentChild = children[index];
        FileMutableTreeNode childNode = new FileMutableTreeNode(new File(directory, currentChild));
        if (parentNode.toString().equals("/")) {
            root.add(childNode);
        } else {
            parentNode.add(childNode);
        }
        return childNode;
    }

    @Override
    public int getChildCount(Object parent) {
        FileMutableTreeNode fileNode = (FileMutableTreeNode) parent;
        File file = fileNode.getFileNode();
        if (file.isDirectory()) {
            String[] fileList = file.list();
            if (fileList != null) {
                return file.list().length;
            }
        }
        return 0;
    }

    @Override
    public boolean isLeaf(Object node) {
        FileMutableTreeNode fileNode = (FileMutableTreeNode) node;
        File file = fileNode.getFileNode();
        return file.isFile();
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        FileMutableTreeNode parentNode = (FileMutableTreeNode) parent;
        File directory = parentNode.getFileNode();
        FileMutableTreeNode childNode = (FileMutableTreeNode) child;
        File file = childNode.getFileNode();
        String[] children = directory.list();
        for (int i = 0; i < children.length; i++) {
            if (file.getName().equals(children[i])) {
                return i;
            }
        }
        return -1;

    }

    @Override
    public void valueForPathChanged(TreePath path, Object value) {
        System.out.println("valueForPathChanged -> path : " + path + ", value : " + value);
    }

    @Override
    public void addTreeModelListener(TreeModelListener listener) {
        listeners.add(listener);
    }

    @Override
    public void removeTreeModelListener(TreeModelListener listener) {
        listeners.remove(listener);
    }

}
</code>```

FileMutableTreeNode .java

```<code>import java.io.File;
import javax.swing.tree.DefaultMutableTreeNode;

class FileMutableTreeNode extends DefaultMutableTreeNode {

    private File fileNode = null;

    public FileMutableTreeNode(File fileNode) {
        this.fileNode = fileNode;
    }

    public File getFileNode() {
        return fileNode;
    }

    @Override
    public String toString() {
        //For root, returning the name as '/'
        if (fileNode.getAbsolutePath().equals("/")) {
            return "/";
        } else {
            return fileNode.getName();
        }
    }
}
</code>```

Body:
I am trying to build JTree based file browser and trying to navigate to particular path using setSelectionPath with DefaultMutableTreeNode.

I have taken the reference of the code from here

import java.io.File;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
import static javax.management.Query.value;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class FileSysBrowser extends JFrame {

    public JTree fileTree;
    private FileSystemModel fileSystemModel;
    static String REPO = "repo/dinesh/trunk";
    static String[] REPO_PATH = REPO.split("/", -1);
    static int repoPathIdx = 0;
    private JTextArea fileDetailsTextArea = new JTextArea();

    public FileSysBrowser(String directory) {
        System.out.println(Arrays.toString(REPO_PATH));
        setTitle("FileSysBrowser");
        fileDetailsTextArea.setEditable(false);
        fileSystemModel = new FileSystemModel(new File(directory));
        fileTree = new JTree(fileSystemModel);
        fileTree.setEditable(true);
        fileTree.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent event) {
//                System.out.println(fileTree.getLastSelectedPathComponent());
//                File file = (File) fileTree.getLastSelectedPathComponent();
//                fileDetailsTextArea.setText(getFileDetails(file));
            }
        });
        getContentPane().add(new JScrollPane(fileTree));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(640, 480);
        setVisible(true);
    }

    private DefaultMutableTreeNode buildNodeFromString(String path) {
        String[] s = path.split("/");
        File myFilePath = new File(path);

        DefaultMutableTreeNode node, lastNode = null, root = null;
        for (String str : s) {
            if (str.indexOf(":") != -1) {
                str = str.substring(0, str.indexOf(":"));
            }
            node = new DefaultMutableTreeNode(str);
            if (root == null) {
                root = node;
            }
            if (lastNode != null) {
                lastNode.add(node);
            }
            lastNode = node;
        }
        return root;
    }

    public static void main(String args[]) {

        FileSysBrowser fileSysBrowser = new FileSysBrowser("/");

        JTree jt = fileSysBrowser.fileTree;

//        jt.expandRow(21);
//        jt.expandRow(32);
//        TreePath pathForRow = jt.getPathForRow(4);
//        System.out.println(pathForRow);
        DefaultMutableTreeNode node = fileSysBrowser.buildNodeFromString("repo/dinesh/trunk");

        TreePath pathForRow = new TreePath(node.getLastLeaf().getPath());
        System.out.println("pathForRow : " + pathForRow);
        jt.setSelectionPath(pathForRow);
    }
}

class FileSystemModel implements TreeModel {

    private File root;

    private final Vector listeners = new Vector();

    public FileSystemModel(File rootDirectory) {
        root = rootDirectory;
    }

    @Override
    public Object getRoot() {
        return root;
    }

    @Override
    public Object getChild(Object parent, int index) {
        File directory = (File) parent;
        String[] children = directory.list();
        Arrays.sort(children);
        String currentChild = children[index];
        return new TreeFile(directory, currentChild);
    }

    @Override
    public int getChildCount(Object parent) {
        File file = (File) parent;
        if (file.isDirectory()) {
            String[] fileList = file.list();
            if (fileList != null) {
                return file.list().length;
            }
        }
        return 0;
    }

    @Override
    public boolean isLeaf(Object node) {
        if (node.getClass() == DefaultMutableTreeNode.class) {
            DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) node;
            System.out.println("chidcount ->" + dmtn.getChildCount());
            System.out.println(dmtn.getChildCount()==0);
            return dmtn.getChildCount() == 0;
        } else {
            File file = (File) node;
            return file.isFile();
        }
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        File directory = (File) parent;
        File file = (File) child;
        String[] children = directory.list();
        for (int i = 0; i < children.length; i++) {
            if (file.getName().equals(children[i])) {
                return i;
            }
        }
        return -1;

    }

    @Override
    public void valueForPathChanged(TreePath path, Object value) {
        File oldFile = (File) path.getLastPathComponent();
        String fileParentPath = oldFile.getParent();
        String newFileName = (String) value;
        File targetFile = new File(fileParentPath, newFileName);
        oldFile.renameTo(targetFile);
        File parent = new File(fileParentPath);
        int[] changedChildrenIndices = {getIndexOfChild(parent, targetFile)};
        Object[] changedChildren = {targetFile};
        fireTreeNodesChanged(path.getParentPath(), changedChildrenIndices, changedChildren);

    }

    private void fireTreeNodesChanged(TreePath parentPath, int[] indices, Object[] children) {
        TreeModelEvent event = new TreeModelEvent(this, parentPath, indices, children);
        Iterator iterator = listeners.iterator();
        TreeModelListener listener = null;
        while (iterator.hasNext()) {
            listener = (TreeModelListener) iterator.next();
            listener.treeNodesChanged(event);
        }
    }

    @Override
    public void addTreeModelListener(TreeModelListener listener) {
        listeners.add(listener);
    }

    @Override
    public void removeTreeModelListener(TreeModelListener listener) {
        listeners.remove(listener);
    }

    private class TreeFile extends File {

        public TreeFile(File parent, String child) {
            super(parent, child);
        }

        @Override
        public String toString() {
            return getName();
        }
    }
}

I have just included check in the isLeaf alone. As of now, it is not expanding the path.

With expandRow only, I am able to achieve the node expansion.

What should I do to make it work with setSelectionPath ?

Body:
After exploring about TreeModel, I found a solution. I have extended the DefaultMutableTreeNode as FileMutuableTreeNode and wherever DefaultMutableTreeNode is used with TreeModel, I have replaced it with FileMutuableTreeNode. Hope it is useful for those who are reading this in near future.

The actual question is based on the below reference link.

Reference : http://www.javaprogrammingforums.com/java-swing-tutorials/7944-how-use-jtree-create-file-system-viewer-tree.html

FileSysBrowser.java

//Reference : http://www.javaprogrammingforums.com/java-swing-tutorials/7944-how-use-jtree-create-file-system-viewer-tree.html
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.JButton;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

public class FileSysBrowser extends JFrame {

    public JTree fileTree;
    private FileSystemModel fileSystemModel;

    public FileSysBrowser(String directory) {
//        System.out.println("REPO : " + Arrays.toString(REPO_PATH));
        setTitle("FileSysBrowser");
        fileSystemModel = new FileSystemModel(new FileMutableTreeNode(new File(directory)));
        fileTree = new JTree(fileSystemModel);
        fileTree.setEditable(false);
        JPanel pnlMain = new JPanel(new BorderLayout(5, 5));
        pnlMain.add(new JScrollPane(fileTree), BorderLayout.CENTER);
        final JButton btn = new JButton("click");
        btn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new Thread() {
                    @Override
                    public void run() {
                        btn.setEnabled(false);
                        expandNodePath("/repo/dinesh/trunk/Design/");
                        btn.setEnabled(true);
                    }
                }.start();

            }
        });
        pnlMain.add(btn, BorderLayout.PAGE_END);
        getContentPane().add(pnlMain);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(640, 480);
        setVisible(true);
    }
//Reference : https://stackoverflow.com/questions/8210630/how-to-search-a-particular-node-in-jtree-and-make-that-node-expanded
//Thanks to 'trashgod' for the answer
    private FileMutableTreeNode findNode(FileMutableTreeNode root, String s) {
        @SuppressWarnings("unchecked")
        Enumeration<FileMutableTreeNode> e = root.depthFirstEnumeration();
        while (e.hasMoreElements()) {
            FileMutableTreeNode node = e.nextElement();
            if (node.toString().equals(s)) {
//                return new TreePath(node.getPath());
                return node;
            }
        }
        return null;
    }

    private void expandNodePath(String filePath) {
        if(filePath.startsWith("/")) {
            filePath = filePath.replaceFirst("/", "");
        }
        String[] files = filePath.split("/");
        //Initializing the parent node as 'root'
        FileMutableTreeNode parentNode = fileSystemModel.getRoot();
        for (String file : files) {
            FileMutableTreeNode childNode = findNode(parentNode, file);
            fileTree.expandPath(new TreePath(childNode.getPath()));
            // Then setting the current 'child' node as parent node
            // for the next iteration
            parentNode = childNode;
        }

//  The below code is what the expansion of above for loop code.
//  For ease of understanding, I have kept it for others.
//        FileMutableTreeNode repoNode = findNode(fileSystemModel.getRoot(), "repo");
//        fileTree.expandPath(new TreePath(repoNode.getPath()));
//        FileMutableTreeNode dineshNode = findNode(repoNode, "dinesh");
//        fileTree.expandPath(new TreePath(dineshNode.getPath()));

    }

    public static void main(String args[]) {
//        System.out.println(new File("/").getName());

        FileSysBrowser fileSysBrowser = new FileSysBrowser("/");

        JTree jt = fileSysBrowser.fileTree;

        jt.addTreeSelectionListener(new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                TreePath tp = e.getNewLeadSelectionPath();
                if (tp != null) {
                    System.out.println(tp);
//                    System.out.println(tp.getLastPathComponent());
                }
            }
        });
    }
}

class FileSystemModel implements TreeModel {

//    private File root;
    private FileMutableTreeNode root;

    private final Vector listeners = new Vector();

    public FileSystemModel(FileMutableTreeNode rootDirectory) {
        root = rootDirectory;
    }

    @Override
    public FileMutableTreeNode getRoot() {
        return root;
    }

    @Override
    public Object getChild(Object parent, int index) {

        FileMutableTreeNode parentNode = (FileMutableTreeNode) parent;
        File directory = parentNode.getFileNode();
        String[] children = directory.list();
        Arrays.sort(children);
        String currentChild = children[index];
        FileMutableTreeNode childNode = new FileMutableTreeNode(new File(directory, currentChild));
        if (parentNode.toString().equals("/")) {
            root.add(childNode);
        } else {
            parentNode.add(childNode);
        }
        return childNode;
    }

    @Override
    public int getChildCount(Object parent) {
        FileMutableTreeNode fileNode = (FileMutableTreeNode) parent;
        File file = fileNode.getFileNode();
        if (file.isDirectory()) {
            String[] fileList = file.list();
            if (fileList != null) {
                return file.list().length;
            }
        }
        return 0;
    }

    @Override
    public boolean isLeaf(Object node) {
        FileMutableTreeNode fileNode = (FileMutableTreeNode) node;
        File file = fileNode.getFileNode();
        return file.isFile();
    }

    @Override
    public int getIndexOfChild(Object parent, Object child) {
        FileMutableTreeNode parentNode = (FileMutableTreeNode) parent;
        File directory = parentNode.getFileNode();
        FileMutableTreeNode childNode = (FileMutableTreeNode) child;
        File file = childNode.getFileNode();
        String[] children = directory.list();
        for (int i = 0; i < children.length; i++) {
            if (file.getName().equals(children[i])) {
                return i;
            }
        }
        return -1;

    }

    @Override
    public void valueForPathChanged(TreePath path, Object value) {
        System.out.println("valueForPathChanged -> path : " + path + ", value : " + value);
    }

    @Override
    public void addTreeModelListener(TreeModelListener listener) {
        listeners.add(listener);
    }

    @Override
    public void removeTreeModelListener(TreeModelListener listener) {
        listeners.remove(listener);
    }

}

FileMutableTreeNode .java

import java.io.File;
import javax.swing.tree.DefaultMutableTreeNode;

class FileMutableTreeNode extends DefaultMutableTreeNode {

    private File fileNode = null;

    public FileMutableTreeNode(File fileNode) {
        this.fileNode = fileNode;
    }

    public File getFileNode() {
        return fileNode;
    }

    @Override
    public String toString() {
        //For root, returning the name as '/'
        if (fileNode.getAbsolutePath().equals("/")) {
            return "/";
        } else {
            return fileNode.getName();
        }
    }
}


问:
log4js - node package - not writing to file
I am novice to nodejs and wanted my node app to log to a file as well as console.

Here is my code structure:

fpa_log4j.json:

```<code>{
  "appenders": {
    "fpa_file": {
      "type": "file",
      "filename": "fpa.log",
      "maxLogSize": 10485760,
      "backups": 10,
      "compress": true
    },
    "screen": {
      "type": "stdout",
      "layout": {
        "type": "coloured"
      }
    }
  },
  "categories": {
    "default": {
      "appenders": [
        "fpa_file",
        "screen"
      ],
      "level": "trace"
    }
  }
}
</code>```

config.js

```<code>var LOG4J_CFG = 'config/fpa_log4j.json';
var fs = require('fs');
var log4js = require('log4js');
var path = require('path');

LOG4J_CFG = path.resolve(LOG4J_CFG);
log4js.configure(JSON.parse(fs.readFileSync(LOG4J_CFG, 'utf8')));
....
....
module.exports = {
    log4js,
    ....
    ....
}
</code>```

app.js

```<code>var cfg = require('./config');
var log = cfg.log4js.getLogger("appMain");
log.info('FPA program STARTED!');
</code>```

OUTPUT

```<code>[2017-12-04T03:20:17.791] [INFO] appMain - FPA program STARTED!
</code>```

However the log file seems to be empty:

```<code>dir fpa.log
 Volume in drive C is XXXXXXXXX
 Volume Serial Number is XXXXXXXXXXXX

 Directory of c:\fpaMain

12/04/2017  12:13 AM                 0 fpa.log
               1 File(s)              0 bytes
               0 Dir(s)  12,242,776,064 bytes free
</code>```

To be frank, I was able to make this work few days back. But then something got changed (alas, not able to recollect what it is!) I guess, and then logging into the file stopped.

答:
Ok. So I figured it out finally. Sharing it here for the sake of others. Here it comes:

There were few more lines in the app.js (which were removed for clarity) and the app was in fact crashing immediately after the log.info() statement. And I was expecting the statements to appear in the log file as it appeared on the console. But then, I failed to realize that, unlike other programming languages, nodejs has got the powerful feature of parallel processing by birth itself (which in fact was one of the core reasons for my love towards it :)).

So in my case, due to its unparallel feature of parallel processing, nodejs just fired the log statement and went on processing other statements. And, when it crashed, it took down the whole program with it. Since writing to the console was way much faster than IO (for the obvious reasons!!), it showed up on the screen faster. However before it could write to the file system the app got crashed, ending up nothing being written to the file!

Lesson Learned:

Always remember that nodejs === parallel processing

For any IO related issues like the above, ensure that the program runs to complete or at least for some more time before it crashes,
  thus providing enough time for the IO to complete.

Body:
I am novice to nodejs and wanted my node app to log to a file as well as console.

Here is my code structure:

fpa_log4j.json:

{
  "appenders": {
    "fpa_file": {
      "type": "file",
      "filename": "fpa.log",
      "maxLogSize": 10485760,
      "backups": 10,
      "compress": true
    },
    "screen": {
      "type": "stdout",
      "layout": {
        "type": "coloured"
      }
    }
  },
  "categories": {
    "default": {
      "appenders": [
        "fpa_file",
        "screen"
      ],
      "level": "trace"
    }
  }
}

config.js

var LOG4J_CFG = 'config/fpa_log4j.json';
var fs = require('fs');
var log4js = require('log4js');
var path = require('path');

LOG4J_CFG = path.resolve(LOG4J_CFG);
log4js.configure(JSON.parse(fs.readFileSync(LOG4J_CFG, 'utf8')));
....
....
module.exports = {
    log4js,
    ....
    ....
}

app.js

var cfg = require('./config');
var log = cfg.log4js.getLogger("appMain");
log.info('FPA program STARTED!');

OUTPUT

[2017-12-04T03:20:17.791] [INFO] appMain - FPA program STARTED!

However the log file seems to be empty:

dir fpa.log
 Volume in drive C is XXXXXXXXX
 Volume Serial Number is XXXXXXXXXXXX

 Directory of c:\fpaMain

12/04/2017  12:13 AM                 0 fpa.log
               1 File(s)              0 bytes
               0 Dir(s)  12,242,776,064 bytes free

To be frank, I was able to make this work few days back. But then something got changed (alas, not able to recollect what it is!) I guess, and then logging into the file stopped.


问:
event when user check some checkbox
I want to make event when user check some checkbox.

I wrote the code below but nothing happened -

I added "alert", but it doesn't shown

HTML

```<code><td id='checkbox_val_to_reveal'>

    <div class="form-group">
        <label>Status</label>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA</label></div>
        <div class='checkbox'><label><input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply</label></div>
    </div>

</td>

<div class='reveal_div_by_checkbox_val'>
    <p><label class="title">Ticket Cause</label><br />
</div>
</code>```

JS

```<code><script>
//  $("#checkbox_val_to_reveal .flat").change(function() {

    $("#checkbox_val_to_reveal input[type='checkbox']").change(function() {
        alert("RRR");

    if ($(this).val() === "3" && $(this).is(":checked")) {
        $(".reveal_div_by_checkbox_val").show();
    } else {
        $(".reveal_div_by_checkbox_val").hide();
    }
    });
</script>
</code>```

答: You should define table structure properly Table/Tr/Td. Js code is proper.</p>

Title: event when user check some checkbox

Body:
I want to make event when user check some checkbox.

I wrote the code below but nothing happened -

I added "alert", but it doesn't shown

HTML

        Status

<input type='checkbox' class='flat' name='statusID_Array[]' value='1'  /> Waiting for support to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='2'  /> Waiting for customer to reply

<input type='checkbox' class='flat' name='statusID_Array[]' value='3'  /> Solved

<input type='checkbox' class='flat' name='statusID_Array[]' value='4'  /> QA

<input type='checkbox' class='flat' name='statusID_Array[]' value='5'  /> Waiting for programmer to reply

Ticket Cause

JS


问:
Simple explanation of "Unified Modelling Language", why is it important?
i am new to asp.net and i was told that i need to know UML thoroughly to build successful software, is this correct? i mean cant i just "code and fix" and "model" in my brain. how important is UML and what is the best way to learn it?</p>

答:
i mean cant i just "code and fix" and
  "model" in my brain

You can.  It's done every day.  And a lot of what's going through it at the time, and how you convey your ideas on napkins is already a form of UML without its rigid nomenclature.

But if you're working with colleagues on big systems, there may be occasions were they speak the language.

ContentLicense: CC BY-SA 2.5


问:
Debug a crashing IE11
I have some Javascript code which makes IE11 to crash. How can I find out the offending code? (function name, line number, stack trace, whatever)

The only option I see is

debug with VS2015

but this goes to far telling me the hex offset in the DLL (mshtml.dll) where the exception was raised

that's the error report from VS2015:

Unhandled exception at 0x62E06A9C (mshtml.dll) in iexplore.exe:
  0xC0000005: Access violation reading location 0x00000028.

答:
The "solution" I found was to upgrade to the Javascript library responsible for the crash (D3, d3js.org). The crash simply dissappeared

But yes, IE11 still sucks big time

Title: Debug a crashing IE11


问:
What is SpringBootApplication functionality?
I understand that @SpringBootApplication is used to mark the main class of  a spring application.

Here I see that it "is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan". But why is there needed a @Configuration if it is already made automatically with  @EnableAutoConfiguration.

答: @EnableAutoConfiguration means Spring boot will look what libraries you use and try to set up beans accordingly. It has nothing to do with @Configuration.</p>


问:
I'm getting the time picker value in 24 hr format. How can I convert it to 12 hr format?
Code

```<code>    public static class TimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR);
            int minute = c.get(Calendar.MINUTE);
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
        }
        @Override
        public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
//            displayCurrentTime.setText(String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
            displayCurrentTime.setText(String.format("%02d:%02d %s", hourOfDay == 0 ? 12 : hourOfDay,
                    minute, hourOfDay < 12 ? "am" : "pm"));
        }
    }
</code>```

This is the code that I'm using to display the time from the time picker. But the time is being displayed in 24hr format because of is24HourFormat.
 How do I convert the same into 12hr format?

答:
You can do it by-</p>

```<code>Calendar mcurrentTime = Calendar.getInstance();
        int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
        int minute = mcurrentTime.get(Calendar.MINUTE);
        TimePickerDialog mTimePicker;
        mTimePicker = new TimePickerDialog(AddReminder.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                eReminderTime.setText( selectedHour + ":" + selectedMinute);
            }
        }, hour, minute, true);//Yes 24 hour time  //false if 12 hour
        mTimePicker.setTitle("Select Time");
        mTimePicker.show();

    }
});
</code>```

Body:
Code

    public static class TimePicker extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Calendar c = Calendar.getInstance();
            int hour = c.get(Calendar.HOUR);
            int minute = c.get(Calendar.MINUTE);
            return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
        }
        @Override
        public void onTimeSet(android.widget.TimePicker view, int hourOfDay, int minute) {
//            displayCurrentTime.setText(String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
            displayCurrentTime.setText(String.format("%02d:%02d %s", hourOfDay == 0 ? 12 : hourOfDay,
                    minute, hourOfDay < 12 ? "am" : "pm"));
        }
    }

This is the code that I'm using to display the time from the time picker. But the time is being displayed in 24hr format because of is24HourFormat.
 How do I convert the same into 12hr format?

Body:
You can do it by-

Calendar mcurrentTime = Calendar.getInstance();
        int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
        int minute = mcurrentTime.get(Calendar.MINUTE);
        TimePickerDialog mTimePicker;
        mTimePicker = new TimePickerDialog(AddReminder.this, new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                eReminderTime.setText( selectedHour + ":" + selectedMinute);
            }
        }, hour, minute, true);//Yes 24 hour time  //false if 12 hour
        mTimePicker.setTitle("Select Time");
        mTimePicker.show();

    }
});


问:
Could not compile dependency :mimerl when adding wallaby to my Elixir/Phoenix project
I'm new to Elixir/Phoenix and I'm now looking to write tests using Wallaby (or Hound, but it's the same issue).

For your information, I'm using a Docker image.

I'm trying to get Cabbage and Wallaby working, but as soon as I add Wallaby dependency to my project:

```<code>...
  defp deps do
    {:phoenix, "~> 1.3.0"},
    ...
    {:cowboy, "~> 1.0"},
    {:wallaby, "~> 0.19.2"}
  end
...
</code>```

then I have the following error when I run mix test:

```<code>escript: exception error: no match of right hand side value undefined
  in function  rebar_log:log/3 (/home/tristan/Devel/rebar3/_build/default/lib/rebar/src/rebar_log.erl, line 94)
  in call from rebar3:handle_error/1 (/home/tristan/Devel/rebar3/_build/default/lib/rebar/src/rebar3.erl, line 325)
  in call from escript:run/2 (escript.erl, line 759)
  in call from escript:start/1 (escript.erl, line 277)
  in call from init:start_em/1
  in call from init:do_boot/3
** (Mix) Could not compile dependency :mimerl, "/root/.mix/rebar3 bare compile --paths "/application/_build/test/lib/*/ebin"" command failed. You can recompile this dependency with "mix deps.compile mimerl", update it with "mix deps.update mimerl" or clean it with "mix deps.clean mimerl"
</code>```

Anyone who knows why do I have this error and how I could fix it?

答: You can add , only:  :test after the version of the dependency and try that and also run mix deps.get before run mix test

Body:
I'm new to Elixir/Phoenix and I'm now looking to write tests using Wallaby (or Hound, but it's the same issue).

For your information, I'm using a Docker image.

I'm trying to get Cabbage and Wallaby working, but as soon as I add Wallaby dependency to my project:

...
  defp deps do
    {:phoenix, "~> 1.3.0"},
    ...
    {:cowboy, "~> 1.0"},
    {:wallaby, "~> 0.19.2"}
  end
...

then I have the following error when I run mix test:

escript: exception error: no match of right hand side value undefined
  in function  rebar_log:log/3 (/home/tristan/Devel/rebar3/_build/default/lib/rebar/src/rebar_log.erl, line 94)
  in call from rebar3:handle_error/1 (/home/tristan/Devel/rebar3/_build/default/lib/rebar/src/rebar3.erl, line 325)
  in call from escript:run/2 (escript.erl, line 759)
  in call from escript:start/1 (escript.erl, line 277)
  in call from init:start_em/1
  in call from init:do_boot/3
** (Mix) Could not compile dependency :mimerl, "/root/.mix/rebar3 bare compile --paths "/application/_build/test/lib/*/ebin"" command failed. You can recompile this dependency with "mix deps.compile mimerl", update it with "mix deps.update mimerl" or clean it with "mix deps.clean mimerl"

Anyone who knows why do I have this error and how I could fix it?


问:
High Performance File I/O java API for file size of 300MB (max)
Building an Application, which is meant for only File I/O (could be pdf,jpg etc). Maximum file size can be 300MB. Application will be deployed on Linux 64 bit.
Tried the traditional blocking IO(FileOutputStream etc). But I am looking for Non-blocking or some better approach with good performance.

Here is the code that I am using right now.

```<code>FileOutputStream imageOutFile = new FileOutputStream("path/filename");
imageOutFile.write(byteArray);
imageOutFile.close();
</code>```

Please help me with better approach,code snippet for meeting this scenario.
Rest service will have input as filemetada and bytestream as input to my Service.

答:
I suggest using memory mapped files. We have used these for fast, shared read/write access to data set up to 40x main memory size.

You can use plan MappedByteBuffer from RandomAccessFile, or use a library like mine.

A low level file memory access

https://github.com/OpenHFT/Chronicle-Bytes/blob/master/src/test/java/net/openhft/chronicle/bytes/MappedMemoryTest.java

An append only queue/journal built on memory mapped files.
https://github.com/OpenHFT/Chronicle-Queue

A key/value store built on memory mapped files.
https://github.com/OpenHFT/Chronicle-Map

For reference the above code that I have used took around 75ms to write a 25Mb pdf file.

I assume you meant 25 MB (Megabytes) not Mb (Megabits) and that translates to 333 MB/s which is reasonable for a single desktop SSD. i.e. most likely the problem is you are working at the limit of what your disk sub-system can do.

BTW You can buy an NVMe drive which can do around to 2 GB/s for less than $1000.

Body:
Building an Application, which is meant for only File I/O (could be pdf,jpg etc). Maximum file size can be 300MB. Application will be deployed on Linux 64 bit.
Tried the traditional blocking IO(FileOutputStream etc). But I am looking for Non-blocking or some better approach with good performance.

Here is the code that I am using right now.

FileOutputStream imageOutFile = new FileOutputStream("path/filename");
imageOutFile.write(byteArray);
imageOutFile.close();

Please help me with better approach,code snippet for meeting this scenario.
Rest service will have input as filemetada and bytestream as input to my Service.


问:
What DOM events are available to WebKit on Android?
I'm building a mobile web app targeting Android users. I need to know what DOM events are available to me. I have been able to make the following work, but not terribly reliably:

click

mouseover

mousedown

mouseup

change

I have not been able to get the following to work:

keypress

keydown

keyup

Does anyone know the full list of what is supported and in what contexts (e.g., is onchange only available to form inputs?)? I can't find a reference for this on The Googles.

Thanks!

Update: I asked the same question on the Android developers list. I will be doing some more testing and will post my results both here and there.

答:
OK, this is interesting. My use case is that I have a series of links (A tags) on a screen in a WebKit view. To test what events area available, using jQuery 1.3.1, I attached every event listed on this page (even ones that don't make sense) to the links then used the up, down, and enter controls on the Android emulator and noted which events fired in which circumstances.

Here is the code I used to attach the events, with results to follow. Note, I'm using "live" event binding because for my application, the A tags are inserted dynamically.

```<code>$.each([
    'blur',
    'change',
    'click',
    'contextmenu',
    'copy',
    'cut',
    'dblclick',
    'error',
    'focus',
    'keydown',
    'keypress',
    'keyup',
    'mousedown',
    'mousemove',
    'mouseout',
    'mouseover',
    'mouseup',
    'mousewheel',
    'paste',
    'reset',
    'resize',
    'scroll',
    'select',
    'submit',

    // W3C events
    'DOMActivate',
    'DOMAttrModified',
    'DOMCharacterDataModified',
    'DOMFocusIn',
    'DOMFocusOut',
    'DOMMouseScroll',
    'DOMNodeInserted',
    'DOMNodeRemoved',
    'DOMSubtreeModified',
    'textInput',

    // Microsoft events
    'activate',
    'beforecopy',
    'beforecut',
    'beforepaste',
    'deactivate',
    'focusin',
    'focusout',
    'hashchange',
    'mouseenter',
    'mouseleave'
], function () {
    $('a').live(this, function (evt) {
        alert(evt.type);
    });
});
</code>```

Here's how it shook out:

On first page load with nothing highlighted (no ugly orange selection box around any item), using down button to select the first item, the following events fired (in order): mouseover, mouseenter, mousemove, DOMFocusIn

With an item selected, moving to the next item using the down button, the following events fired (in order): mouseout, mouseover, mousemove, DOMFocusOut, DOMFocusIn

With an item selected, clicking the "enter" button, the following events fired (in order): mousemove, mousedown, DOMFocusOut, mouseup, click, DOMActivate

This strikes me as a bunch of random garbage. And, who's that cheeky IE-only event (mouseenter) making a cameo, then taking the rest of the day off? Oh well, at least now I know what events to watch for.

It would be great if others want to take my test code and do a more thorough run through, perhaps using form elements, images, etc.

OwnerDisplayName: Andrew Hedges

LastEditorDisplayName: Andrew Hedges

Body:
OK, this is interesting. My use case is that I have a series of links (A tags) on a screen in a WebKit view. To test what events area available, using jQuery 1.3.1, I attached every event listed on this page (even ones that don't make sense) to the links then used the up, down, and enter controls on the Android emulator and noted which events fired in which circumstances.

Here is the code I used to attach the events, with results to follow. Note, I'm using "live" event binding because for my application, the A tags are inserted dynamically.

$.each([
    'blur',
    'change',
    'click',
    'contextmenu',
    'copy',
    'cut',
    'dblclick',
    'error',
    'focus',
    'keydown',
    'keypress',
    'keyup',
    'mousedown',
    'mousemove',
    'mouseout',
    'mouseover',
    'mouseup',
    'mousewheel',
    'paste',
    'reset',
    'resize',
    'scroll',
    'select',
    'submit',

    // W3C events
    'DOMActivate',
    'DOMAttrModified',
    'DOMCharacterDataModified',
    'DOMFocusIn',
    'DOMFocusOut',
    'DOMMouseScroll',
    'DOMNodeInserted',
    'DOMNodeRemoved',
    'DOMSubtreeModified',
    'textInput',

    // Microsoft events
    'activate',
    'beforecopy',
    'beforecut',
    'beforepaste',
    'deactivate',
    'focusin',
    'focusout',
    'hashchange',
    'mouseenter',
    'mouseleave'
], function () {
    $('a').live(this, function (evt) {
        alert(evt.type);
    });
});

Here's how it shook out:

On first page load with nothing highlighted (no ugly orange selection box around any item), using down button to select the first item, the following events fired (in order): mouseover, mouseenter, mousemove, DOMFocusIn

With an item selected, moving to the next item using the down button, the following events fired (in order): mouseout, mouseover, mousemove, DOMFocusOut, DOMFocusIn

With an item selected, clicking the "enter" button, the following events fired (in order): mousemove, mousedown, DOMFocusOut, mouseup, click, DOMActivate

This strikes me as a bunch of random garbage. And, who's that cheeky IE-only event (mouseenter) making a cameo, then taking the rest of the day off? Oh well, at least now I know what events to watch for.

It would be great if others want to take my test code and do a more thorough run through, perhaps using form elements, images, etc.


问:
Java InvocationHandler and a Singleton
I have a singleton object "MySingle" which all through my classes I retrevie as MySingle.createOrGetInstance();

Now the problem I am having is that I would like to do some Method Logging and other stuff before a method in MySingle is called, so I looked into the Java InvocationHandler class Source Link

However the problem is now how would I call the singleton method, because when I use the same code and instead of doing

```<code>DebugProxy.newInstance(new FooImpl());
</code>```

I do this

DebugProxy.newInstance(MySingle.createOrGetInstance()); But when I do this, I get a class Cast expression when I end up assigning the result to a variable `(MySingle sing).

Im developing on Android but I doubt that makes any difference :).

Thanks,
Faisal abid

答:
For android application debug is diff. calss which is implemented for specially for android

see this link

Title: Java InvocationHandler and a Singleton

Body:
I have a singleton object "MySingle" which all through my classes I retrevie as MySingle.createOrGetInstance();

Now the problem I am having is that I would like to do some Method Logging and other stuff before a method in MySingle is called, so I looked into the Java InvocationHandler class Source Link

However the problem is now how would I call the singleton method, because when I use the same code and instead of doing

DebugProxy.newInstance(new FooImpl());

I do this

DebugProxy.newInstance(MySingle.createOrGetInstance()); But when I do this, I get a class Cast expression when I end up assigning the result to a variable `(MySingle sing).

Im developing on Android but I doubt that makes any difference :).

Thanks,
Faisal abid


问:
Having a block of code wait to run at a certain time in iOS
Let's say I have a view controller with code that I want to execute at a certain time, say 2:00pm. What I want to happen is that if the user opens the view controller at 1:58pm, that the code will wait and continuously check the time, executing itself at exactly 2:00pm. Is there a way to do this in Swift 4, perhaps with a timer?</p>

答:
You can go around this way to achieve the result:

```<code> override func viewDidLoad() {
     super.viewDidLoad()
     let dateFormatter = DateFormatter()
     /*The accepted DateFormat*/
     dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
     /*My Date String to run the code at*/
     let dateString = "12-06-2017 15:41"
        let date = dateFormatter.date(from: dateString)

        /*Now find the time differnce from now*/
        let secondsFromNowToFinish = date?.timeIntervalSinceNow

        DispatchQueue.main.asyncAfter(deadline: .now() + secondsFromNowToFinish!, execute: {

            print ("Hello Future.")
        })

    }
</code>```

Tested and running.

References:

DateFormatter

Convert Date String to Date

Happy coding. Hope it helps. Please remove the forced unwrappings.

Body:
You can go around this way to achieve the result:

 override func viewDidLoad() {
     super.viewDidLoad()
     let dateFormatter = DateFormatter()
     /*The accepted DateFormat*/
     dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
     /*My Date String to run the code at*/
     let dateString = "12-06-2017 15:41"
        let date = dateFormatter.date(from: dateString)

        /*Now find the time differnce from now*/
        let secondsFromNowToFinish = date?.timeIntervalSinceNow

        DispatchQueue.main.asyncAfter(deadline: .now() + secondsFromNowToFinish!, execute: {

            print ("Hello Future.")
        })

    }

Tested and running.

References:

DateFormatter

Convert Date String to Date

Happy coding. Hope it helps. Please remove the forced unwrappings.


问:
How to add an android studio project to another android studio project?
I want to add an android studio project to my existing android studio project but when i try to import another module from file->import module then i get an error saying the app module already exists. </p>

答:
You need to change your module name while i porting old project to new one
as shown in image


问:
Is getIfPresent considered as a get operation for expireAfterAccess?
Does the getIfPresent function reset the time for expireAfterAccess?

答:
The CacheBuilder.expireAfterAccess() docs say:

Access time is reset by all cache read and write operations

Since Cache.getIfPresent() is a cache read, it resets the access time.


答:
Try this:

.inner{
  height: 300px;
  width: 200px;
  background-color: red;
  border-radius: 10px;
}

.outer{
  padding: 10px;
  background-color: green;
  display: inline-block;
  border-radius: 20px;
  position: relative;
  margin-left: 100px;
}

.arrow{
 position: absolute;
 top: 30px;
 left: -50px;
 border: 25px solid transparent;
 border-right: 25px solid green;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outer">
  <div class="inner"></div>
  <div class='arrow'>
</div></code>```

Title: make CSS corner style

Body:
I am confused, how to make the design of display options like this with css :

how to make corner style like this picture ... please help me. thanks

Body:
Try this:

.inner{
  height: 300px;
  width: 200px;
  background-color: red;
  border-radius: 10px;
}

.outer{
  padding: 10px;
  background-color: green;
  display: inline-block;
  border-radius: 20px;
  position: relative;
  margin-left: 100px;
}

.arrow{
 position: absolute;
 top: 30px;
 left: -50px;
 border: 25px solid transparent;
 border-right: 25px solid green;
}

<div class="outer">
  <div class="inner"></div>
  <div class='arrow'>
</div>


问:
Does Spark support true column scans over parquet files in S3?
One of the great benefits of the Parquet data storage format is that it's columnar.  If I've got a 'wide' dataset with hundreds of columns, but my query only touches a few of those, then it's possible read only the data that stores those few columns, and skip the rest.

Presumably this feature works by reading a bit of metadata at the head of a parquet file that indicates the locations on the filesystem for each column.  The reader can then seek on disk to read in only the necessary columns.

Does anyone know whether spark's default parquet reader correctly implements this kind of selective seeking on S3?  I think it's supported by S3, but there's a big difference between theoretical support and an implementation that properly exploits that support.

答:
This needs to be broken down

Does the Parquet code get the predicates from spark (yes)

Does parquet then attempt to selectively read only those columns, using the Hadoop FileSystem seek() + read() or readFully(position, buffer, length) calls? Yes

Does the S3 connector translate these File Operations into efficient HTTP GET requests? In Amazon EMR: Yes. In Apache Hadoop, you need hadoop 2.8 on the classpath and set the properly spark.hadoop.fs.s3a.experimental.fadvise=random to trigger random access.

Hadoop 2.7 and earlier handle the aggressive seek() round the file badly, because they always initiate a GET offset-end-of-file, get surprised by the next seek, have to abort that connection, reopen a new TCP/HTTPS 1.1 connection (slow, CPU heavy), do it again, repeatedly. The random IO operation hurts on bulk loading of things like .csv.gz, but is critical to getting ORC/Parquet perf.

You don't get the speedup on Hadoop 2.7's hadoop-aws JAR. If you need it you need to update hadoop*.jar and dependencies, or build Spark up from scratch against Hadoop 2.8

Note that Hadoop 2.8+ also has a nice little feature: if you call toString() on an S3A filesystem client in a log statement, it prints out all the filesystem IO stats, including how much data was discarded in seeks, aborted TCP connections &c. Helps you work out what's going on.

2018-04-13 warning:: Do not try to drop the Hadoop 2.8+ hadoop-aws JAR on the classpath along with the rest of the hadoop-2.7 JAR set and expect to see any speedup. All you will see are stack traces. You need to update all the hadoop JARs and their transitive dependencies.


问:
CSS: cant use alpha filter
I am want transparency a screen and show the screen behind

my css:

```<code>.correct-answer {
  background-color: #98CB66;
  filter: alpha(opacity=60);
  z-index: 10;
  opacity: 0.7;
  height: 100%;
  width: 100%;
}
</code>```

i tried use alpha filter in css,
and its not working

答:
Try Below CSS Snipet :</p>

```<code>.yourselector {
background:#000;
opacity: .75; /* standard: ff gt 1.5, opera, safari */
-ms-filter: “alpha(opacity=75)”; /* ie 8 */
filter: alpha(opacity=75); /* ie lt 7 */
-khtml-opacity: .75; /* safari 1.x */
-moz-opacity: .75; /* ff lt 1.5, netscape */
}
</code>```

Title: CSS: cant use alpha filter

Body:
I am want transparency a screen and show the screen behind

my css:

.correct-answer {
  background-color: #98CB66;
  filter: alpha(opacity=60);
  z-index: 10;
  opacity: 0.7;
  height: 100%;
  width: 100%;
}

i tried use alpha filter in css,
and its not working

Body:
Try Below CSS Snipet :

.yourselector {
background:#000;
opacity: .75; /* standard: ff gt 1.5, opera, safari */
-ms-filter: “alpha(opacity=75)”; /* ie 8 */
filter: alpha(opacity=75); /* ie lt 7 */
-khtml-opacity: .75; /* safari 1.x */
-moz-opacity: .75; /* ff lt 1.5, netscape */
}


问:
Oracle PL/SQL return array of rows
Dear Oracle Developers,

I have searched and googled to find a solution for my problem but nothing helped me.

Situation :

TABLE : CUSTOMER(....);

My problem is : I want to create a stored procedure say get_customers to return an array of customer rows. I have no idea how to get this working.

I tried to create a type customer_rec and using a cursor to retrieve no more than maxRows

```<code>create or replace procedure get_customers(maxRows IN NUMBER, ??? OUT ????)
</code>```

How to define the OUT parameter ?

How to retrieve the rows in the array using a cursor ?

Thanks a lot

答: You can, using the SYS_REFCURSOR on your function output.

Title: Oracle PL/SQL return array of rows

Body:
Dear Oracle Developers,

I have searched and googled to find a solution for my problem but nothing helped me.

Situation :

TABLE : CUSTOMER(....);

My problem is : I want to create a stored procedure say get_customers to return an array of customer rows. I have no idea how to get this working.

I tried to create a type customer_rec and using a cursor to retrieve no more than maxRows

create or replace procedure get_customers(maxRows IN NUMBER, ??? OUT ????)

How to define the OUT parameter ?

How to retrieve the rows in the array using a cursor ?

Thanks a lot


问:
Why i cant join string with first value of dictionary?
I would like to ask that why cant i join the string with the first value of the dictionary?

```<code>Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat", 0},
    {"dog", 1},
    {"llama", 2},
    {"iguana", 3}
};

string z = string.Join("Test_", d.Select(x => x.Value + "\n"));
</code>```

These are the value of Z now

```<code>0
Test_1
Test_2
Test_3
</code>```

答:
Please read String.Join documentation first.

You need use String.Concat, instead of String.Join.

Differences:

String.Concat just union collection of strings to the final string. E.g. String.Concat(new []{"1", "2", "3"}) returns "123"

String.Join additionally adds separator between items. So, String.Join(", ", new []{"1", "2", "3"}) returns "1, 2, 3".

So, you asked to use "Test_" as separator. Of course, separator does not added before the first argument. To add it, please use string.Concat(d.Select(x => "Test_" + x.Value + "\n"));

Body:
I would like to ask that why cant i join the string with the first value of the dictionary?

Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat", 0},
    {"dog", 1},
    {"llama", 2},
    {"iguana", 3}
};

string z = string.Join("Test_", d.Select(x => x.Value + "\n"));

These are the value of Z now

0
Test_1
Test_2
Test_3


问:
How to bypass socket?
I have installed a streaming server "Lighttpd" (light-tpd) which runs on port 81.

I have a C program that listens to http requests on port 80 using a server socket created by socket api.

I want that as soon as I get a request on the port 80 from a client I forward that to the streaming server and the remaining conversation takes place b/w the Streaming Server and client & they bypass my C program completely.

The problem is client would be expecting msgs from socket at port 80 (i.e from the socket of my C program) since it had sent request to port 80 only rather than from the Streaming server which gives service on port 81.
can anyone help me out on this issue of bypassing the socket on port 80 for replying to the client.

Solution I think: my program can be a middle man...It will forward the request to port 81 of streaming server and when it get replies from there it forwards them to the client...but bypassing would be efficient and I don't know how to do that. Please help me out.

Thanks in advance

答:
I have recently implemented a similar technique where a single program accepts a TCP connection and then 'passes' that connection to another component and plays no further part in the socket conversation.  It uses the technique of passing the file descriptor of the accepted socket over a UNIX socket to the server component which effectively does an inter-process dup() of the fd.

See here and here.

This works for me as I have control of both ends of the UNIX socket on the server-side, but to work for you, you'd need:

A UNIX socket between your dispatching component and server components.

Full control of the server component.

You might need to hack away at the lighttpd source code...

Sorry, not really an proper answer...

Title: How to bypass socket?


问:
How to remove space (margin/padding) of ion-row and ion-col in ionic?
Here is my code:

```<code><ion-content padding text-center>
    <img src="../assets/img/logo.png" width="200" class="logo" />

</ion-content>
<ion-footer>
    <ion-row no-padding>
        <ion-col col-6 align-self-stretch>
            <button ion-button full>Button</button>
        </ion-col>
        <ion-col col-6 align-self-stretch>
            <button ion-button full>Button</button>
        </ion-col>
    </ion-row>
</ion-footer>
</code>```

I need to remove those paddings/margin for ion-row and ion-col. I tried googling but i got no luck. I am also newbie in Ionic. TIA!

Here is the screenshot:

I need to achieve this:

答:
You need to set the no-padding attribute on ion-col instead of ion-row and no-margin for the buttons.

```<code><ion-row>
    <ion-col col-6 no-padding>
        <button ion-button full no-margin>Button</button>
    </ion-col>
    <ion-col col-6 no-padding>
        <button ion-button full no-margin>Button</button>
    </ion-col>
</ion-row>
</code>```

Body:
Here is my code:

<ion-content padding text-center>

</ion-content>
<ion-footer>
    <ion-row no-padding>
        <ion-col col-6 align-self-stretch>
            <button ion-button full>Button</button>
        </ion-col>
        <ion-col col-6 align-self-stretch>
            <button ion-button full>Button</button>
        </ion-col>
    </ion-row>
</ion-footer>

I need to remove those paddings/margin for ion-row and ion-col. I tried googling but i got no luck. I am also newbie in Ionic. TIA!

Here is the screenshot:

I need to achieve this:

Body:
You need to set the no-padding attribute on ion-col instead of ion-row and no-margin for the buttons.

<ion-row>
    <ion-col col-6 no-padding>
        <button ion-button full no-margin>Button</button>
    </ion-col>
    <ion-col col-6 no-padding>
        <button ion-button full no-margin>Button</button>
    </ion-col>
</ion-row>


问:
How could i overwrite css typehead js
I would like to overwrite typehead js input form search. Because actually my input is not taking all the place from my column div.

As you can see :

I would like to have the full bar like this ( i can do this when i change the input name but the search don't work after the change):

Here the full code : (hope someone could help me :) )

```<code> <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Recherche</div>
                    <div class="panel-body">

                        <form class="typeahead" role="search">
                            <div class="form-group">
                                <input type="search" name="q" class="typeahead form-control" placeholder="Search" autocomplete="off">
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins  and Typeahead) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!-- Typeahead.js Bundle -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>
<!-- Typeahead Initialization -->
<script>
    jQuery(document).ready(function($) {
        // Set the Options for "Bloodhound" suggestion engine
        var engine = new Bloodhound({
            remote: {
                url: 'find?q=%QUERY%',
                wildcard: '%QUERY%'
            },
            datumTokenizer: Bloodhound.tokenizers.whitespace('q'),
            queryTokenizer: Bloodhound.tokenizers.whitespace
        });

        $(".typeahead").typeahead({
            hint: true,
            highlight: true,
            minLength: 1
        }, {
            source: engine.ttAdapter(),

            // This will be appended to "tt-dataset-" to form the class name of the suggestion menu.
            name: 'usersList',

            // the key from the array we want to display (name,id,email,etc...)
            templates: {
                empty: [
                    '<div class="list-group search-results-dropdown"><div class="list-group-item">Nothing found.</div></div>'
                ],
                header: [
                    '<div class="list-group search-results-dropdown">'
                ],
                suggestion: function (data) {
                    return '<a href="user/' + data.id + '" class="list-group-item">' + data.name + ' - ' + data.email + '</a>'
                }
            }
        });
    });
</script>
</code>```

答:
Try this,

```<code><style>
    .twitter-typeahead, .tt-hint, .tt-input, .tt-menu { width: 100%; }
</style>
</code>```

Put this style tag in your the  tag.

Title: How could i overwrite css typehead js

Body:
I would like to overwrite typehead js input form search. Because actually my input is not taking all the place from my column div.

As you can see :

I would like to have the full bar like this ( i can do this when i change the input name but the search don't work after the change):

Here the full code : (hope someone could help me :) )

Recherche

                        <form class="typeahead" role="search">

                                <input type="search" name="q" class="typeahead form-control" placeholder="Search" autocomplete="off">

                        </form>

Body:
Try this,

<style>
    .twitter-typeahead, .tt-hint, .tt-input, .tt-menu { width: 100%; }
</style>

Put this style tag in your the <head> tag.


问:
rolling up groups in a matrix
Here is the data I have, I use proc tabulate to present it how it is presented in excel, and to make the visualization easier. The goal is to make sure groups strictly below the diagonal (i know it's a rectangle, the (1,1) (2,2)...(7,7) "diagonal") to roll up the column until it hits the diagonal or makes a group size of at least 75.

```<code>      1   2   3    4    5    6   7  (month variable)
(age)
  1  80  90  100  110  122  141 88
  2  80  90  100  110   56   14 88
  3  80  90   87   45   12   41 88
  4  24  90  100  110   22  141 88
  5  0   1    0    0    0    0   2
  6  0   1    0    0    0    0   6
  7  0   1    0    0    0    0   2
  8  0   1    0    0    0    0  11
</code>```

Ive already used if/thens to regroup certain data values, but I need a general way to do it for other sets.
Thanks in advance

desired results

```<code>   1  2   3    4    5    6   7  (month variable)
(age)
  1  80  90  100  110  122  141 88
  2  80  90  100  110   56   14 88
  3  104 90   87   45   12   41 88
  4  0   94  100  110   22  141 88
  5  0   0    0    0    0    0   2
  6  0   0    0    0    0    0   6
  7  0   0    0    0    0    0   13
  8  0   0    0    0    0    0   0
</code>```

答:
Mock up some categorical data for some patients who have to be counted

```<code>data mock;
  do patient_id = 1 to 2500;
    month = ceil(7*ranuni(123));
    age = ceil(8*ranuni(123));
    output;
  end;
  stop;
run;
</code>```

Create a tabulation of counts (N) similar to the one shown in the question:

```<code>options missing='0';

proc tabulate data=mock;
  class month age;
  table age,month*n=''/nocellmerge;
run;
</code>```

For each month get the sub-diagonal patient count

```<code>proc sql;
/*  create table subdiagonal_column as */
  select month, count(*) as subdiag_col_freq
  from mock
  where age > month
  group by month;
</code>```

For each row get the pre-diagonal patient count

```<code>/*  create table prediagonal_row as */
  select age, count(*) as prediag_row_freq
  from mock
  where age > month
  group by age;
</code>```

other sets can be tricky if the categorical values are not +1 monotonic.  To do a similar process for non-montonic categorical values you will need to create surrogate variables that are +1 monotonic.  For example:

```<code>data mock;
  do item_id = 1 to 2500;
    pet = scan ('cat dog snake rabbit hamster', ceil(5*ranuni(123)));
    place = scan ('farm home condo apt tower wild', ceil(6*ranuni(123)));
    output;
  end;
run;

proc tabulate data=mock;
  class pet place;
  table pet,place*n=''/nocellmerge;
run;

proc sql;
  create table unq_pets as select distinct pet from mock;
  create table unq_places as select distinct place from mock;

data pets;
  set unq_pets;
  pet_num = _n_;
run;

data places;
  set unq_places;
  place_num = _n_;
run;

proc sql;
  select distinct place_num, mock.place, count(*) as subdiag_col_freq
  from mock
  join pets on pets.pet = mock.pet
  join places on places.place = mock.place
  where pet_num > place_num
  group by place_num
  order by place_num
  ;
</code>```

Title: rolling up groups in a matrix

Body:
Here is the data I have, I use proc tabulate to present it how it is presented in excel, and to make the visualization easier. The goal is to make sure groups strictly below the diagonal (i know it's a rectangle, the (1,1) (2,2)...(7,7) "diagonal") to roll up the column until it hits the diagonal or makes a group size of at least 75.

      1   2   3    4    5    6   7  (month variable)
(age)
  1  80  90  100  110  122  141 88
  2  80  90  100  110   56   14 88
  3  80  90   87   45   12   41 88
  4  24  90  100  110   22  141 88
  5  0   1    0    0    0    0   2
  6  0   1    0    0    0    0   6
  7  0   1    0    0    0    0   2
  8  0   1    0    0    0    0  11

Ive already used if/thens to regroup certain data values, but I need a general way to do it for other sets.
Thanks in advance

desired results

   1  2   3    4    5    6   7  (month variable)
(age)
  1  80  90  100  110  122  141 88
  2  80  90  100  110   56   14 88
  3  104 90   87   45   12   41 88
  4  0   94  100  110   22  141 88
  5  0   0    0    0    0    0   2
  6  0   0    0    0    0    0   6
  7  0   0    0    0    0    0   13
  8  0   0    0    0    0    0   0

Body:
Mock up some categorical data for some patients who have to be counted

data mock;
  do patient_id = 1 to 2500;
    month = ceil(7*ranuni(123));
    age = ceil(8*ranuni(123));
    output;
  end;
  stop;
run;

Create a tabulation of counts (N) similar to the one shown in the question:

options missing='0';

proc tabulate data=mock;
  class month age;
  table age,month*n=''/nocellmerge;
run;

For each month get the sub-diagonal patient count

proc sql;
/*  create table subdiagonal_column as */
  select month, count(*) as subdiag_col_freq
  from mock
  where age > month
  group by month;

For each row get the pre-diagonal patient count

/*  create table prediagonal_row as */
  select age, count(*) as prediag_row_freq
  from mock
  where age > month
  group by age;

other sets can be tricky if the categorical values are not +1 monotonic.  To do a similar process for non-montonic categorical values you will need to create surrogate variables that are +1 monotonic.  For example:

data mock;
  do item_id = 1 to 2500;
    pet = scan ('cat dog snake rabbit hamster', ceil(5*ranuni(123)));
    place = scan ('farm home condo apt tower wild', ceil(6*ranuni(123)));
    output;
  end;
run;

proc tabulate data=mock;
  class pet place;
  table pet,place*n=''/nocellmerge;
run;

proc sql;
  create table unq_pets as select distinct pet from mock;
  create table unq_places as select distinct place from mock;

data pets;
  set unq_pets;
  pet_num = _n_;
run;

data places;
  set unq_places;
  place_num = _n_;
run;

proc sql;
  select distinct place_num, mock.place, count(*) as subdiag_col_freq
  from mock
  join pets on pets.pet = mock.pet
  join places on places.place = mock.place
  where pet_num > place_num
  group by place_num
  order by place_num
  ;


问:
Which of these is the more correct implementation of INotifyPropertyChanged?
I've wondered often about this: Which of the following two implementations of INotifyPropertyChanged for any property Foo is the better, or even more correct one?

```<code>/* version A: */                      |     /* version B: */
private bool foo;                     |     private bool foo;
public bool Foo                       |     public bool Foo
{                                     |     {
   set                                |        set
   {                                  |        {
                                      |           if (value != foo)
                                      |           {
      foo = value;                    |              foo = value;
      OnPropertyChanged("Foo");       |              OnPropertyChanged("Foo");
                                      |           }
    }                                 |        }
}                                     |     }
</code>```

(I've omitted everything that is not relevant for this question.)

I suspect it should be version B on the right, as it prevents unnecessary events from being triggered. However, are there situations where these very same, missed events could lead to problems?

答:
Version B looks more correct as it doesn't raise the event if the property hasn't actually changed value. There won't be any problems with Version A, it's just an unnecessary call which won't update any of the UI.

And as the documentation states:

Notifies clients that a property value
  has changed.

Body:
I've wondered often about this: Which of the following two implementations of INotifyPropertyChanged for any property Foo is the better, or even more correct one?

/* version A: */                      |     /* version B: */
private bool foo;                     |     private bool foo;
public bool Foo                       |     public bool Foo
{                                     |     {
   set                                |        set
   {                                  |        {
                                      |           if (value != foo)
                                      |           {
      foo = value;                    |              foo = value;
      OnPropertyChanged("Foo");       |              OnPropertyChanged("Foo");
                                      |           }
    }                                 |        }
}                                     |     }

(I've omitted everything that is not relevant for this question.)

I suspect it should be version B on the right, as it prevents unnecessary events from being triggered. However, are there situations where these very same, missed events could lead to problems?


问:
Unable to publish LUIS App
We are unable to publish the LUIS application. Publish button was disabled. Please find the attached screenshot and suggest on this please.

答:
This bug has been around for a while now. Advice from Microsoft support was to:

delete all cookies for luis.ai

sign out of the session

then sign back
in

When you sign in again the publish to production button should be enabled again

Title: Unable to publish LUIS App


问:
Robotframework How to uploadfile to the website with RIDE
This is my code

```<code>*** Settings ***
Library           Selenium2Library

*** Variables ***
${Login}          xpath=/html/body/app/main/login/div/div[1]/div/form/div[3]/div/button

*** Test Cases ***
Test
    OPEN
    LOGIN
    Sleep    5s
    ADD TOPIC
    Sleep    2s
    SelectType
    TypePDF
    Sleep    5s
    AddFile

*** Keywords ***
OPEN
    Open Browser    https://********** \ \ \    googlechrome

LOGIN

Input Text    id=inputEmail3    ********

Input Text    id=inputPassword3  *******

 Click Element    xpath=/html/body/app/main/login/div/div[1]/div/form/div[3]/div/button

ADD TOPIC
    Click Element    xpath=/html/body/app/main/pages/div/div/news/div/news-list/button

SelectType
    Click Element    id=selectType

TypePDF
    Click Element    xpath=//*[@id="selectType"]/option[5]

AddFile
    Click Button    xpath=/html/body/app/main/pages/div/div/news/div/news-add/ba-card/div/div[2]/div[2]/div[1]/div[2]/ba-file-uploader/div/span/button
    Sleep    2s
    Choose File    <input type="file" id="myFile">    C:{/}User${/}pr.com${/}Download${/}base.png

Addpicture

Choose File    //input[@type='file']    C:\Users\pr.com\Downloads\b.jpg
</code>```

This is the result

```<code>Test
| FAIL |
File 'C:{/}User\pr.com\Download\base.png' does not exist on the local file system
</code>```

I use:

```<code>Python version 2.7.14
Robotframework ride  1.5.2.1
</code>```

答:
From the document

http://robotframework.org/robotframework/latest/libraries/OperatingSystem.html

Because Robot Framework uses the backslash ('\') as an escape character in the test data, using a literal backslash requires duplicating it like in r'c:\path\file.txt. '

So use "\" double slash when u r providing path to file

if it still does not work , then check if the path you provide exists or not

```<code>*** Settings ***
Library    Selenium2Library
Library    OperatingSystem

*** Test Cases ***
Test
    Open Browser and login
*** Keywords ***
Open Browser and login
    File Should Exist    C:\\Users\\pr.com\\Downloads\\b.jpg
</code>```

Body:
This is my code

*** Settings ***
Library           Selenium2Library

*** Variables ***
${Login}          xpath=/html/body/app/main/login/div/div[1]/div/form/div[3]/div/button

*** Test Cases ***
Test
    OPEN
    LOGIN
    Sleep    5s
    ADD TOPIC
    Sleep    2s
    SelectType
    TypePDF
    Sleep    5s
    AddFile

*** Keywords ***
OPEN
    Open Browser    https://********** \ \ \    googlechrome

LOGIN

Input Text    id=inputEmail3    ********

Input Text    id=inputPassword3  *******

 Click Element    xpath=/html/body/app/main/login/div/div[1]/div/form/div[3]/div/button

ADD TOPIC
    Click Element    xpath=/html/body/app/main/pages/div/div/news/div/news-list/button

SelectType
    Click Element    id=selectType

TypePDF
    Click Element    xpath=//*[@id="selectType"]/option[5]

AddFile
    Click Button    xpath=/html/body/app/main/pages/div/div/news/div/news-add/ba-card/div/div[2]/div[2]/div[1]/div[2]/ba-file-uploader/div/span/button
    Sleep    2s
    Choose File    <input type="file" id="myFile">    C:{/}User${/}pr.com${/}Download${/}base.png

Addpicture

Choose File    //input[@type='file']    C:\Users\pr.com\Downloads\b.jpg

This is the result

Test
| FAIL |
File 'C:{/}User\pr.com\Download\base.png' does not exist on the local file system

I use:

Python version 2.7.14
Robotframework ride  1.5.2.1

Body:
From the document

http://robotframework.org/robotframework/latest/libraries/OperatingSystem.html

Because Robot Framework uses the backslash ('\') as an escape character in the test data, using a literal backslash requires duplicating it like in r'c:\path\file.txt. '

So use "\" double slash when u r providing path to file

if it still does not work , then check if the path you provide exists or not

*** Settings ***
Library    Selenium2Library
Library    OperatingSystem

*** Test Cases ***
Test
    Open Browser and login
*** Keywords ***
Open Browser and login
    File Should Exist    C:\\Users\\pr.com\\Downloads\\b.jpg