问:
I tried to fetch the date from textfield,but i got only year(2017) fetched
I tried to fetch the date from the textfield by using mysql and i got only year(2017) fetched
This is my query:

```<code>theQuery("insert into Files11(FileName,Date,Coding,Demo,Audit,Lop,Denials,Cs,Comments,Percentage) values('"+JT_FileName.getText()+"','"+JT_Date1.getText()+"','"+Coding.getText()+"','"+Demo.getText()+"','"+Audit.getText()+"','"+Lop.getText()+"','"+Denials.getText()+"','"+Cs.getText()+"','"+Comments.getText()+"','"+Percentage.getText()+"')");
</code>```

Previously I have fetched the complete date by using this Query:

```<code>theQuery("insert into Files5(FileName,LinesCount,UserId,Date) values('"+JT_FileName.getText()+"','"+JT_LinesCount.getText()+"','"+text.getText()+"','"+JT_Date1.getText()+"')");
</code>```

For Fetching:
I have used this query

```<code>String sql = "SELECT * FROM Files11";
</code>```

Can anyone please help me,What i am missing here?
This is my whole Source Code:

```<code>import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;
import java.io.*;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import net.sourceforge.jdatepicker.impl.JDatePanelImpl;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import net.sourceforge.jdatepicker.impl.UtilDateModel;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;

public class NewProjectRCM2 extends JFrame implements ActionListener{
 JLabel JL_Filechooser,JL_FileName,JL_Coding,JL_Date,JL_From,JL_To,JL_Demo,JL_Audit,JL_Lop,JL_Denials,JL_Cs,JL_Comments,JL_Target,JL_Percentage;
 JTextField JT_Filechooser,JT_FileName,JT_Coding,JT_Date1,JT_Demo,JT_Audit,JT_Lop,JT_Denials,JT_Cs,JT_Comments,JT_Target,JT_Percentage;
 JButton btn_update,openfile,btn_refresh,btn_calculate;

    JLabel l1=new JLabel("Username:");

    JButton b = new JButton("Login");

    JTextField text = new JTextField(20);

    JTextField Coding,Demo,Audit,Lop,Denials,Cs,Comments,Percentage;

 public NewProjectRCM2(){
     super("USER_ID");
     JL_Filechooser = new JLabel("File chooser:");
     JL_FileName = new JLabel("File Name:");
     JL_Date = new JLabel("Date:");
     JL_From = new JLabel("From:");
     JL_To = new JLabel("To:");
     JL_Coding = new JLabel("Coding:");
     JL_Demo = new JLabel("Demo:");
     JL_Audit = new JLabel("Audit:");
     JL_Lop = new JLabel("Lop:");
     JL_Denials = new JLabel("Denials:");
     JL_Cs = new JLabel("Cs:");
     JL_Comments = new JLabel("Comments:");

     JL_Target=new JLabel("Target:");

     JL_Percentage=new JLabel("Percentage:");

     l1.setBounds(20,20, 80,30);
     b.setBounds(100,120, 80,30);
     text.setText(System.getProperty("user.name")); text.setBounds(100, 20, 100, 30);
     text.setEnabled(false);
     text.setFont(new Font("Tahoma", Font.BOLD,25));
     text.setBackground(Color.GRAY);

     JL_Filechooser.setBounds(20, 20, 100, 20);
     JL_FileName.setBounds(20, 50, 100, 20);
     JL_Date.setBounds(20,90, 100, 20);
     JL_From.setBounds(20, 133, 100, 20);
     JL_To.setBounds(250, 133, 100, 20);

     JL_Coding.setBounds(20,180, 100, 20);
     JL_Demo.setBounds(20, 210, 100, 20);
     JL_Audit.setBounds(20, 240, 100, 20);
     JL_Lop.setBounds(20, 270, 100, 20);
     JL_Denials.setBounds(20, 300, 100, 20);
     JL_Cs.setBounds(20, 330, 100, 20);
     JL_Comments.setBounds(20, 360, 100, 20);

     JL_Target.setBounds(250, 180, 100, 20);
     JL_Percentage.setBounds(175,410, 100, 20);

     DefaultTableModel model = new DefaultTableModel();
     JTable jtb = new JTable();//tableadded
     JScrollPane sp=new JScrollPane(jtb);    //tableadded
     sp.setBounds(20, 450, 1000, 200);//tableadded

     JT_Filechooser = new JTextField(20);
     JT_FileName = new JTextField(20);
     JT_Date1 = new JTextField(20);
     Coding = new JTextField(20);
     Demo = new JTextField(20);
     Audit = new JTextField(20);
     Lop = new JTextField(20);
     Denials = new JTextField(20);
     Cs = new JTextField(20);
     Comments = new JTextField(20);

     JT_Target = new JTextField(20);
     int Target1=100;
     JT_Target.setText(Integer.toString(Target1));
     Percentage = new JTextField(20);

     JT_Date1.setText(String.valueOf(java.time.LocalDate.now()));
     text.setBounds(100, 20, 100, 30);
     JT_Date1.setEnabled(false);
     JT_Date1.setFont(new Font("Tahoma", Font.BOLD, 15));
     JT_Date1.setBackground(Color.GRAY);

    Calendar cal = Calendar.getInstance();
     SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
     text.setBounds(100, 20, 100, 30);

     JT_Filechooser.setBounds(130,20,150,20);
     JT_FileName.setBounds(130,50,150, 20);
     JT_Date1.setBounds(130,90, 150, 20);
     Coding.setBounds(130,180, 75, 20);
     Demo.setBounds(130,210,75, 20);
     Audit.setBounds(130,240,75, 20);
     Lop.setBounds(130,270, 75, 20);
     Denials.setBounds(130,300, 75, 20);
     Cs.setBounds(130,330, 75, 20);
     Comments.setBounds(130,360,75, 20);

     JT_Target.setBounds(350, 180,75, 20);

     Percentage.setBounds(250,410, 100, 20);

     btn_update = new JButton("UPDATE");
     btn_update.setBounds(270,300,80, 20);
     btn_refresh = new JButton("Refresh");
     btn_refresh.setBounds(480,132, 80, 20);
     btn_calculate = new JButton("RESULT");
     btn_calculate.setBounds(270,360, 80, 20);

     openfile = new JButton("openfile");
     openfile.setBounds(300, 20, 80, 20);
     openfile.addActionListener(this);

     /* UtilDateModel model1 = new UtilDateModel();
     JDatePanelImpl datePanel = new JDatePanelImpl(model1);
     JDatePickerImpl datePicker = new JDatePickerImpl(datePanel,new DateLabelFormatter());
     datePicker.setBounds(130, 110, 180, 30); */

     UtilDateModel model2 = new UtilDateModel();
     JDatePanelImpl datePanel2 = new JDatePanelImpl(model2);
     JDatePickerImpl datePicker1 = new JDatePickerImpl(datePanel2,new DateLabelFormatter());
     datePicker1.setBounds(60, 133, 180, 20);

     UtilDateModel model3 = new UtilDateModel();
     JDatePanelImpl datePanel3 = new JDatePanelImpl(model3);
     JDatePickerImpl datePicker2 = new JDatePickerImpl(datePanel3,new DateLabelFormatter());
     datePicker2.setBounds(273, 133, 180, 20);

     setLayout(null);
     add(JL_Filechooser);
     add(JL_FileName);
    // add(datePicker);
     add(datePicker1);
     add(datePicker2);
     add(JL_Date);
     add(JL_From);
     add(JL_To);
     add(JL_Coding);
     add(JL_Demo);
     add(JL_Audit);
     add(JL_Lop);
     add(JL_Denials);
     add(JL_Cs);
     add(JL_Comments);

     add(JL_Target);
     add(JL_Percentage);

     add(JT_Filechooser);
     add(JT_FileName);
     add(JT_Date1);
     add(Coding);
     add(Demo);
     add(Audit);
     add(Lop);
     add(Denials);
     add(Cs);
     add(Comments);

     add(JT_Target);
     add(Percentage);

     add(btn_update);
     add(btn_refresh);
     add(btn_calculate);

     add(l1);
     add(b);
     add(text);
     add(openfile);
     add(sp);

     JL_Filechooser.setVisible(false);
     JL_FileName.setVisible(false);
     JL_Date.setVisible(false);
     JL_Coding.setVisible(false);
     JL_From.setVisible(false);
     JL_To.setVisible(false);
     JL_Demo.setVisible(false);
     JL_Audit.setVisible(false);
     JL_Lop.setVisible(false);
     JL_Denials.setVisible(false);
     JL_Cs.setVisible(false);
     JL_Comments.setVisible(false);

     JL_Target.setVisible(false);
     JL_Percentage.setVisible(false);

    // datePicker.setVisible(false);
     datePicker1.setVisible(false);
     datePicker2.setVisible(false);

     JT_Filechooser.setEnabled(false);
     JT_Filechooser.setFont(new Font("Tahoma", Font.BOLD, 15));

     JT_Filechooser.setVisible(false);
     JT_FileName.setVisible(false);
     JT_Date1.setVisible(false);
     Coding.setVisible(false);
     Demo.setVisible(false);
     Audit.setVisible(false);
     Lop.setVisible(false);
     Denials.setVisible(false);
     Cs.setVisible(false);
     Comments.setVisible(false);

     JT_Target.setVisible(false);
     Percentage.setVisible(false);

     btn_update.setVisible(false);
     btn_refresh.setVisible(false);
     btn_calculate.setVisible(false);
     openfile.setVisible(false);
     sp.setVisible(false);

   //button update
    btn_update.addActionListener(new  ActionListener() {

         public void actionPerformed(ActionEvent e) {
         try{
             theQuery("insert into Files11(FileName,Date,Coding,Demo,Audit,Lop,Denials,Cs,Comments,Percentage) values('"+JT_FileName.getText()+"','"+JT_Date1.getText()+"','"+Coding.getText()+"','"+Demo.getText()+"','"+Audit.getText()+"','"+Lop.getText()+"','"+Denials.getText()+"','"+Cs.getText()+"','"+Comments.getText()+"','"+Percentage.getText()+"')");

          }
         catch(Exception ex){}
         }
     });

    btn_calculate.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            int num1=Integer.parseInt(Coding.getText());

            int num2=Integer.parseInt(Demo.getText());
            int num3=Integer.parseInt(Audit.getText());
            int num4=Integer.parseInt(Lop.getText());
            int num5=Integer.parseInt(Denials.getText());
            int num6=Integer.parseInt(Cs.getText());
            //int num7=Integer.parseInt(Comments.getText());
            double value=(num1+num2+num3+num4+num5+num6);
            double percent=value/100;
            double result=percent*100;
            Percentage.setText(result +"");

        }
    });

    btn_refresh.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            try{
                 String sql = "SELECT * FROM Files11 where Date between '"+datePicker1.getJFormattedTextField().getText()+"' and '"+datePicker2.getJFormattedTextField().getText()+"'";
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/tut", "root", "root");
            PreparedStatement pstm = con.prepareStatement(sql);
            ResultSet Rs = pstm.executeQuery();
            Vector data=new Vector();//tableadded start

            Vector column=new Vector();
            column.add("FileName");
            column.add("Date");
            column.add("Coding");
            column.add("Demo");
            column.add("Audit");
            column.add("Lop");
            column.add("Denials");
            column.add("Cs");
            column.add("Comments");
            column.add("Percentage");

            while(Rs.next()){
               Vector row = new Vector();
               row.add(Rs.getString("FileName"));
               row.add(Rs.getInt("Date"));
               row.add(Rs.getInt("Coding"));
               row.add(Rs.getString("Demo"));
               row.add(Rs.getString("Audit"));
               row.add(Rs.getString("Lop"));
               row.add(Rs.getString("Denials"));
               row.add(Rs.getString("Cs"));
               row.add(Rs.getString("Comments"));
               row.add(Rs.getString("Percentage"));

               data.add(row);
            }
            jtb.setModel(new DefaultTableModel(data,column));//tableaddedend
            }
               catch(Exception ex){}
        }

    });

    b.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             l1.setVisible(false);
             text.setVisible(false);
             b.setVisible(false);
             JL_Filechooser.setVisible(true);
             JL_FileName.setVisible(true);
             JL_Coding.setVisible(true);
             JL_Date.setVisible(true);
             JL_From.setVisible(true);
             JL_To.setVisible(true);
             JL_Demo.setVisible(true);
             JL_Audit.setVisible(true);
             JL_Lop.setVisible(true);
             JL_Denials.setVisible(true);
             JL_Cs.setVisible(true);
             JL_Comments.setVisible(true);

             JL_Target.setVisible(true);
             JL_Percentage.setVisible(true);

             JT_Filechooser.setVisible(true);
             JT_FileName.setVisible(true);
             Coding.setVisible(true);
             JT_Date1.setVisible(true);
             Demo.setVisible(true);
             Audit.setVisible(true);
             Lop.setVisible(true);
             Denials.setVisible(true);
             Cs.setVisible(true);
             Comments.setVisible(true);

             JT_Target.setVisible(true);

             Percentage.setVisible(true);

           //  datePicker.setVisible(true);
             datePicker1.setVisible(true);
             datePicker2.setVisible(true);

             btn_update.setVisible(true);
             btn_refresh.setVisible(true);
             btn_calculate.setVisible(true);
             openfile.setVisible(true);
             sp.setVisible(true);
        }
    });

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     setVisible(true);
     setLocationRelativeTo(null);
     setSize(650,700);

 }

//function to execute the insert update delete query
  public void theQuery(String query){
      Connection con = null;
      Statement st = null;
      try{
          con = DriverManager.getConnection("jdbc:mysql://localhost/tut","root","root");
          st = con.createStatement();
          st.executeUpdate(query);
          JOptionPane.showMessageDialog(null,"YOUR FILE HAS BEEN SUBMITTED AND UPDATED SUCCESSFULLY");
      }catch(Exception ex){
          JOptionPane.showMessageDialog(null,ex.getMessage());
      }
  }

  public void actionPerformed(ActionEvent e) {
      if(e.getSource()==openfile){
          JFileChooser fc=new JFileChooser();
          int i=fc.showOpenDialog(this);
          if(i==JFileChooser.APPROVE_OPTION){
              File f=fc.getSelectedFile();
              String filepath=f.getPath();
              JT_Filechooser.setText(filepath);
              JT_FileName.setText(f.getName());
              try{
              FileInputStream fis = new FileInputStream(f.getAbsolutePath());

              XWPFDocument document = new XWPFDocument(fis);

              List<XWPFParagraph> paragraphs = document.getParagraphs();

              int count = 0;
              int charCount = 0;
              int c = 0;
              for (XWPFParagraph para : paragraphs) {
                count++;
                charCount += para.getText().length();
                c=charCount/65;
                System.out.println(para.getText());
              }
              System.out.println("No. of lines : "+count);
             // JT_Coding.setText(Integer.toString(c));
             // JT_Coding.setEnabled(false);
             // JT_Coding.setBackground(Color.GRAY);
              fis.close();
              }catch (Exception ex) {ex.printStackTrace();  }

          }
      }
      }

     public static void main(String[] args){

         new  NewProjectRCM2();
     }
}
</code>```

Thanks in advance

答: It was by careless mistake and i have returned the integer(Rs.getint) instead of String(Rs.getString). It was funny but it took me lot of time to find.</p>

Body:
I tried to fetch the date from the textfield by using mysql and i got only year(2017) fetched
This is my query:

theQuery("insert into Files11(FileName,Date,Coding,Demo,Audit,Lop,Denials,Cs,Comments,Percentage) values('"+JT_FileName.getText()+"','"+JT_Date1.getText()+"','"+Coding.getText()+"','"+Demo.getText()+"','"+Audit.getText()+"','"+Lop.getText()+"','"+Denials.getText()+"','"+Cs.getText()+"','"+Comments.getText()+"','"+Percentage.getText()+"')");

Previously I have fetched the complete date by using this Query:

theQuery("insert into Files5(FileName,LinesCount,UserId,Date) values('"+JT_FileName.getText()+"','"+JT_LinesCount.getText()+"','"+text.getText()+"','"+JT_Date1.getText()+"')");

For Fetching:
I have used this query

String sql = "SELECT * FROM Files11";

Can anyone please help me,What i am missing here?
This is my whole Source Code:

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.*;
import java.io.*;
import java.util.Calendar;
import java.util.List;
import java.util.Vector;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import net.sourceforge.jdatepicker.impl.JDatePanelImpl;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import net.sourceforge.jdatepicker.impl.UtilDateModel;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;

public class NewProjectRCM2 extends JFrame implements ActionListener{
 JLabel JL_Filechooser,JL_FileName,JL_Coding,JL_Date,JL_From,JL_To,JL_Demo,JL_Audit,JL_Lop,JL_Denials,JL_Cs,JL_Comments,JL_Target,JL_Percentage;
 JTextField JT_Filechooser,JT_FileName,JT_Coding,JT_Date1,JT_Demo,JT_Audit,JT_Lop,JT_Denials,JT_Cs,JT_Comments,JT_Target,JT_Percentage;
 JButton btn_update,openfile,btn_refresh,btn_calculate;

    JLabel l1=new JLabel("Username:");

    JButton b = new JButton("Login");

    JTextField text = new JTextField(20);

    JTextField Coding,Demo,Audit,Lop,Denials,Cs,Comments,Percentage;

 public NewProjectRCM2(){
     super("USER_ID");
     JL_Filechooser = new JLabel("File chooser:");
     JL_FileName = new JLabel("File Name:");
     JL_Date = new JLabel("Date:");
     JL_From = new JLabel("From:");
     JL_To = new JLabel("To:");
     JL_Coding = new JLabel("Coding:");
     JL_Demo = new JLabel("Demo:");
     JL_Audit = new JLabel("Audit:");
     JL_Lop = new JLabel("Lop:");
     JL_Denials = new JLabel("Denials:");
     JL_Cs = new JLabel("Cs:");
     JL_Comments = new JLabel("Comments:");

     JL_Target=new JLabel("Target:");

     JL_Percentage=new JLabel("Percentage:");

     l1.setBounds(20,20, 80,30);
     b.setBounds(100,120, 80,30);
     text.setText(System.getProperty("user.name")); text.setBounds(100, 20, 100, 30);
     text.setEnabled(false);
     text.setFont(new Font("Tahoma", Font.BOLD,25));
     text.setBackground(Color.GRAY);

     JL_Filechooser.setBounds(20, 20, 100, 20);
     JL_FileName.setBounds(20, 50, 100, 20);
     JL_Date.setBounds(20,90, 100, 20);
     JL_From.setBounds(20, 133, 100, 20);
     JL_To.setBounds(250, 133, 100, 20);

     JL_Coding.setBounds(20,180, 100, 20);
     JL_Demo.setBounds(20, 210, 100, 20);
     JL_Audit.setBounds(20, 240, 100, 20);
     JL_Lop.setBounds(20, 270, 100, 20);
     JL_Denials.setBounds(20, 300, 100, 20);
     JL_Cs.setBounds(20, 330, 100, 20);
     JL_Comments.setBounds(20, 360, 100, 20);

     JL_Target.setBounds(250, 180, 100, 20);
     JL_Percentage.setBounds(175,410, 100, 20);

     DefaultTableModel model = new DefaultTableModel();
     JTable jtb = new JTable();//tableadded
     JScrollPane sp=new JScrollPane(jtb);    //tableadded
     sp.setBounds(20, 450, 1000, 200);//tableadded

     JT_Filechooser = new JTextField(20);
     JT_FileName = new JTextField(20);
     JT_Date1 = new JTextField(20);
     Coding = new JTextField(20);
     Demo = new JTextField(20);
     Audit = new JTextField(20);
     Lop = new JTextField(20);
     Denials = new JTextField(20);
     Cs = new JTextField(20);
     Comments = new JTextField(20);

     JT_Target = new JTextField(20);
     int Target1=100;
     JT_Target.setText(Integer.toString(Target1));
     Percentage = new JTextField(20);

     JT_Date1.setText(String.valueOf(java.time.LocalDate.now()));
     text.setBounds(100, 20, 100, 30);
     JT_Date1.setEnabled(false);
     JT_Date1.setFont(new Font("Tahoma", Font.BOLD, 15));
     JT_Date1.setBackground(Color.GRAY);

    Calendar cal = Calendar.getInstance();
     SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
     text.setBounds(100, 20, 100, 30);

     JT_Filechooser.setBounds(130,20,150,20);
     JT_FileName.setBounds(130,50,150, 20);
     JT_Date1.setBounds(130,90, 150, 20);
     Coding.setBounds(130,180, 75, 20);
     Demo.setBounds(130,210,75, 20);
     Audit.setBounds(130,240,75, 20);
     Lop.setBounds(130,270, 75, 20);
     Denials.setBounds(130,300, 75, 20);
     Cs.setBounds(130,330, 75, 20);
     Comments.setBounds(130,360,75, 20);

     JT_Target.setBounds(350, 180,75, 20);

     Percentage.setBounds(250,410, 100, 20);

     btn_update = new JButton("UPDATE");
     btn_update.setBounds(270,300,80, 20);
     btn_refresh = new JButton("Refresh");
     btn_refresh.setBounds(480,132, 80, 20);
     btn_calculate = new JButton("RESULT");
     btn_calculate.setBounds(270,360, 80, 20);

     openfile = new JButton("openfile");
     openfile.setBounds(300, 20, 80, 20);
     openfile.addActionListener(this);

     /* UtilDateModel model1 = new UtilDateModel();
     JDatePanelImpl datePanel = new JDatePanelImpl(model1);
     JDatePickerImpl datePicker = new JDatePickerImpl(datePanel,new DateLabelFormatter());
     datePicker.setBounds(130, 110, 180, 30); */

     UtilDateModel model2 = new UtilDateModel();
     JDatePanelImpl datePanel2 = new JDatePanelImpl(model2);
     JDatePickerImpl datePicker1 = new JDatePickerImpl(datePanel2,new DateLabelFormatter());
     datePicker1.setBounds(60, 133, 180, 20);

     UtilDateModel model3 = new UtilDateModel();
     JDatePanelImpl datePanel3 = new JDatePanelImpl(model3);
     JDatePickerImpl datePicker2 = new JDatePickerImpl(datePanel3,new DateLabelFormatter());
     datePicker2.setBounds(273, 133, 180, 20);

     setLayout(null);
     add(JL_Filechooser);
     add(JL_FileName);
    // add(datePicker);
     add(datePicker1);
     add(datePicker2);
     add(JL_Date);
     add(JL_From);
     add(JL_To);
     add(JL_Coding);
     add(JL_Demo);
     add(JL_Audit);
     add(JL_Lop);
     add(JL_Denials);
     add(JL_Cs);
     add(JL_Comments);

     add(JL_Target);
     add(JL_Percentage);

     add(JT_Filechooser);
     add(JT_FileName);
     add(JT_Date1);
     add(Coding);
     add(Demo);
     add(Audit);
     add(Lop);
     add(Denials);
     add(Cs);
     add(Comments);

     add(JT_Target);
     add(Percentage);

     add(btn_update);
     add(btn_refresh);
     add(btn_calculate);

     add(l1);
     add(b);
     add(text);
     add(openfile);
     add(sp);

     JL_Filechooser.setVisible(false);
     JL_FileName.setVisible(false);
     JL_Date.setVisible(false);
     JL_Coding.setVisible(false);
     JL_From.setVisible(false);
     JL_To.setVisible(false);
     JL_Demo.setVisible(false);
     JL_Audit.setVisible(false);
     JL_Lop.setVisible(false);
     JL_Denials.setVisible(false);
     JL_Cs.setVisible(false);
     JL_Comments.setVisible(false);

     JL_Target.setVisible(false);
     JL_Percentage.setVisible(false);

    // datePicker.setVisible(false);
     datePicker1.setVisible(false);
     datePicker2.setVisible(false);

     JT_Filechooser.setEnabled(false);
     JT_Filechooser.setFont(new Font("Tahoma", Font.BOLD, 15));

     JT_Filechooser.setVisible(false);
     JT_FileName.setVisible(false);
     JT_Date1.setVisible(false);
     Coding.setVisible(false);
     Demo.setVisible(false);
     Audit.setVisible(false);
     Lop.setVisible(false);
     Denials.setVisible(false);
     Cs.setVisible(false);
     Comments.setVisible(false);

     JT_Target.setVisible(false);
     Percentage.setVisible(false);

     btn_update.setVisible(false);
     btn_refresh.setVisible(false);
     btn_calculate.setVisible(false);
     openfile.setVisible(false);
     sp.setVisible(false);

   //button update
    btn_update.addActionListener(new  ActionListener() {

         public void actionPerformed(ActionEvent e) {
         try{
             theQuery("insert into Files11(FileName,Date,Coding,Demo,Audit,Lop,Denials,Cs,Comments,Percentage) values('"+JT_FileName.getText()+"','"+JT_Date1.getText()+"','"+Coding.getText()+"','"+Demo.getText()+"','"+Audit.getText()+"','"+Lop.getText()+"','"+Denials.getText()+"','"+Cs.getText()+"','"+Comments.getText()+"','"+Percentage.getText()+"')");

          }
         catch(Exception ex){}
         }
     });

    btn_calculate.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            int num1=Integer.parseInt(Coding.getText());

            int num2=Integer.parseInt(Demo.getText());
            int num3=Integer.parseInt(Audit.getText());
            int num4=Integer.parseInt(Lop.getText());
            int num5=Integer.parseInt(Denials.getText());
            int num6=Integer.parseInt(Cs.getText());
            //int num7=Integer.parseInt(Comments.getText());
            double value=(num1+num2+num3+num4+num5+num6);
            double percent=value/100;
            double result=percent*100;
            Percentage.setText(result +"");

        }
    });

    btn_refresh.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            try{
                 String sql = "SELECT * FROM Files11 where Date between '"+datePicker1.getJFormattedTextField().getText()+"' and '"+datePicker2.getJFormattedTextField().getText()+"'";
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost/tut", "root", "root");
            PreparedStatement pstm = con.prepareStatement(sql);
            ResultSet Rs = pstm.executeQuery();
            Vector data=new Vector();//tableadded start

            Vector column=new Vector();
            column.add("FileName");
            column.add("Date");
            column.add("Coding");
            column.add("Demo");
            column.add("Audit");
            column.add("Lop");
            column.add("Denials");
            column.add("Cs");
            column.add("Comments");
            column.add("Percentage");

            while(Rs.next()){
               Vector row = new Vector();
               row.add(Rs.getString("FileName"));
               row.add(Rs.getInt("Date"));
               row.add(Rs.getInt("Coding"));
               row.add(Rs.getString("Demo"));
               row.add(Rs.getString("Audit"));
               row.add(Rs.getString("Lop"));
               row.add(Rs.getString("Denials"));
               row.add(Rs.getString("Cs"));
               row.add(Rs.getString("Comments"));
               row.add(Rs.getString("Percentage"));

               data.add(row);
            }
            jtb.setModel(new DefaultTableModel(data,column));//tableaddedend
            }
               catch(Exception ex){}
        }

    });

    b.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
             l1.setVisible(false);
             text.setVisible(false);
             b.setVisible(false);
             JL_Filechooser.setVisible(true);
             JL_FileName.setVisible(true);
             JL_Coding.setVisible(true);
             JL_Date.setVisible(true);
             JL_From.setVisible(true);
             JL_To.setVisible(true);
             JL_Demo.setVisible(true);
             JL_Audit.setVisible(true);
             JL_Lop.setVisible(true);
             JL_Denials.setVisible(true);
             JL_Cs.setVisible(true);
             JL_Comments.setVisible(true);

             JL_Target.setVisible(true);
             JL_Percentage.setVisible(true);

             JT_Filechooser.setVisible(true);
             JT_FileName.setVisible(true);
             Coding.setVisible(true);
             JT_Date1.setVisible(true);
             Demo.setVisible(true);
             Audit.setVisible(true);
             Lop.setVisible(true);
             Denials.setVisible(true);
             Cs.setVisible(true);
             Comments.setVisible(true);

             JT_Target.setVisible(true);

             Percentage.setVisible(true);

           //  datePicker.setVisible(true);
             datePicker1.setVisible(true);
             datePicker2.setVisible(true);

             btn_update.setVisible(true);
             btn_refresh.setVisible(true);
             btn_calculate.setVisible(true);
             openfile.setVisible(true);
             sp.setVisible(true);
        }
    });

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     setVisible(true);
     setLocationRelativeTo(null);
     setSize(650,700);

 }

//function to execute the insert update delete query
  public void theQuery(String query){
      Connection con = null;
      Statement st = null;
      try{
          con = DriverManager.getConnection("jdbc:mysql://localhost/tut","root","root");
          st = con.createStatement();
          st.executeUpdate(query);
          JOptionPane.showMessageDialog(null,"YOUR FILE HAS BEEN SUBMITTED AND UPDATED SUCCESSFULLY");
      }catch(Exception ex){
          JOptionPane.showMessageDialog(null,ex.getMessage());
      }
  }

  public void actionPerformed(ActionEvent e) {
      if(e.getSource()==openfile){
          JFileChooser fc=new JFileChooser();
          int i=fc.showOpenDialog(this);
          if(i==JFileChooser.APPROVE_OPTION){
              File f=fc.getSelectedFile();
              String filepath=f.getPath();
              JT_Filechooser.setText(filepath);
              JT_FileName.setText(f.getName());
              try{
              FileInputStream fis = new FileInputStream(f.getAbsolutePath());

              XWPFDocument document = new XWPFDocument(fis);

              List<XWPFParagraph> paragraphs = document.getParagraphs();

              int count = 0;
              int charCount = 0;
              int c = 0;
              for (XWPFParagraph para : paragraphs) {
                count++;
                charCount += para.getText().length();
                c=charCount/65;
                System.out.println(para.getText());
              }
              System.out.println("No. of lines : "+count);
             // JT_Coding.setText(Integer.toString(c));
             // JT_Coding.setEnabled(false);
             // JT_Coding.setBackground(Color.GRAY);
              fis.close();
              }catch (Exception ex) {ex.printStackTrace();  }

          }
      }
      }

     public static void main(String[] args){

         new  NewProjectRCM2();
     }
}

Thanks in advance


来源: stackexchange

问:
Custom Layout for Custom Module wont Load In Magento 1.9
I have made a custom module in Magento. I am now trying to make it load a custom layout/template. I am sure it is something simple I am missing. Please take a look at my code and tell me what I am doing wrong.

My Package is called "Ben" and my Module "Distribution"

Firstly in "App/etc/modules" i let magento know about my module
"Ben_Distribution.xml"

```<code><?xml version="1.0"?>
 <config>
    <modules>
        <Ben_Distribution>
            <active>true</active>
            <codePool>local</codePool>
        </Ben_Distribution>
    </modules>
</config>
</code>```

Then in "app/code/local/Ben/Distribution/controllers" i put my controller "IndexController.php"

```<code><?php
class Ben_Distribution_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        //echo 'Hello World';
        $this->loadLayout();
        $this->renderLayout();
    }
}
?>
</code>```

Then in "App/code/local/Ben/Distribution/etc" i put my config file "config.xml"

```<code><config>
    <modules>
        <Ben_Distribution>
            <version>0.1.0</version>
        </Ben_Distribution>
    </modules>

    <frontend>
        <routers>
            <distribution>
                <use>standard</use>
                <args>
                    <module>Ben_Distribution</module>
                    <frontName>distribution</frontName>
                </args>
            </distribution>
        </routers>
        <layout>
            <updates>
                <distribution>
                    <file>distribution.xml</file>
                </distribution>
            </updates>
        </layout>
    </frontend>
</config>
</code>```

Then in "App/Design/Frontend/Packagename/themename/template/ben/" i put "distribution.phtml" containing some HTML to display

The finally i tried to make the layout.xml file so in "App/Design/Frontend/Packagename/themename/layout/ben/" i put  "distribution.xml"

```<code><?xml version="1.0"?>
<layout version="0.1.0">
    <distribution_index_index>
        <reference name="content">
            <block type="core/template" name="distribution" template="distribution.phtml"/>
        </reference>
    </distribution_index_index>
</layout>
</code>```

The final result is that my page loads at   www.url.co.uk/distribution/ as expected. When i used the echo statement in the controller it loads fine (a blank page with "Hello World". but when i switch to load/render the layout, i get the default website layout and none on the content in my .phtml file. So my layout.xml isnt being loaded in.

Thanks

ADDITIONAL INFO
I had my .phtml template loading my using this code in the controller, but as this loaded the standard "3 column" page layout and i needed a 1 column layout i have tried to do it using the layout.xml file instead.

```<code><?php
class Ben_Distribution_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        //Get current layout state
        $this->loadLayout();

        $block = $this->getLayout()->createBlock(
            'Mage_Core_Block_Template',
            'ben.distribution',
            array(
                'template' => 'ben/distribution.phtml'
            )
        );

        $this->getLayout()->getBlock('content')->append($block);

        $this->_initLayoutMessages('core/session');

        $this->renderLayout();
    }
}
?>
</code>```

答:
I found my own simple mistake. Sorry to waste your time.

```<code><block type="core/template" name="distribution" template="distribution.phtml"/>
</code>```

should be

```<code><block type="core/template" name="distribution" template="ben/distribution.phtml"/>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have made a custom module in Magento. I am now trying to make it load a custom layout/template. I am sure it is something simple I am missing. Please take a look at my code and tell me what I am doing wrong.

My Package is called "Ben" and my Module "Distribution"

Firstly in "App/etc/modules" i let magento know about my module
"Ben_Distribution.xml"

<?xml version="1.0"?>
 <config>
    <modules>
        <Ben_Distribution>
            <active>true</active>
            <codePool>local</codePool>
        </Ben_Distribution>
    </modules>
</config>

Then in "app/code/local/Ben/Distribution/controllers" i put my controller "IndexController.php"

<?php
class Ben_Distribution_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        //echo 'Hello World';
        $this->loadLayout();
        $this->renderLayout();
    }
}
?>

Then in "App/code/local/Ben/Distribution/etc" i put my config file "config.xml"

<config>
    <modules>
        <Ben_Distribution>
            <version>0.1.0</version>
        </Ben_Distribution>
    </modules>

    <frontend>
        <routers>
            <distribution>
                <use>standard</use>
                <args>
                    <module>Ben_Distribution</module>
                    <frontName>distribution</frontName>
                </args>
            </distribution>
        </routers>
        <layout>
            <updates>
                <distribution>
                    <file>distribution.xml</file>
                </distribution>
            </updates>
        </layout>
    </frontend>
</config>

Then in "App/Design/Frontend/Packagename/themename/template/ben/" i put "distribution.phtml" containing some HTML to display

The finally i tried to make the layout.xml file so in "App/Design/Frontend/Packagename/themename/layout/ben/" i put  "distribution.xml"

<?xml version="1.0"?>
<layout version="0.1.0">
    <distribution_index_index>
        <reference name="content">
            <block type="core/template" name="distribution" template="distribution.phtml"/>
        </reference>
    </distribution_index_index>
</layout>

The final result is that my page loads at   www.url.co.uk/distribution/ as expected. When i used the echo statement in the controller it loads fine (a blank page with "Hello World". but when i switch to load/render the layout, i get the default website layout and none on the content in my .phtml file. So my layout.xml isnt being loaded in.

Thanks

ADDITIONAL INFO
I had my .phtml template loading my using this code in the controller, but as this loaded the standard "3 column" page layout and i needed a 1 column layout i have tried to do it using the layout.xml file instead.

<?php
class Ben_Distribution_IndexController extends Mage_Core_Controller_Front_Action
{
    public function indexAction()
    {
        //Get current layout state
        $this->loadLayout();

        $block = $this->getLayout()->createBlock(
            'Mage_Core_Block_Template',
            'ben.distribution',
            array(
                'template' => 'ben/distribution.phtml'
            )
        );

        $this->getLayout()->getBlock('content')->append($block);

        $this->_initLayoutMessages('core/session');

        $this->renderLayout();
    }
}
?>

Body:
I found my own simple mistake. Sorry to waste your time.

<block type="core/template" name="distribution" template="distribution.phtml"/>

should be

<block type="core/template" name="distribution" template="ben/distribution.phtml"/>


问:
Get dates between 2 dates with equal intervals
I have 2 dates 01/04/2017 and 30/04/2017. I want all the dates between these 2 dates with 7 days interval.

```<code>Expected Output :
01/04/2017
08/04/2017
15/04/2017
22/04/2017
29/04/2017
</code>```

Please help!!

答:
One method would be to use a Calendar table. Then return the results from there using the modulus to get the 7th rows:

```<code>WITH Dates AS(
    SELECT *,
           ROW_NUMBER() OVER (ORDER BY [date]) AS RN
    FROM DateTable
    WHERE [Date] BETWEEN '20170401' AND '20170430')
SELECT *
FROM Dates
WHERE (RN - 1) % 7 = 0;
</code>```

I've used this solution, as from your post you imply that you might supply any date range, and that the 1st day may not necessarily be a Monday (or other specific day).

Body:
I have 2 dates 01/04/2017 and 30/04/2017. I want all the dates between these 2 dates with 7 days interval.

Expected Output :
01/04/2017
08/04/2017
15/04/2017
22/04/2017
29/04/2017

Please help!!

Body:
One method would be to use a Calendar table. Then return the results from there using the modulus to get the 7th rows:

WITH Dates AS(
    SELECT *,
           ROW_NUMBER() OVER (ORDER BY [date]) AS RN
    FROM DateTable
    WHERE [Date] BETWEEN '20170401' AND '20170430')
SELECT *
FROM Dates
WHERE (RN - 1) % 7 = 0;

I've used this solution, as from your post you imply that you might supply any date range, and that the 1st day may not necessarily be a Monday (or other specific day).


问:
AVPlayer play continuously
I have an array of object. Each object has a property url. Using this url I am playing audio on AVPlayer.

```<code>func playAudio(url: URL)
    {
        let player = AVPlayer(url: url )
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true)
        {
            do
            {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                    try AVAudioSession.sharedInstance().setActive(true)
            }
            catch _ as NSError {

            }

            playerViewController.player!.play()
        }

        NotificationCenter.default.addObserver(self, selector: #selector(CourseDetailViewController.moviePlayBackDidFinish(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
    }
</code>```

I want to play the audios of all objects continuously. For which I have set

```<code>NotificationCenter.default.addObserver(self, selector: #selector(CourseDetailViewController.moviePlayBackDidFinish(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
</code>```

In CourseDetailViewController.moviePlayBackDidFinish I am again calling playAudio. I then took player as a global variable so that it is not initialised again. But there is no overload of AVPlayer where we can supply url to already existing AVPlayer. And if do let player = AVPlayer(url: url ) for next audio, it doesn't play because the previous AVPlayer instance is in the foreground.
This is the challenge I am facing in playing continuous audios. I would appreciate if there a better and neat way to do this.

答:
I did the same in AVPlayer, but playing video continuously. I hope you can solve this issue exactly the same way. Add an observer to check if the player reached at the end of item. When ever each item reached at the end, notification will call.

Adding observer:

```<code>NotificationCenter.default.addObserver(self,
                                       selector: #selector(playerItemDidReachEnd(notification:)),
                                       name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                       object: avPlayer.currentItem)
avPlayer.play()
</code>```

Notification method:

func playerItemDidReachEnd(notification: Notification){
    //TODO: Add your code here..
}

Title: AVPlayer play continuously

Body:
I have an array of object. Each object has a property url. Using this url I am playing audio on AVPlayer.

func playAudio(url: URL)
    {
        let player = AVPlayer(url: url )
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true)
        {
            do
            {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                    try AVAudioSession.sharedInstance().setActive(true)
            }
            catch _ as NSError {

            }

            playerViewController.player!.play()
        }

        NotificationCenter.default.addObserver(self, selector: #selector(CourseDetailViewController.moviePlayBackDidFinish(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
    }

I want to play the audios of all objects continuously. For which I have set

NotificationCenter.default.addObserver(self, selector: #selector(CourseDetailViewController.moviePlayBackDidFinish(notification:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)

In CourseDetailViewController.moviePlayBackDidFinish I am again calling playAudio. I then took player as a global variable so that it is not initialised again. But there is no overload of AVPlayer where we can supply url to already existing AVPlayer. And if do let player = AVPlayer(url: url ) for next audio, it doesn't play because the previous AVPlayer instance is in the foreground.
This is the challenge I am facing in playing continuous audios. I would appreciate if there a better and neat way to do this.

Body:
I did the same in AVPlayer, but playing video continuously. I hope you can solve this issue exactly the same way. Add an observer to check if the player reached at the end of item. When ever each item reached at the end, notification will call.

Adding observer:

NotificationCenter.default.addObserver(self,
                                       selector: #selector(playerItemDidReachEnd(notification:)),
                                       name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                       object: avPlayer.currentItem)
avPlayer.play()

Notification method:

func playerItemDidReachEnd(notification: Notification){
    //TODO: Add your code here..
}


问:
How to rollback the two previous commits?
Consider this scenario:

Developer A does a commit: #n

Dev. B does commit #n+1

Dev. A does commit #n+2

and commit #n+3

and then discovers that in his commit #n+2 he introduced a defect.

How can dev. A rollback his last 2 commits and continue developing on commit #n+1?

Tried git reset --hard HEAD~2*, but it's coming back to dev A's commit #n.

答:
It should come back to the n+1 commit. You probably have a merge commit in there as well. You can also do a git reset --hard <sha1_of_where_you_want_to_be>

WARNING!! --hard means that any uncommitted changes you currently have
  will be thrown away permanently.

ContentLicense: CC BY-SA 2.5


问:
BasicDataSource sometimes throws "Protocol not supported, abandoning connection."

Hello all,

I have this problem with our connection pooling. I have had this problem for about 2 weeks which keeps popping up, and the problem is that it is not a consistence problem. Sometimes it work sometimes it throws exception.

The exception stack trace is the following:

```<code>dec. 04, 2017 8:34:29 AM org.postgresql.core.v3.ConnectionFactoryImpl openConnectionImpl
SEVERE: Protocol not supported, abandoning connection.
dec. 04, 2017 8:34:29 AM org.postgresql.Driver connect
SEVERE: Connection error:
org.postgresql.util.PSQLException: A connection could not be made using the requested protocol null.
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:57)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
        at org.postgresql.Driver.makeConnection(Driver.java:450)
        at org.postgresql.Driver.connect(Driver.java:252)
        at org.apache.commons.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:39)
        at org.apache.commons.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:256)
        at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:888)
        at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:432)
        at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:361)
        at org.apache.commons.dbcp2.PoolingDataSource.getConnection(PoolingDataSource.java:134)
        at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
        at implementation.DataSource.getConnection(DataSource.java:54)
        at io.swagger.api.impl.ProjectApiServiceImpl.deleteProject(ProjectApiServiceImpl.java:58)
        at io.swagger.api.ProjectApi.deleteProject(ProjectApi.java:60)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        ......
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
        at java.base/java.lang.Thread.run(Thread.java:844)
</code>```

I am using the following maven versions:

```<code><dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.1.1</version>
</dependency>
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-pool2</artifactId>
  <version>2.4.3</version>
</dependency>
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.1.4</version>
</dependency>
</code>```

This is the DataSource class which returns the connection:

```<code>package implementation;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
/**
 *
 * @author Lagoni
 */
public class DataSource {

    private static DataSource datasource;
    private BasicDataSource ds;
    private final Object lock = new Object();

    private DataSource() throws IOException, SQLException, PropertyVetoException {
        ds = new BasicDataSource();
        ds.setDriverClassName("org.postgresql.Driver");
        ds.setUsername("username");
        ds.setPassword("password");
        ds.setUrl("jdbc:postgresql://host:" + 1234 + "/database");

        ds.setMaxWaitMillis(1000 * 60); //wait max 1 min to get new connection
        ds.setMaxTotal(5);
        ds.setMaxIdle(5);
        ds.setTestWhileIdle(true);
        ds.setTestOnReturn(true);
        ds.setTimeBetweenEvictionRunsMillis(10000); // 10 sec wait to run evictor process
        ds.setSoftMinEvictableIdleTimeMillis(10000); // 10 sec wait to run evictor process
        ds.setMinEvictableIdleTimeMillis(10000); // 10 seconds to wait before idle connection is evicted
        ds.setMaxConnLifetimeMillis(1000*60*10); // 10 minutes is max life time
    }
    public static DataSource getInstance() {
        return datasource;
    }

    public static void cacheInstance() throws IOException, SQLException, PropertyVetoException{
        datasource = new DataSource();
    }

    /**
     * Weird exception is sometimes thrown.
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        synchronized(lock){
            return ds.getConnection();
        }
    }
}
</code>```

Could it be the settings which are used on ds or is it something else? In the beginning I thought it was the getConnection method which where not synchronized correctly, but I am starting to doubt that since. I have tried to tweak the settings both with a lower evict times and higher. But I am out of ideas.

答: The solution to this problem was to use a local database instead of a public database server which I was given access to. So make sure the database server is not faulted if you experience a similar problem. </p>

Body:
Hello all,

I have this problem with our connection pooling. I have had this problem for about 2 weeks which keeps popping up, and the problem is that it is not a consistence problem. Sometimes it work sometimes it throws exception.

The exception stack trace is the following:

dec. 04, 2017 8:34:29 AM org.postgresql.core.v3.ConnectionFactoryImpl openConnectionImpl
SEVERE: Protocol not supported, abandoning connection.
dec. 04, 2017 8:34:29 AM org.postgresql.Driver connect
SEVERE: Connection error:
org.postgresql.util.PSQLException: A connection could not be made using the requested protocol null.
        at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:57)
        at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
        at org.postgresql.Driver.makeConnection(Driver.java:450)
        at org.postgresql.Driver.connect(Driver.java:252)
        at org.apache.commons.dbcp2.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:39)
        at org.apache.commons.dbcp2.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:256)
        at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:888)
        at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:432)
        at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:361)
        at org.apache.commons.dbcp2.PoolingDataSource.getConnection(PoolingDataSource.java:134)
        at org.apache.commons.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1533)
        at implementation.DataSource.getConnection(DataSource.java:54)
        at io.swagger.api.impl.ProjectApiServiceImpl.deleteProject(ProjectApiServiceImpl.java:58)
        at io.swagger.api.ProjectApi.deleteProject(ProjectApi.java:60)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        ......
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
        at java.base/java.lang.Thread.run(Thread.java:844)

I am using the following maven versions:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.1.1</version>
</dependency>
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-pool2</artifactId>
  <version>2.4.3</version>
</dependency>
<dependency>
  <groupId>org.postgresql</groupId>
  <artifactId>postgresql</artifactId>
  <version>42.1.4</version>
</dependency>

This is the DataSource class which returns the connection:

package implementation;

import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp2.BasicDataSource;
/**
 *
 * @author Lagoni
 */
public class DataSource {

    private static DataSource datasource;
    private BasicDataSource ds;
    private final Object lock = new Object();

    private DataSource() throws IOException, SQLException, PropertyVetoException {
        ds = new BasicDataSource();
        ds.setDriverClassName("org.postgresql.Driver");
        ds.setUsername("username");
        ds.setPassword("password");
        ds.setUrl("jdbc:postgresql://host:" + 1234 + "/database");

        ds.setMaxWaitMillis(1000 * 60); //wait max 1 min to get new connection
        ds.setMaxTotal(5);
        ds.setMaxIdle(5);
        ds.setTestWhileIdle(true);
        ds.setTestOnReturn(true);
        ds.setTimeBetweenEvictionRunsMillis(10000); // 10 sec wait to run evictor process
        ds.setSoftMinEvictableIdleTimeMillis(10000); // 10 sec wait to run evictor process
        ds.setMinEvictableIdleTimeMillis(10000); // 10 seconds to wait before idle connection is evicted
        ds.setMaxConnLifetimeMillis(1000*60*10); // 10 minutes is max life time
    }
    public static DataSource getInstance() {
        return datasource;
    }

    public static void cacheInstance() throws IOException, SQLException, PropertyVetoException{
        datasource = new DataSource();
    }

    /**
     * Weird exception is sometimes thrown.
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        synchronized(lock){
            return ds.getConnection();
        }
    }
}

Could it be the settings which are used on ds or is it something else? In the beginning I thought it was the getConnection method which where not synchronized correctly, but I am starting to doubt that since. I have tried to tweak the settings both with a lower evict times and higher. But I am out of ideas.


问:
PHP to determine client's requested dataType or responseType
I have a simple ajax request:

```<code>$.post('server.php',data, function (json) {console.log(json)},'json');
</code>```

I've set it up so that jQuery is expecting json as specified by the last dataType setting.

Related question: Is dataType another name for responseType?  See http://msdn.microsoft.com/en-us/library/windows/apps/hh871381.aspx

Now my real question.  server.php sometimes returns json, other times html, and other times xml, and will set the appropriate header when rendering the response.

Before rendering the response, however, the server needs to determine what type of data to provide.  I wish to base the response upon the dataType and/or responseType header it receives from the client. How do I read this header within PHP?

答:
The XMLHttpRequest.responseType attribute, is no information that is in any form send to the server. Therefore you cannot use this to have your server's php code determine the requested content-type.

However there is a HTTP Request Header field named ACCEPT (see mdn),
which can be set using the XMLHttpRequest.setRequestHeader() (see mdn again). With it you can attribute to the request some information, accessible to your php code via $_SERVER['HTTP_ACCEPT'].

On client-side, in place of (or in addition to) setting  XMLHttpRequest.responseType you can do this

```<code>// create XHR Object
var xhr =  new XMLHttpRequest();

// open request
xhr.open(<url to request>, "POST");

// set the responseType to json (which only provokes
// that the returned data is automatically interpreted
// by the browser as being json. saving you from manually
// doing a JSON.parse(xhr.responseText);
xhr.responseType='json';

// set the request HTTP ACCEPT header to be the MIME of JSON
// that is "application/json"
xhr.setRequestHeader("ACCEPT","application/json");

//[... setup the callbacks for handling the resonses or failures]

//send the request
xhr.send();
</code>```

On server-side, you might then do something along the lines of

```<code>if($_SERVER['HTTP_ACCEPT'] === 'application/json')
{
    header('Content-Type: application/json');
    echo '<json-string>';
    die(0);
}
else
{
    // do some stuff for other Request that do
    // not want explicitly json.
}
</code>```

Body:
I have a simple ajax request:

$.post('server.php',data, function (json) {console.log(json)},'json');

I've set it up so that jQuery is expecting json as specified by the last dataType setting.

Related question: Is dataType another name for responseType?  See http://msdn.microsoft.com/en-us/library/windows/apps/hh871381.aspx

Now my real question.  server.php sometimes returns json, other times html, and other times xml, and will set the appropriate header when rendering the response.

Before rendering the response, however, the server needs to determine what type of data to provide.  I wish to base the response upon the dataType and/or responseType header it receives from the client. How do I read this header within PHP?

Body:
The XMLHttpRequest.responseType attribute, is no information that is in any form send to the server. Therefore you cannot use this to have your server's php code determine the requested content-type.

However there is a HTTP Request Header field named ACCEPT (see mdn),
which can be set using the XMLHttpRequest.setRequestHeader() (see mdn again). With it you can attribute to the request some information, accessible to your php code via $_SERVER['HTTP_ACCEPT'].

On client-side, in place of (or in addition to) setting  XMLHttpRequest.responseType you can do this

// create XHR Object
var xhr =  new XMLHttpRequest();

// open request
xhr.open(<url to request>, "POST");

// set the responseType to json (which only provokes
// that the returned data is automatically interpreted
// by the browser as being json. saving you from manually
// doing a JSON.parse(xhr.responseText);
xhr.responseType='json';

// set the request HTTP ACCEPT header to be the MIME of JSON
// that is "application/json"
xhr.setRequestHeader("ACCEPT","application/json");

//[... setup the callbacks for handling the resonses or failures]

//send the request
xhr.send();

On server-side, you might then do something along the lines of

if($_SERVER['HTTP_ACCEPT'] === 'application/json')
{
    header('Content-Type: application/json');
    echo '<json-string>';
    die(0);
}
else
{
    // do some stuff for other Request that do
    // not want explicitly json.
}


问:
Is there a way to asterisk an input as it's being typed?
I've to make this code where I have to take a customers order and then take a form of payment. For the card payment I was wondering if there was a way to have the input replaced with asterisks as they were typed. There is a line where I ask them to input their pin which is as follows:

```<code>pin=input("Insert your pin") #Asks user for pin number.
</code>```

Let's say the pin is 1234. Instead of it showing 1234 as it is typed, is there a way to make it go **** when it's being typed. I've tried using .getpass(); whether or not I've used it right I don't know. Any help would be appreciated.

答:
Getpass would usually just be used like:

```<code>from getpass import getpass

pin = getpass()
</code>```

Worth noting in some IDEs can cause problems. See here for example.

Body:
I've to make this code where I have to take a customers order and then take a form of payment. For the card payment I was wondering if there was a way to have the input replaced with asterisks as they were typed. There is a line where I ask them to input their pin which is as follows:

pin=input("Insert your pin") #Asks user for pin number.

Let's say the pin is 1234. Instead of it showing 1234 as it is typed, is there a way to make it go **** when it's being typed. I've tried using .getpass(); whether or not I've used it right I don't know. Any help would be appreciated.

Body:
Getpass would usually just be used like:

from getpass import getpass

pin = getpass()

Worth noting in some IDEs can cause problems. See here for example.


问:
Why does calling DateTime.withTime() from another method cause an exceptionInInitializerError
This code worked until just a couple days ago.  Now it no longer works on android version 6.0.  It does work on version 7.0 and newer.

```<code>public void setToDate(String quickDate) {
    DateTime toDate = new DateTime();

    if (quickDate.equals(context.getString(R.string.quickDate_today))) {
        fromDate = fromDate.withTimeAtStartOfDay();
        toDate = DateUtils.endOfDay(toDate);
    }
    ....
}

 /**
 * @return a copy of dateTime with the time set to 11:59:59.999 pm.
 */
public static DateTime endOfDay(DateTime dateTime) {
    return dateTime.withTime(23, 59, 59, 999);
}
</code>```

Here is the weird thing, If I move the withTime() call to be called directly instead of in a utility method like so:

```<code>public void setToDate(String quickDate) {
    DateTime toDate = new DateTime();

    if (quickDate.equals(context.getString(R.string.quickDate_today))) {
        fromDate = fromDate.withTimeAtStartOfDay();
        toDate = toDate.withTime(23, 59, 59, 999);
    }
    ....
}
</code>```

Then the code works, no exceptions thrown.  Why? how can i make it work inside the utility method again?

Stack Trace:

```<code>Process: com.salesrabbit.android.sales.universal, PID: 29358
java.lang.ExceptionInInitializerError
    at com.salesrabbit.android.sales.universal.canvass.filter.filters.Filter.setQuickFromAndToDates(Filter.java:273)
    at com.salesrabbit.android.widget.FilterView.lambda$loadQuickDateMenu$3$FilterView(FilterView.java:203)
    at com.salesrabbit.android.widget.FilterView$$Lambda$3.onMenuItemClick(Unknown Source)
    at android.support.v7.widget.PopupMenu$1.onMenuItemSelected(PopupMenu.java:108)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
    at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
    at android.widget.AdapterView.performItemClick(AdapterView.java:310)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3066)
    at android.widget.AbsListView$3.run(AbsListView.java:3903)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.IllegalArgumentException: Unknown pattern character 'X'
    at java.text.SimpleDateFormat.validatePatternCharacter(SimpleDateFormat.java:323)
    at java.text.SimpleDateFormat.validatePattern(SimpleDateFormat.java:312)
    at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:365)
    at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:258)
    at com.salesrabbit.android.util.DateUtils.<clinit>(DateUtils.java:31)
</code>```

答:
As you probably know - ExceptionInInitializerError is thrown when Java fails to create an instance of a class - it usually indicates an error in the constructor but can also be from a static block in the class.

Example (This class cannot be created because of the static block, you would see the error):

```<code>class MyClass {

    private static boolean canDivideByZero;
    private Object unassignedValue;

    static {
         //Of course this code is ridiculous, it's just an example
         canDivideByZero = (10/0 == 10);
    }

    public MyClass() {
        //The stupid NPE here would also manifest as an ExceptionInInitializerError
        if ( unassignedValue.equals("") ) {
            ...
        }
    }

}
</code>```

Although you have not included the required stack trace your comment gives us a clue

Here is the weird thing, If I move the withTime() ... Then the code works, no exceptions thrown

So the issue can either be that your utility class is not instantiable or, something in the method you are calling is broken - and you are calling it from a constructor. Do bear in mind, that a utility class should really be final with a private constructor which does nothing.

NOTE: In OP's specific example a static variable trying to use a value from another SDK was the cause. This is something I did not cover in my example above - static blocks and static variables are both initialized when the class is loaded and either can throw this exception.

Body:
This code worked until just a couple days ago.  Now it no longer works on android version 6.0.  It does work on version 7.0 and newer.

public void setToDate(String quickDate) {
    DateTime toDate = new DateTime();

    if (quickDate.equals(context.getString(R.string.quickDate_today))) {
        fromDate = fromDate.withTimeAtStartOfDay();
        toDate = DateUtils.endOfDay(toDate);
    }
    ....
}

 /**
 * @return a copy of dateTime with the time set to 11:59:59.999 pm.
 */
public static DateTime endOfDay(DateTime dateTime) {
    return dateTime.withTime(23, 59, 59, 999);
}

Here is the weird thing, If I move the withTime() call to be called directly instead of in a utility method like so:

public void setToDate(String quickDate) {
    DateTime toDate = new DateTime();

    if (quickDate.equals(context.getString(R.string.quickDate_today))) {
        fromDate = fromDate.withTimeAtStartOfDay();
        toDate = toDate.withTime(23, 59, 59, 999);
    }
    ....
}

Then the code works, no exceptions thrown.  Why? how can i make it work inside the utility method again?

Stack Trace:

Process: com.salesrabbit.android.sales.universal, PID: 29358
java.lang.ExceptionInInitializerError
    at com.salesrabbit.android.sales.universal.canvass.filter.filters.Filter.setQuickFromAndToDates(Filter.java:273)
    at com.salesrabbit.android.widget.FilterView.lambda$loadQuickDateMenu$3$FilterView(FilterView.java:203)
    at com.salesrabbit.android.widget.FilterView$$Lambda$3.onMenuItemClick(Unknown Source)
    at android.support.v7.widget.PopupMenu$1.onMenuItemSelected(PopupMenu.java:108)
    at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:822)
    at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:171)
    at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:973)
    at android.support.v7.view.menu.MenuPopup.onItemClick(MenuPopup.java:127)
    at android.widget.AdapterView.performItemClick(AdapterView.java:310)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1145)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:3066)
    at android.widget.AbsListView$3.run(AbsListView.java:3903)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.lang.IllegalArgumentException: Unknown pattern character 'X'
    at java.text.SimpleDateFormat.validatePatternCharacter(SimpleDateFormat.java:323)
    at java.text.SimpleDateFormat.validatePattern(SimpleDateFormat.java:312)
    at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:365)
    at java.text.SimpleDateFormat.<init>(SimpleDateFormat.java:258)
    at com.salesrabbit.android.util.DateUtils.<clinit>(DateUtils.java:31)

Body:
As you probably know - ExceptionInInitializerError is thrown when Java fails to create an instance of a class - it usually indicates an error in the constructor but can also be from a static block in the class.

Example (This class cannot be created because of the static block, you would see the error):

class MyClass {

    private static boolean canDivideByZero;
    private Object unassignedValue;

    static {
         //Of course this code is ridiculous, it's just an example
         canDivideByZero = (10/0 == 10);
    }

    public MyClass() {
        //The stupid NPE here would also manifest as an ExceptionInInitializerError
        if ( unassignedValue.equals("") ) {
            ...
        }
    }

}

Although you have not included the required stack trace your comment gives us a clue

Here is the weird thing, If I move the withTime() ... Then the code works, no exceptions thrown

So the issue can either be that your utility class is not instantiable or, something in the method you are calling is broken - and you are calling it from a constructor. Do bear in mind, that a utility class should really be final with a private constructor which does nothing.

NOTE: In OP's specific example a static variable trying to use a value from another SDK was the cause. This is something I did not cover in my example above - static blocks and static variables are both initialized when the class is loaded and either can throw this exception.


问:
Swift - Parsing a Web Page
For the project I am currently working on, I need to download and parse the HTML for getting specific date and times.

I created a dummy project for that testing and here is the code:

```<code>import UIKit
import Alamofire
import SwiftSoup

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let diyanetURL = "https://namazvakitleri.diyanet.gov.tr/tr-TR/"

        let params = ["ulkeId" : 2, "ilId" : 500,"ilceId" : 9146]
        Alamofire.request(diyanetURL, method: .post, parameters: params, encoding: URLEncoding.default).validate(contentType: ["application/x-www-form-urlencoded"]).response { (response) in

            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                do {
                    let html: String = utf8Text
                    let doc: Document = try SwiftSoup.parse(html)
                    let bla = try doc.getElementsByAttribute("tbody")
                    for bl in bla {
                        print(bl)
                    }

                } catch let error {
                    print(error.localizedDescription)
                }

            }
        }
    }
}
</code>```

I want to get that part of the website but I couldn't:

```<code><tbody>

                                        <tr>

                                            <td>04.12.2017</td>

                                            <td>06:16</td>

                                            <td>07:47</td>

                                            <td>12:46</td>

                                            <td>15:10</td>

                                            <td>17:32</td>

                                            <td>18:56</td>

                                        </tr>

                                        <tr>

                                            <td>05.12.2017</td>

                                            <td>06:17</td>

                                            <td>07:48</td>

                                            <td>12:46</td>

                                            <td>15:09</td>

                                            <td>17:31</td>

                                            <td>18:56</td>

                                        </tr>
</code>```

How can I parse the web page and get these dates and times?

Thanks in advance.

答: Why don't you just use the API : https://ahmetimamoglu.com.tr/ahmeti-namaz-vakitleri-api-get-metodu-ile.</p>

ContentLicense: CC BY-SA 4.0

Title: Swift - Parsing a Web Page

Body:
For the project I am currently working on, I need to download and parse the HTML for getting specific date and times.

I created a dummy project for that testing and here is the code:

import UIKit
import Alamofire
import SwiftSoup

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let diyanetURL = "https://namazvakitleri.diyanet.gov.tr/tr-TR/"

        let params = ["ulkeId" : 2, "ilId" : 500,"ilceId" : 9146]
        Alamofire.request(diyanetURL, method: .post, parameters: params, encoding: URLEncoding.default).validate(contentType: ["application/x-www-form-urlencoded"]).response { (response) in

            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                do {
                    let html: String = utf8Text
                    let doc: Document = try SwiftSoup.parse(html)
                    let bla = try doc.getElementsByAttribute("tbody")
                    for bl in bla {
                        print(bl)
                    }

                } catch let error {
                    print(error.localizedDescription)
                }

            }
        }
    }
}

I want to get that part of the website but I couldn't:

                                            04.12.2017

                                            06:16

                                            07:47

                                            12:46

                                            15:10

                                            17:32

                                            18:56

                                            05.12.2017

                                            06:17

                                            07:48

                                            12:46

                                            15:09

                                            17:31

                                            18:56

How can I parse the web page and get these dates and times?

Thanks in advance.


问:
Changing of Data format from Pivoted data in Dataframes using Pandas Python

The Scenario

My dataset was in format as follows:

Which I refer as ACTUAL FORMAT

```<code>uid iid rat tmp
196 242 3   881250949
186 302 3   891717742
22  377 1   878887116
244 51  2   880606923
166 346 1   886397596
298 474 4   884182806
115 265 2   881171488
253 465 5   891628467
305 451 3   886324817
6   86  3   883603013
</code>```

and while passing it to other function (KMeans Clustering) it requires to be format like this, which I've created using Pivot mapping:

Which I refer as MATRIX FORMAT

```<code>uid 1               2               3               4
4   4.3320762062    4.3407749532    4.3111995162    4.3411425423
5   4               3               2.1952622349    3.1913491995
6   4               3.4233243638    3.8255108621    3.948791424
7   4.4983411706    4.0477240538    4.0241460801    5
8   4.1773004578    4.0191412859    4.0442369862    4.1754642909
9   4.2733984521    4.2797130861    4.2682723131    4.2816986988
15  1               3.0554789259    3.2279546684    3.1282278957
16  5               4.3473697565    4.0675394438    5
</code>```

The Problem:

Now, Since I need the result / MATRIX FORMAT Data to passed again to the First Algorithm, I need to convert it to OLD FORMAT.

Coversion:

For conversion of OLD to MATRIX Format I did:

```<code>Pivot_Matrix = source_data.pivot(values='rat', index='uid', columns='iid')
</code>```

I tried reversing & interchanging of values to get the  OLD FORMAT, which has apparently failed. Is there any way to retrieve MATRIX to OLD FORMAT?

答:
You need stack with rename_axis for columns names and last reset_index:

```<code>df = df.stack().rename_axis(('uid','iid')).reset_index(name='rat')
print (df.head())
   uid iid       rat
0    4   1  4.332076
1    4   2  4.340775
2    4   3  4.311200
3    4   4  4.341143
4    5   1  4.000000
</code>```

Body:
The Scenario

My dataset was in format as follows:

Which I refer as ACTUAL FORMAT

uid iid rat tmp
196 242 3   881250949
186 302 3   891717742
22  377 1   878887116
244 51  2   880606923
166 346 1   886397596
298 474 4   884182806
115 265 2   881171488
253 465 5   891628467
305 451 3   886324817
6   86  3   883603013

and while passing it to other function (KMeans Clustering) it requires to be format like this, which I've created using Pivot mapping:

Which I refer as MATRIX FORMAT

uid 1               2               3               4
4   4.3320762062    4.3407749532    4.3111995162    4.3411425423
5   4               3               2.1952622349    3.1913491995
6   4               3.4233243638    3.8255108621    3.948791424
7   4.4983411706    4.0477240538    4.0241460801    5
8   4.1773004578    4.0191412859    4.0442369862    4.1754642909
9   4.2733984521    4.2797130861    4.2682723131    4.2816986988
15  1               3.0554789259    3.2279546684    3.1282278957
16  5               4.3473697565    4.0675394438    5

The Problem:

Now, Since I need the result / MATRIX FORMAT Data to passed again to the First Algorithm, I need to convert it to OLD FORMAT.

Coversion:

For conversion of OLD to MATRIX Format I did:

Pivot_Matrix = source_data.pivot(values='rat', index='uid', columns='iid')

I tried reversing & interchanging of values to get the  OLD FORMAT, which has apparently failed. Is there any way to retrieve MATRIX to OLD FORMAT?

Body:
You need stack with rename_axis for columns names and last reset_index:

df = df.stack().rename_axis(('uid','iid')).reset_index(name='rat')
print (df.head())
   uid iid       rat
0    4   1  4.332076
1    4   2  4.340775
2    4   3  4.311200
3    4   4  4.341143
4    5   1  4.000000


问:
Bash: for interprets ".*" and transforms it into "." and ".."
I am trying to write a script that will iterate over all arguments and performs a search for each of them. Example of usage:

```<code>./myScript "java" "chrome" "daemon"
./myScript "java" ".*"
</code>```

The problem occurs when .* is used.

First approach:

```<code>patterns=$@
for pattern in ${patterns}; do
      ..
done
</code>```

interprets .* as being . and .. (I wasn't able to find out why).

Second approach:

```<code>patterns=$@
for pattern in "${patterns}"; do
      ..
done
</code>```

Considers all arguments as a single word (instead searching once for java and once for chrome, it will search for "java chrome").

Thanks!

答:
the problem comes from assinging an array to a variable :

```<code>patterns=$@
</code>```

to preserve arguments should be changed to

```<code>patterns=( "$@" )
</code>```

then

```<code>for pattern in "${patterns[@]}"; do
    ..
done
</code>```

Body:
I am trying to write a script that will iterate over all arguments and performs a search for each of them. Example of usage:

./myScript "java" "chrome" "daemon"
./myScript "java" ".*"

The problem occurs when .* is used.

First approach:

patterns=$@
for pattern in ${patterns}; do
      ..
done

interprets .* as being . and .. (I wasn't able to find out why).

Second approach:

patterns=$@
for pattern in "${patterns}"; do
      ..
done

Considers all arguments as a single word (instead searching once for java and once for chrome, it will search for "java chrome").

Thanks!

Body:
the problem comes from assinging an array to a variable :

patterns=$@

to preserve arguments should be changed to

patterns=( "$@" )

then

for pattern in "${patterns[@]}"; do
    ..
done


问:
Is there a .NET library for Kinect to develop Kinect application for PC (not XBOX)
Is there a .NET library for Kinect to develop Kinect application for PC (not XBOX)? Library doesn't need to be official. (AFAIK MS won't release a library for PC anyway)

答:
Microsoft has promised they will eventually release drivers and an SDK for the Kinect. Accorrding to this link, that may be sooner rather then later.

Otherwise, check out the Openkinect mailing list and wiki. They will be up to date on everything relating to development for the Kinect.


问:
How to disable authorization for /restart endpoint?
I try to implement restart feature in my web application.

I've added following dependencies:

```<code>compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter:1.2.4.RELEASE")
</code>```

In start logs I found that post /restart was registered.

I decided to request this url:

But result is fail. I understand that this url should be protected but I have custom authorization/authentication mechanism and I don't have rights to change it.

Is there way to disable protection for this url? A better way - to have service which I can inject inside my controller and invoke. Is there something inside the spring to solve my problem?

答:
try this:</p>

```<code>endpoints.restart.enabled = true
management.security.enabled=false
</code>```

Body:
I try to implement restart feature in my web application.

I've added following dependencies:

compile("org.springframework.boot:spring-boot-starter-actuator")
compile("org.springframework.cloud:spring-cloud-starter:1.2.4.RELEASE")

In start logs I found that post /restart was registered.

I decided to request this url:

But result is fail. I understand that this url should be protected but I have custom authorization/authentication mechanism and I don't have rights to change it.

Is there way to disable protection for this url? A better way - to have service which I can inject inside my controller and invoke. Is there something inside the spring to solve my problem?

Body:
try this:

endpoints.restart.enabled = true
management.security.enabled=false


问:
const correctness and member reference
I have the following class:

```<code>class DataBuilder
{
public:
    DataBuilder(Data& data): data_(data){}

    //Fun modify data_, uses private methods
    void Fun(std::string name, int id) //const ?
    {
        //calculate newInfo based on params (uses private methods)
        auto& info = data_.GetInfo();
        info = newInfo;
    }
private:
    //some private methods
    Data& data_;
};
</code>```

Theoretically Fun can be const but I wonder if it is correct (logical constness) ?

Edit1 I added a very simplified Fun implementation.
Edit2 Data has two GetInfo overloads:

```<code>Info& Data::GetInfo();
const Info& Data::GetInfo() const;
</code>```

答:
Fun is manipulating data. So it should not be able to be declared const. The fact that you are able to do that is that apparently, data.GetInfo is declared const, yet returns a reference through which you can manipulate it's internal state. That's bad programming.

So no, this is not correct. Even in theory, Fun should not be const because it is not. It is manipulating internal state. The fact that it could be is due to bad coding. Fix that. const-correctness is something that cannot be done halfheartedly. You do it, or you don't.

Title: const correctness and member reference

Body:
I have the following class:

class DataBuilder
{
public:
    DataBuilder(Data& data): data_(data){}

    //Fun modify data_, uses private methods
    void Fun(std::string name, int id) //const ?
    {
        //calculate newInfo based on params (uses private methods)
        auto& info = data_.GetInfo();
        info = newInfo;
    }
private:
    //some private methods
    Data& data_;
};

Theoretically Fun can be const but I wonder if it is correct (logical constness) ?

Edit1 I added a very simplified Fun implementation.
Edit2 Data has two GetInfo overloads:

Info& Data::GetInfo();
const Info& Data::GetInfo() const;


问:
Companion objects benefits of posibility to implement interfaces
Why in Kotlin/Scala companion objects can implements some interfaces, what benefits this can have? When is useful to use this feature?</p>

答:
You use singleton object when you need only one instance of particular class in program.

E.g. Scala's Nil implements List[Nothing]. Rather than every type of list to implement it's particular Nil there is just one of them.

In typeclass pattern, where you have just one implicit object for corresponding implementation.

Also, where you'd create a public static Something in Java, you'd create that in a companion object.

I personally found them useful for implementing an sbt plugin, that renders object Blah extends Renderable to files blah.html. Find more about usefulness here. I had to know that it implements that trait!


问:
Order object by enum in custom order
I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.

My enum:

```<code>public enum AnimalSize
    {
        Small = 1, Medium = 3, Large = 5,
    }
</code>```

My Animal class:

```<code>public class Animal : IComparable<Animal>
{
    public bool IsCarnivore;
    public AnimalSize Size;

    public Animal(bool isCarnivore, AnimalSize size)
    {
        this.IsCarnivore = isCarnivore;
        this.Size = size;
    }

    public int CompareTo(Animal other)
    {
        return this.Size.CompareTo(other.Size);
    }
</code>```

I call the CompareTo from another class where I have a private list of animals.

How can I arrange the animals in order of Medium, Large, Small?

答:
If you want to use IComparable, you'll need to convert to int first.

```<code>public int CompareTo(Animal other)
        {
            return ((int)this.Size).CompareTo((int)other.Size);
        }
</code>```

With this change, calling the Sort() function of a list containing animal objects will work as expected.

Title: Order object by enum in custom order

Body:
I'm trying to rearrange a list of animals in order from medium, large, small. I've been trying to do this with IComparable.CompareTo but I can't figure out how to order it in this specific way. I can only find ways to order by Ascending or Descending values.

My enum:

public enum AnimalSize
    {
        Small = 1, Medium = 3, Large = 5,
    }

My Animal class:

public class Animal : IComparable<Animal>
{
    public bool IsCarnivore;
    public AnimalSize Size;

    public Animal(bool isCarnivore, AnimalSize size)
    {
        this.IsCarnivore = isCarnivore;
        this.Size = size;
    }

    public int CompareTo(Animal other)
    {
        return this.Size.CompareTo(other.Size);
    }

I call the CompareTo from another class where I have a private list of animals.

How can I arrange the animals in order of Medium, Large, Small?

Body:
If you want to use IComparable, you'll need to convert to int first.

public int CompareTo(Animal other)
        {
            return ((int)this.Size).CompareTo((int)other.Size);
        }

With this change, calling the Sort() function of a list containing animal objects will work as expected.


问:
Simple programming practice (using modulus op)
First question, I'm trying to do a practice where I am asked to return true if the given non-negative number is a multiple of 3 or 5, but not both. Examples are;

old35(3) → true

old35(10) → true

old35(15) → false

So 3 would be true, as it's a multiple of 3, but I can't currently make my code work for all instances. Code below;

```<code>public boolean old35(int n) {
     if ((35 % n == 3) || (35 % n == 5))
        return true;
     return false;
}
</code>```

How could I edit this to fit the criteria of what the practice is telling me to do?
>

答:
You can use the logical XOR of the conditions. Basically you can do C1 ^ C2.
Edit: To check if multiple of 3 you must check n % 3 == 0, the same for multiple of 5.

Body:
First question, I'm trying to do a practice where I am asked to return true if the given non-negative number is a multiple of 3 or 5, but not both. Examples are;

old35(3) → true

old35(10) → true

old35(15) → false

So 3 would be true, as it's a multiple of 3, but I can't currently make my code work for all instances. Code below;

public boolean old35(int n) {
     if ((35 % n == 3) || (35 % n == 5))
        return true;
     return false;
}

How could I edit this to fit the criteria of what the practice is telling me to do?
>


问:
Ionic - Can't generate resources ios
I update the npm with npm update -g and now I can't generate ios resources.

For example if I remove android and ios folder and do ionic cordova resources just add the android folder.

I also try add with ionic cordova resources ios and ionic cordova resources --icon or --splash but don't add ios folder.

Add now when I try to generate the ios platform (ionic cordova add ios@4.4.0) it returns me and error that I think it's because the resources ios folder are missing.

```<code>    ✖ Running command - failed!
[ERROR] Exception: Using cordova-fetch for cordova-ios@4.5.1

    Adding ios project...
    Creating Cordova project for the iOS platform:
        Path: platforms/ios
        Package: com.zs.APP
        Name: APP NAME
    iOS project created with cordova-ios@4.5.1
    Error: Source path does not exist: resources/ios/icon/icon-1024.png
</code>```

How can I check ionic cordova ios version?

I don't know what to do, please help me to solve this problem.

Thank you

答:
The issue is it needs icon-1024.png.

Check the Ionic blog post.

Xcode needs a 1024×1024 sized icon for submission.

You need to have icon size of 1024x1024 present in the resources path as icon.png
and then run:

```<code>ionic cordova resources ios --icon
</code>```

Note: you may also need 2732 × 2732 size splash.png to generate splash images for IOS 11.

Title: Ionic - Can't generate resources ios

Body:
I update the npm with npm update -g and now I can't generate ios resources.

For example if I remove android and ios folder and do ionic cordova resources just add the android folder.

I also try add with ionic cordova resources ios and ionic cordova resources --icon or --splash but don't add ios folder.

Add now when I try to generate the ios platform (ionic cordova add ios@4.4.0) it returns me and error that I think it's because the resources ios folder are missing.

    ✖ Running command - failed!
[ERROR] Exception: Using cordova-fetch for cordova-ios@4.5.1

    Adding ios project...
    Creating Cordova project for the iOS platform:
        Path: platforms/ios
        Package: com.zs.APP
        Name: APP NAME
    iOS project created with cordova-ios@4.5.1
    Error: Source path does not exist: resources/ios/icon/icon-1024.png

How can I check ionic cordova ios version?

I don't know what to do, please help me to solve this problem.

Thank you

Body:
The issue is it needs icon-1024.png.

Check the Ionic blog post.

Xcode needs a 1024×1024 sized icon for submission.

You need to have icon size of 1024x1024 present in the resources path as icon.png
and then run:

ionic cordova resources ios --icon

Note: you may also need 2732 × 2732 size splash.png to generate splash images for IOS 11.


问:
How to run Findbugs and PMD on a specific jdk in hudson?

I have hudson deployed on tomcat6 and jdk 1.5
in global manage hudson i configured java 1.4 and java 1.5
for my new job i have selected java 1.4
i didn't specify JAVA_HOME in environment variables

答:
Your build is running with Java 1.4.  However, Findbugs requires Java 1.5 or later.

PMD can run under Java 1.4, but the default classes expect 1.5.  According to the PMD release notes,

"to run pmd with 1.4, use the files from the java14 directory (weaved pmd jar and support files)".

You could probably manage it as a two-step build job by customizing the java options for each step.  But if it were me, I would have the main build kick off the PMD and Findbugs actions in a separate downstream build.  That way you could still use 1.4 for your project build, but you could use 1.5 or 1.6 for the analysis (Findbugs needs 1.5 or 1.6 but it can analyze code compiled with 1.4).  This would be simple to manage using the Hudson JDK definitions.

Actually, no.  If it were me, I would use the latest JDK anyway and simply set the target version to 1.4.