hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
dea678b744bdbd0c0ed21b62cd6228dc245ec4ee
73,936
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bill_recept; import com.mysql.jdbc.Connection; import com.mysql.jdbc.PreparedStatement; import com.toedter.calendar.JDateChooser; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Date; import javax.swing.table.DefaultTableModel; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.print.PageFormat; import java.awt.print.Paper; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.awt.FontMetrics; import java.awt.HeadlessException; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JOptionPane; import javax.swing.JTextField; import net.proteanit.sql.DbUtils; /** * * @author Muhammad */ public class Bill extends javax.swing.JFrame { Connection con = null; PreparedStatement pst = null; ResultSet rs = null; double num,ans; int cal; public Bill() { initComponents(); showTableData(); } public void cal_operation() { switch(cal) { case 1 : ans= num + Double.parseDouble(t1.getText()); t1.setText(Double.toString(ans)); break; case 2 : ans= num - Double.parseDouble(t1.getText()); t1.setText(Double.toString(ans)); break; case 3 : ans=num * Double.parseDouble(t1.getText()); t1.setText(Double.toString(ans)); break; case 4 : ans=num / Double.parseDouble(t1.getText()); t1.setText(Double.toString(ans)); break; case 5 : ans=num % Double.parseDouble(t1.getText()); t1.setText(Double.toString(ans)); break; } } public void table_Field_clean() { qty.setText(""); des.setText(""); amount.setText(""); } public double sum_col() { double rowcount=tb1.getRowCount(); double sum=0; for(int i = 0; i<rowcount; i++) { sum=sum+Integer.parseInt(tb1.getValueAt(i, 2).toString()); } return sum; } public void date() { Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("MMM d,YYYY"); order_date.setText(sdf.format(d)); } public void showTableData(){ try{ con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/lootha","root",""); String sql = "SELECT * FROM customer"; pst = (PreparedStatement) con.prepareStatement(sql); rs=pst.executeQuery(); jTable1.setModel(DbUtils.resultSetToTableModel(rs)); } catch(SQLException ex){ JOptionPane.showMessageDialog(null, ex); } } public PageFormat getPageFormat(PrinterJob pj) { PageFormat pf = pj.defaultPage(); Paper paper = pf.getPaper(); double middleHeight =8.0; double headerHeight = 2.0; double footerHeight = 2.0; double width = convert_CM_To_PPI(8); //printer know only point per inch.default value is 72ppi double height = convert_CM_To_PPI(headerHeight+middleHeight+footerHeight); paper.setSize(width, height); paper.setImageableArea( 0, 10, width, height - convert_CM_To_PPI(1) ); //define boarder size after that print area width is about 180 points pf.setOrientation(PageFormat.PORTRAIT); //select orientation portrait or landscape but for this time portrait pf.setPaper(paper); return pf; } protected static double convert_CM_To_PPI(double cm) { return toPPI(cm * 0.393600787); } protected static double toPPI(double inch) { return inch * 72d; } public class BillPrintable implements Printable { public int print(Graphics graphics, PageFormat pageFormat,int pageIndex) throws PrinterException { int result = NO_SUCH_PAGE; if (pageIndex == 0) { Graphics2D g2d = (Graphics2D) graphics; double width = pageFormat.getImageableWidth(); g2d.translate((int) pageFormat.getImageableX(),(int) pageFormat.getImageableY()); ////////// code by alqama////////////// FontMetrics metrics=g2d.getFontMetrics(new Font("Arial",Font.BOLD,7)); // int idLength=metrics.stringWidth("000000"); //int idLength=metrics.stringWidth("00"); int idLength=metrics.stringWidth("000"); int amtLength=metrics.stringWidth("000000"); int qtyLength=metrics.stringWidth("00000"); int priceLength=metrics.stringWidth("000000"); int prodLength=(int)width - idLength - amtLength - qtyLength - priceLength-17; // int idPosition=0; // int productPosition=idPosition + idLength + 2; // int pricePosition=productPosition + prodLength +10; // int qtyPosition=pricePosition + priceLength + 2; // int amtPosition=qtyPosition + qtyLength + 2; int productPosition = 0; int discountPosition= prodLength+5; int pricePosition = discountPosition +idLength+10; int qtyPosition=pricePosition + priceLength + 4; int amtPosition=qtyPosition + qtyLength; try{ /*Draw Header*/ int y=20; int yShift = 10; int headerRectHeight=15; int headerRectHeighta=40; ///////////////// Product names Get /////////// ///////////////// Product names Get /////////// ///////////////// Product price Get /////////// ///////////////// Product price Get /////////// g2d.setFont(new Font("Monospaced",Font.PLAIN,9)); g2d.drawString("-----------------------------------------",12,y);y+=yShift; g2d.drawString(" LOOTHA TRAILORING SHOP Receipt ",12,y);y+=yShift; g2d.drawString("-----------------------------------------",12,y);y+=headerRectHeight; g2d.drawString("-----------------------------------------",10,y);y+=yShift; g2d.drawString(" QTY DESCRIPTION T.Price ",10,y);y+=yShift; g2d.drawString("-----------------------------------------",10,y);y+=headerRectHeight; double rowcount=tb1.getRowCount(); for(int i = 0; i<rowcount; i++) { Integer col0=Integer.parseInt(tb1.getValueAt(i, 0).toString()); String col1=(tb1.getValueAt(i, 1).toString()); double col2=Integer.parseInt(tb1.getValueAt(i, 2).toString()); g2d.drawString(" "+col0+" "+col1+" AED "+col2+" ",10,y);y+=yShift; } g2d.drawString("-----------------------------------------",10,y);y+=yShift; g2d.drawString(" SUB amount: AED "+total+" ",10,y);y+=yShift; g2d.drawString("-----------------------------------------",10,y);y+=yShift; g2d.drawString(" TAX amount: AED "+tax1+" ",10,y);y+=yShift; g2d.drawString("-----------------------------------------",10,y);y+=yShift; g2d.drawString(" Total amount: AED "+Total+" ",10,y);y+=yShift; g2d.drawString("-----------------------------------------",10,y);y+=yShift; g2d.drawString(" Advance amount: AED "+advance+" ",10,y);y+=yShift; g2d.drawString("-----------------------------------------",10,y);y+=yShift; g2d.drawString(" Balance amount: AED "+balance+" ",10,y);y+=yShift; g2d.drawString("*****************************************",10,y);y+=yShift; g2d.drawString(" THANKS TO VISIT OUR SHOP ",10,y);y+=yShift; g2d.drawString("*************************************",10,y);y+=yShift; // g2d.setFont(new Font("Monospaced",Font.BOLD,10)); // g2d.drawString("Customer Shopping Invoice", 30,y);y+=yShift; } catch(Exception r){ r.printStackTrace(); } result = PAGE_EXISTS; } return result; } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); customer_name = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); order_date = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); customer_phone = new javax.swing.JTextField(); receive_date = new com.toedter.calendar.JDateChooser(); order_recept = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jScrollPane2 = new javax.swing.JScrollPane(); tb1 = new javax.swing.JTable(); qty = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); des = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); amount = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jButton20 = new javax.swing.JButton(); iMessage = new javax.swing.JLabel(); jButton26 = new javax.swing.JButton(); jPanel4 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jLabel14 = new javax.swing.JLabel(); sub_total = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); total_amount = new javax.swing.JTextField(); advance_amt = new javax.swing.JTextField(); balance_amt = new javax.swing.JTextField(); jButton22 = new javax.swing.JButton(); jButton23 = new javax.swing.JButton(); jButton24 = new javax.swing.JButton(); jButton25 = new javax.swing.JButton(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); jLabel19 = new javax.swing.JLabel(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel6 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton27 = new javax.swing.JButton(); jButton28 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); t1 = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jButton7 = new javax.swing.JButton(); jButton8 = new javax.swing.JButton(); jButton9 = new javax.swing.JButton(); jButton10 = new javax.swing.JButton(); jButton11 = new javax.swing.JButton(); jButton12 = new javax.swing.JButton(); jButton13 = new javax.swing.JButton(); jButton14 = new javax.swing.JButton(); jButton15 = new javax.swing.JButton(); jButton16 = new javax.swing.JButton(); jButton17 = new javax.swing.JButton(); jButton18 = new javax.swing.JButton(); jButton19 = new javax.swing.JButton(); jButton21 = new javax.swing.JButton(); l1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(255, 255, 255)); setSize(new java.awt.Dimension(1800, 1200)); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 153, 51)); jLabel1.setText("LOOTHA TRAILORING SHOP"); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4)); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setText("Order Recept_NO :"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setText("Customer Name :"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setText("Order Date :"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setText("Receive Date :"); order_date.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { order_dateMouseClicked(evt); } }); order_date.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { order_dateActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel6.setText("Customer Phone No :"); receive_date.setName("date"); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel6) .addGap(18, 18, 18) .addComponent(customer_phone)) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(35, 35, 35) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(customer_name, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE) .addComponent(order_recept)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(receive_date, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(order_date, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(order_date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(15, 15, 15) .addComponent(order_recept, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(customer_name, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(receive_date, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(customer_phone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29)) ); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4)); tb1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Qty", "DESCRIPTION", "Amount (AED)" } )); tb1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tb1MouseClicked(evt); } }); jScrollPane2.setViewportView(tb1); jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel7.setText("Qty :"); jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel8.setText("Description :"); jLabel9.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel9.setText("Amount(AED) :"); jButton1.setText("ADD"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton20.setText("DELETE"); jButton20.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton20ActionPerformed(evt); } }); iMessage.setForeground(new java.awt.Color(255, 0, 0)); jButton26.setText("UPDATE"); jButton26.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton26ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 553, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(iMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 407, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(amount)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(qty, javax.swing.GroupLayout.PREFERRED_SIZE, 233, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addGap(18, 18, 18) .addComponent(des))) .addGap(98, 98, 98) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton26, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton20, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(qty, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(des, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton26)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(amount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton20)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(iMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 312, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel4.setBackground(new java.awt.Color(255, 255, 255)); jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 4)); jLabel10.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel10.setText("Order Sub Total :"); jLabel11.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel11.setText("TAX Amount :"); jLabel12.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel12.setText("Total Amount :"); jLabel13.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel13.setText("Advance Amt :"); jLabel14.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N jLabel14.setText("Balanace Amt :"); jButton22.setText("TOTAL"); jButton22.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton22ActionPerformed(evt); } }); jButton23.setText("FINAL AMOUNT"); jButton23.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton23ActionPerformed(evt); } }); jButton24.setText("ADD TO DATABASE"); jButton24.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton24ActionPerformed(evt); } }); jButton25.setText("RECEPT PRINT"); jButton25.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton25ActionPerformed(evt); } }); jLabel15.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel15.setText("AED"); jLabel16.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel16.setText("AED"); jLabel17.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel17.setText("AED"); jLabel18.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel18.setText("AED"); jLabel19.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel19.setText("AED"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel10, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel11, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel14, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel12, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(sub_total) .addComponent(jTextField2) .addComponent(total_amount) .addComponent(advance_amt) .addComponent(balance_amt, javax.swing.GroupLayout.DEFAULT_SIZE, 117, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel16) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel15) .addComponent(jLabel17) .addComponent(jLabel18) .addComponent(jLabel19)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton24) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jButton25, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton23, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton22, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(jLabel10)) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(sub_total, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel16))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel15, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(total_amount, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel17, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel12)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(advance_amt, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel13)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(balance_amt) .addComponent(jLabel14) .addComponent(jLabel19, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) .addGroup(jPanel4Layout.createSequentialGroup() .addGap(26, 26, 26) .addComponent(jButton22) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton23) .addGap(12, 12, 12) .addComponent(jButton25) .addGap(18, 18, 18) .addComponent(jButton24) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Recept No", "C. Name", "c.phone No", "order date", "receive date", "sub total", "VAT", "T.Amount" } )); jScrollPane1.setViewportView(jTable1); jButton27.setText("Delete"); jButton27.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton27ActionPerformed(evt); } }); jButton28.setText("Update"); jButton28.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton28ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel6Layout.createSequentialGroup() .addGap(71, 71, 71) .addComponent(jButton27) .addGap(41, 41, 41) .addComponent(jButton28) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 384, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE) .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton27) .addComponent(jButton28)) .addContainerGap()) ); jTabbedPane1.addTab("Database", jPanel6); t1.setEditable(false); t1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N t1.setHorizontalAlignment(javax.swing.JTextField.RIGHT); t1.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR)); t1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { t1ActionPerformed(evt); } }); jButton2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton2.setText("<-"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton3.setText("AC"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton4.setText("%"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jButton5.setText("÷"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton6.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jButton6.setText("×"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); jButton7.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton7.setText("3"); jButton7.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton7ActionPerformed(evt); } }); jButton8.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton8.setText("2"); jButton8.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton8ActionPerformed(evt); } }); jButton9.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton9.setText("1"); jButton9.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton9ActionPerformed(evt); } }); jButton10.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jButton10.setText("+"); jButton10.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton10ActionPerformed(evt); } }); jButton11.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton11.setText("6"); jButton11.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton11ActionPerformed(evt); } }); jButton12.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton12.setText("5"); jButton12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton12ActionPerformed(evt); } }); jButton13.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton13.setText("4"); jButton13.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton13ActionPerformed(evt); } }); jButton14.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jButton14.setText("−"); jButton14.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton14ActionPerformed(evt); } }); jButton15.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton15.setText("8"); jButton15.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton15ActionPerformed(evt); } }); jButton16.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton16.setText("9"); jButton16.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton16ActionPerformed(evt); } }); jButton17.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jButton17.setText("7"); jButton17.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton17ActionPerformed(evt); } }); jButton18.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jButton18.setText("."); jButton18.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM); jButton18.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); jButton18.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton18ActionPerformed(evt); } }); jButton19.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jButton19.setText("="); jButton19.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton19ActionPerformed(evt); } }); jButton21.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jButton21.setText("0"); jButton21.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton21ActionPerformed(evt); } }); l1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N l1.setForeground(new java.awt.Color(204, 0, 0)); l1.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); l1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM); l1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(46, 46, 46) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel3Layout.createSequentialGroup() .addComponent(jButton21, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton19, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jButton17, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton16, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton14, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(4, 4, 4) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(10, 10, 10) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(l1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(57, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap(39, Short.MAX_VALUE) .addComponent(l1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(t1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton14, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton16, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton15, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton17, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton18, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton21)) .addComponent(jButton19)) .addContainerGap()) ); jTabbedPane1.addTab("Calculator", jPanel3); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 310, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(335, 335, 335)) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) .addComponent(jTabbedPane1))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jTabbedPane1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed iMessage.setText(""); DefaultTableModel table1=(DefaultTableModel) tb1.getModel(); if(!qty.getText().trim().equals("")) { table1.addRow(new Object[]{qty.getText(),des.getText(),amount.getText()}); } else { iMessage.setText("TextField should not be left blank"); } table_Field_clean(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton26ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton26ActionPerformed iMessage.setText(""); DefaultTableModel table1=(DefaultTableModel) tb1.getModel(); if(tb1.getSelectedRow()== -1){ if(tb1.getRowCount()== 0) { iMessage.setText("Table is Empty"); } else {iMessage.setText("You must Select Info from table to Update"); } } else { table1.setValueAt(qty.getText(),tb1.getSelectedRow(),0); table1.setValueAt(des.getText(),tb1.getSelectedRow(),1); table1.setValueAt(amount.getText(),tb1.getSelectedRow(),2); } }//GEN-LAST:event_jButton26ActionPerformed private void jButton20ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton20ActionPerformed iMessage.setText(""); DefaultTableModel table1=(DefaultTableModel) tb1.getModel(); if(tb1.getSelectedRow()== -1){ if(tb1.getRowCount()== 0) { iMessage.setText("Table is Empty"); } else {iMessage.setText("You must Select Info from table to Update"); } } else table1.removeRow(tb1.getSelectedRow()); }//GEN-LAST:event_jButton20ActionPerformed private void tb1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tb1MouseClicked DefaultTableModel table1=(DefaultTableModel) tb1.getModel(); qty.setText(table1.getValueAt(tb1.getSelectedRow(),0).toString()); des.setText(table1.getValueAt(tb1.getSelectedRow(),1).toString()); amount.setText(table1.getValueAt(tb1.getSelectedRow(),2).toString()); }//GEN-LAST:event_tb1MouseClicked Double total; double tax1; Double Total; private void jButton22ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton22ActionPerformed total=sum_col(); sub_total.setText(" "+total); tax1=total*5/100; jTextField2.setText(" "+tax1); Total=tax1+total; total_amount.setText(" "+Total); }//GEN-LAST:event_jButton22ActionPerformed double balance; double advance; private void jButton23ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton23ActionPerformed advance=Double.parseDouble(advance_amt.getText()); balance=Total-advance; balance_amt.setText(" "+balance); }//GEN-LAST:event_jButton23ActionPerformed private void order_dateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_order_dateActionPerformed Date d = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); order_date.setText("The current time is "+sdf.format(d)); }//GEN-LAST:event_order_dateActionPerformed private void order_dateMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_order_dateMouseClicked date(); }//GEN-LAST:event_order_dateMouseClicked private void jButton25ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton25ActionPerformed PrinterJob pj = PrinterJob.getPrinterJob(); pj.setPrintable(new BillPrintable(),getPageFormat(pj)); try { pj.print(); } catch (PrinterException ex) { ex.printStackTrace(); } }//GEN-LAST:event_jButton25ActionPerformed private void jButton21ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton21ActionPerformed t1.setText(t1.getText()+ "0"); }//GEN-LAST:event_jButton21ActionPerformed private void jButton19ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton19ActionPerformed cal_operation(); l1.setText(""); }//GEN-LAST:event_jButton19ActionPerformed private void jButton18ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton18ActionPerformed t1.setText(t1.getText()+ "."); }//GEN-LAST:event_jButton18ActionPerformed private void jButton17ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton17ActionPerformed t1.setText(t1.getText()+ "7"); }//GEN-LAST:event_jButton17ActionPerformed private void jButton16ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton16ActionPerformed t1.setText(t1.getText()+ "9"); }//GEN-LAST:event_jButton16ActionPerformed private void jButton15ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton15ActionPerformed t1.setText(t1.getText()+ "8"); }//GEN-LAST:event_jButton15ActionPerformed private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed num=Double.parseDouble(t1.getText()); cal = 2; t1.setText(""); l1.setText(num + "-"); }//GEN-LAST:event_jButton14ActionPerformed private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed t1.setText(t1.getText()+ "4"); }//GEN-LAST:event_jButton13ActionPerformed private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed t1.setText(t1.getText()+ "5"); }//GEN-LAST:event_jButton12ActionPerformed private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed t1.setText(t1.getText()+ "6"); }//GEN-LAST:event_jButton11ActionPerformed private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed num=Double.parseDouble(t1.getText()); cal = 1; t1.setText(""); l1.setText(num + "+"); }//GEN-LAST:event_jButton10ActionPerformed private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed t1.setText(t1.getText()+ "1"); }//GEN-LAST:event_jButton9ActionPerformed private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed t1.setText(t1.getText()+ "2"); }//GEN-LAST:event_jButton8ActionPerformed private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed t1.setText(t1.getText()+ "3"); }//GEN-LAST:event_jButton7ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed num=Double.parseDouble(t1.getText()); cal = 3; t1.setText(""); l1.setText(num + "*"); }//GEN-LAST:event_jButton6ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed num=Double.parseDouble(t1.getText()); cal = 4; t1.setText(""); l1.setText(num + "/"); }//GEN-LAST:event_jButton5ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed num=Double.parseDouble(t1.getText()); cal = 5; t1.setText(""); l1.setText(num + "%"); }//GEN-LAST:event_jButton4ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed t1.setText(""); }//GEN-LAST:event_jButton3ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed int len=t1.getText().length(); int num=t1.getText().length() - 1; String store; if(len > 0) { StringBuilder back=new StringBuilder(t1.getText()); back.deleteCharAt(num); store=back.toString(); t1.setText(store); } }//GEN-LAST:event_jButton2ActionPerformed private void t1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_t1ActionPerformed }//GEN-LAST:event_t1ActionPerformed private void jButton24ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton24ActionPerformed try{ String sql = "INSERT INTO customer" +"(`Recipt_no`, `customer_name`, `customer_phone_no`, `order_date`, `Receive_date`, `sub_total`, `Vat_Amount`, `Total_amount`)" +"VALUES (?,?,?,?,?,?,?,?)"; con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/lootha","root",""); pst = (PreparedStatement) con.prepareStatement(sql); pst.setString(1,order_recept.getText()); pst.setString(2,customer_name.getText()); pst.setString(3,customer_phone.getText()); pst.setString(4,order_date.getText()); pst.setString(5,((JTextField)receive_date.getDateEditor().getUiComponent()).getText()); pst.setString(6,sub_total.getText()); pst.setString(7,jTextField2.getText()); pst.setString(8,total_amount.getText()); pst.executeUpdate(); JOptionPane.showMessageDialog(null, "inserted successfully"); } catch(SQLException | HeadlessException ex){ JOptionPane.showMessageDialog(null, ex); } showTableData(); }//GEN-LAST:event_jButton24ActionPerformed private void jButton28ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton28ActionPerformed try{ String sql = "UPDATE `customer` SET `Recipt_no`=?,`customer_name`=?,`customer_phone_no`=?,`order_date`=?,`Receive_date`=?,`sub_total`=?,`Vat_Amount`=?,`Total_amount`=? WHERE Recipt_no=?"; con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/lootha","root",""); pst = (PreparedStatement) con.prepareStatement(sql); pst.setString(1,order_recept.getText()); pst.setString(2,customer_name.getText()); pst.setString(3,customer_phone.getText()); pst.setString(4,order_date.getText()); pst.setString(5,((JTextField)receive_date.getDateEditor().getUiComponent()).getText()); pst.setString(6,sub_total.getText()); pst.setString(7,jTextField2.getText()); pst.setString(8,total_amount.getText()); pst.setString(9,order_recept.getText()); pst.executeUpdate(); JOptionPane.showMessageDialog(null, "updated successfully"); } catch(SQLException | HeadlessException ex){ JOptionPane.showMessageDialog(null, ex); } showTableData(); }//GEN-LAST:event_jButton28ActionPerformed private void jButton27ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton27ActionPerformed try{ String sql = "DELETE FROM `customer` WHERE `Recipt_no` = ?" ; con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/lootha","root",""); pst = (PreparedStatement) con.prepareStatement(sql); pst.setString(1,order_recept.getText()); pst.executeUpdate(); JOptionPane.showMessageDialog(null, "Deleted successfully"); } catch(SQLException | HeadlessException ex){ JOptionPane.showMessageDialog(null, ex); } showTableData(); }//GEN-LAST:event_jButton27ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Bill.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Bill.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Bill.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Bill.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Bill().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField advance_amt; private javax.swing.JTextField amount; private javax.swing.JTextField balance_amt; private javax.swing.JTextField customer_name; private javax.swing.JTextField customer_phone; private javax.swing.JTextField des; private javax.swing.JLabel iMessage; private javax.swing.JButton jButton1; private javax.swing.JButton jButton10; private javax.swing.JButton jButton11; private javax.swing.JButton jButton12; private javax.swing.JButton jButton13; private javax.swing.JButton jButton14; private javax.swing.JButton jButton15; private javax.swing.JButton jButton16; private javax.swing.JButton jButton17; private javax.swing.JButton jButton18; private javax.swing.JButton jButton19; private javax.swing.JButton jButton2; private javax.swing.JButton jButton20; private javax.swing.JButton jButton21; private javax.swing.JButton jButton22; private javax.swing.JButton jButton23; private javax.swing.JButton jButton24; private javax.swing.JButton jButton25; private javax.swing.JButton jButton26; private javax.swing.JButton jButton27; private javax.swing.JButton jButton28; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JButton jButton7; private javax.swing.JButton jButton8; private javax.swing.JButton jButton9; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel19; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField2; private javax.swing.JLabel l1; private javax.swing.JTextField order_date; private javax.swing.JTextField order_recept; private javax.swing.JTextField qty; private com.toedter.calendar.JDateChooser receive_date; private javax.swing.JTextField sub_total; private javax.swing.JTextField t1; private javax.swing.JTable tb1; private javax.swing.JTextField total_amount; // End of variables declaration//GEN-END:variables }
50.81512
193
0.633697
6979e39c5d2e582d5ec1302ee813ccf1e12bf43f
3,248
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shenyu.plugin.base.condition.strategy; import com.google.common.collect.Lists; import org.apache.shenyu.common.dto.ConditionData; import org.apache.shenyu.common.enums.MatchModeEnum; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.mock.http.server.reactive.MockServerHttpRequest; import org.springframework.mock.web.server.MockServerWebExchange; import org.springframework.web.server.ServerWebExchange; import java.util.List; /** * Test cases for MatchStrategyFactory. */ public final class MatchStrategyFactoryTest { private ServerWebExchange exchange; private List<ConditionData> conditionDataList; @Before public void setUp() { this.conditionDataList = Lists.newArrayListWithCapacity(2); ConditionData matchConditionData = new ConditionData(); matchConditionData.setOperator("match"); matchConditionData.setParamName("shenyu"); matchConditionData.setParamType("uri"); matchConditionData.setParamValue("/http/**"); ConditionData eqConditionData = new ConditionData(); eqConditionData.setOperator("="); eqConditionData.setParamName("shenyu"); eqConditionData.setParamType("uri"); eqConditionData.setParamValue("/http/test"); conditionDataList.add(matchConditionData); conditionDataList.add(eqConditionData); this.exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/http/shenyu") .build()); } @Test public void testNewInstance() { MatchStrategy andMatchStrategy = MatchStrategyFactory.newInstance(MatchModeEnum.AND.getCode()); Assert.assertEquals(andMatchStrategy.getClass(), AndMatchStrategy.class); MatchStrategy orMatchStrategy = MatchStrategyFactory.newInstance(MatchModeEnum.OR.getCode()); Assert.assertEquals(orMatchStrategy.getClass(), OrMatchStrategy.class); int nonExistCode = -1; MatchStrategy defaultMatchStrategy = MatchStrategyFactory.newInstance(nonExistCode); Assert.assertEquals(defaultMatchStrategy.getClass(), AndMatchStrategy.class); } @Test public void testMatch() { Assert.assertFalse(MatchStrategyFactory.match(MatchModeEnum.AND.getCode(), conditionDataList, exchange)); Assert.assertTrue(MatchStrategyFactory.match(MatchModeEnum.OR.getCode(), conditionDataList, exchange)); } }
41.113924
113
0.746613
ad20cde6d7ab5fcb968e949a6ba65f9a03447ad1
1,042
import java.util.Objects; public class StringComparison { public static void main(String[] args) { String s1 = "HELLO"; String s2 = "HELLO"; System.out.println("Different ways of comparing Strings in Java."); System.out.println(" Example 1 - Comparing objects using Objects class of java.util package: " + Objects.equals(s1, s2)); System.out.println(" Example 2 - Comparing strings using equals method: " + s1.equals(s2)); System.out.println(" Example 3 - Comparing strings using equalsIgnoreCase method: " + s1.equalsIgnoreCase(s2)); System.out.println(" Example 4 - Comparing strings using compareTo() method: " + s1.compareTo(s2)); System.out.println("\n"); System.out.println("Note: The '==' operand is also used to compare objects to check equality. " + "This operand checks if both the objects point to the same memory location or not."); System.out.print(" The '==' will give : "); System.out.println(s1 == s2); } }
41.68
129
0.646833
d719d14661376a488a3cbb69c462a534ea82418d
2,236
/* Copyright 2021 JD Project Authors. Licensed under Apache-2.0. Copyright 2019 The Vitess Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.jd.jdbc.key; public final class Bytes { // Compare returns an integer comparing two byte slices lexicographically. // The result will be 0 if a==b, -1 if a < b, and +1 if a > b. // A nil argument is equivalent to an empty slice. public static int compare(byte[] a, byte[] b) { if (null == a || a.length == 0) { return -1; } if (null == b || b.length == 0) { return 1; } int min = Math.min(a.length, b.length); for (int i = 0; i < min; i++) { int n = a[i] & 0xff; int m = b[i] & 0xff; if (n > m) { return 1; } else if (n < m) { return -1; } } return 0; } // Equal reports whether a and b // are the same length and contain the same bytes. // A nil argument is equivalent to an empty slice. public static boolean equal(byte[] a, byte[] b) { if (a == null || b == null || a.length != b.length) { return false; } for (int i = 0; i < a.length; i++) { int n = a[i] & 0xff; int m = b[i] & 0xff; if (n != m) { return false; } } return true; } public static byte[] decodeToByteArray(String str) { char[] charArray = str.toCharArray(); byte[] arr = new byte[charArray.length]; for (int i = 0; i < charArray.length; i++) { arr[i] = (byte) Integer.parseInt(String.valueOf(charArray[i])); } return arr; } }
31.055556
78
0.55814
d519aa1ab239b136ab0387c6d0c17de242f4c823
5,387
package com.exasol.releasedroid.adapter.communityportal; import static com.exasol.releasedroid.adapter.communityportal.CommunityPortalConstants.*; import static java.nio.charset.StandardCharsets.UTF_8; import java.io.IOException; import java.net.ProxySelector; import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import org.json.JSONObject; import com.exasol.errorreporting.ExaError; import com.exasol.releasedroid.usecases.PropertyReader; /** * Implements an adapter to interact with Exasol Community Portal via API. */ public class CommunityPortalAPIAdapter implements CommunityPortalGateway { private final PropertyReader propertyReader; /** * Create a new instance of {@link CommunityPortalAPIAdapter}. * * @param propertyReader property reader */ public CommunityPortalAPIAdapter(final PropertyReader propertyReader) { this.propertyReader = propertyReader; } @Override // [impl->dsn~create-new-release-announcement-on-exasol-community-portal~1] public String sendDraftPost(final CommunityPost communityPost) throws CommunityPortalException { final String token = getAuthenticationToken(); return createPost(CommunityPostConverter.toJson(communityPost), token); } private String getAuthenticationToken() throws CommunityPortalException { final HttpResponse<String> response = getAuthorizationResponse(); final var portalAuthorizationResponse = CommunityPortalAuthorizationResponse .createCommunityPortalAuthorizationResponse(response.body()); return getAuthenticationToken(portalAuthorizationResponse); } private String getAuthenticationToken(final CommunityPortalAuthorizationResponse portalAuthorizationResponse) throws CommunityPortalException { if (portalAuthorizationResponse.isStatusOk()) { return portalAuthorizationResponse.getToken() .orElseThrow(() -> new CommunityPortalException(ExaError.messageBuilder("E-RD-CP-1").message( "The Exasol Community Portal authentication token was not parsed correctly or missing.") .toString())); } else { throw new CommunityPortalException(ExaError.messageBuilder("E-RD-CP-2").message("{{message}}") .parameter("message", portalAuthorizationResponse.getErrorMessage().orElse("Error message is missing.")) .toString()); } } private HttpResponse<String> getAuthorizationResponse() throws CommunityPortalException { final HttpRequest request = HttpRequest.newBuilder() // .uri(URI.create(EXASOL_COMMUNITY_PORTAL_URL + "restapi/vc/authentication/sessions/login")) // .header("Content-Type", "application/x-www-form-urlencoded ") // .POST(credentialsFormData()) // .build(); return sendRequest(request); } private HttpResponse<String> sendRequest(final HttpRequest request) throws CommunityPortalException { final HttpClient build = HttpClient.newBuilder().proxy(ProxySelector.getDefault()).build(); try { final HttpResponse<String> response = build.send(request, HttpResponse.BodyHandlers.ofString()); validateResponse(response); return response; } catch (final IOException | InterruptedException exception) { Thread.currentThread().interrupt(); throw new CommunityPortalException(exception); } } private String createPost(final String post, final String token) throws CommunityPortalException { final HttpRequest request = HttpRequest.newBuilder() // .header("li-api-session-key", token) // .uri(URI.create(EXASOL_COMMUNITY_PORTAL_URL + "api/2.0/messages")) // .POST(HttpRequest.BodyPublishers.ofString(post)) // .build(); final HttpResponse<String> response = sendRequest(request); return extractPostUrl(response.body()); } private String extractPostUrl(final String body) { return new JSONObject(body).getJSONObject("data").getString("view_href"); } private void validateResponse(final HttpResponse<String> response) throws CommunityPortalException { if (response.statusCode() != 200) { throw new CommunityPortalException(ExaError.messageBuilder("E-RD-CP-4") // .message("The response from the Exasol Community Portal had a bad status: {{statusCode}}.", response.statusCode()) // .toString()); } } private HttpRequest.BodyPublisher credentialsFormData() { final String username = this.propertyReader.readProperty(COMMUNITY_USERNAME_KEY, false); final String password = this.propertyReader.readProperty(COMMUNITY_PASSWORD_KEY, true); final String formData = encode("user.login") + "=" + encode(username) // + "&" + encode("user.password") + "=" + encode(password); return HttpRequest.BodyPublishers.ofString(formData); } private String encode(final String string) { return URLEncoder.encode(string, UTF_8); } }
45.652542
116
0.684425
19ff4b57e84b86b36f770543b977e9b78b3f2403
509
package com.woniuxy.map.basic; import java.util.Map.Entry; import java.util.TreeMap; public class TreeTest { public static void main(String[] args) { TreeMapDemo tmd = new TreeMapDemo(); TreeMap<Integer, String> tm = tmd.add(); tmd.get(tm); System.out.println("-------------"); tm.remove(1); tmd.get(tm); System.out.println("--------------"); Integer f = tm.firstKey(); System.out.println(f); System.out.println("--------------"); Entry<Integer, String> ef = tm.firstEntry(); } }
23.136364
46
0.614931
27d2c6a80347acc2a2fe248b9e7ee25f5dbc18c7
419
package com.redhat.springmusic.repositories.jpa; import org.springframework.context.annotation.Profile; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.redhat.springmusic.domain.jpa.Album; @Repository @Profile("!mongodb & !redis") public interface AlbumRepository extends JpaRepository<Album, String>, EntityOperationsRepository<Album> { }
29.928571
106
0.832936
d80b6465ea7a6d2c5536d4ea718dd5806b31a6cc
6,823
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package connection; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import passagens_aereas.Voo; /** * * @author lucas_nuze0yo */ public class VooCRUD { private Connection con = null; public VooCRUD() { con = Conexao.getConexao(); } public void inserir(Voo voo) { PreparedStatement stmt = null; String sql = "insert into voo (origem, destino, aviao, data, ass_c, ass_esp, preco_c, preco_e, rota,hora) VALUES(?,?,?,?,?,?,?,?,?,?)"; try { stmt = con.prepareStatement(sql); stmt.setString(1, voo.getOrigem()); stmt.setString(2, voo.getDestino()); stmt.setString(3, voo.getAviao()); stmt.setDate(4, voo.getData()); stmt.setInt(5, voo.getAss_c()); stmt.setInt(6, voo.getAss_e()); stmt.setFloat(7, voo.getPreco_c()); stmt.setFloat(8, voo.getPreco_e()); stmt.setInt(9, voo.getRota()); stmt.setString(10, voo.getHora()); stmt.executeUpdate(); } catch (SQLException ex) { System.err.println("Erro: " + ex); } finally { Conexao.fecharConexao(con, stmt); } } public boolean atualizar(Voo voo, int idOld) { PreparedStatement stmt = null; String sql = "update voo set origem = ?, destino = ?, aviao = ?, data = ?, ass_c = ?, ass_esp = ?, preco_c = ?, preco_e = ?, rota= ? ,hora = ? where id_voo = ?"; try { stmt = con.prepareStatement(sql); stmt.setString(1, voo.getOrigem()); stmt.setString(2, voo.getDestino()); stmt.setString(3, voo.getAviao()); stmt.setDate(4, voo.getData()); stmt.setInt(5, voo.getAss_c()); stmt.setInt(6, voo.getAss_e()); stmt.setFloat(7, voo.getPreco_c()); stmt.setFloat(8, voo.getPreco_e()); stmt.setInt(9, voo.getRota()); stmt.setString(10, voo.getHora()); stmt.setInt(11, idOld); stmt.executeUpdate(); return true; } catch (SQLException ex) { System.err.println("Erro: " + ex); return false; } finally { Conexao.fecharConexao(con, stmt); } } public void exclusao(int id) { PreparedStatement stmt = null; String sql = "delete from voo where id_voo = ?"; try { stmt = con.prepareStatement(sql); stmt.setInt(1, id); stmt.executeUpdate(); } catch (SQLException ex) { System.err.println("Erro: " + ex); } finally { Conexao.fecharConexao(con, stmt); } } public void vooIncrementaC(int id) { PreparedStatement stmt = null; String sql = "update voo set ass_c = ass_c + 1 where id_voo = ?"; try { stmt = con.prepareStatement(sql); stmt.setInt(1, id); stmt.executeUpdate(); } catch (SQLException ex) { System.err.println("Erro: " + ex); } finally { Conexao.fecharConexao(con, stmt); } } public void vooDecrementaC(int id) { PreparedStatement stmt = null; String sql = "update voo set ass_c = ass_c - 1 where id_voo = ?"; try { stmt = con.prepareStatement(sql); stmt.setInt(1, id); stmt.executeUpdate(); } catch (SQLException ex) { System.err.println("Erro: " + ex); } finally { Conexao.fecharConexao(con, stmt); } } public void vooIncrementaE(int id) { PreparedStatement stmt = null; String sql = "update voo set ass_esp = ass_esp + 1 where id_voo = ?"; try { stmt = con.prepareStatement(sql); stmt.setInt(1, id); stmt.executeUpdate(); } catch (SQLException ex) { System.err.println("Erro: " + ex); } finally { Conexao.fecharConexao(con, stmt); } } public void vooDecrementaE(int id) { PreparedStatement stmt = null; String sql = "update voo set ass_esp = ass_esp - 1 where id_voo = ?"; try { stmt = con.prepareStatement(sql); stmt.setInt(1, id); stmt.executeUpdate(); } catch (SQLException ex) { System.err.println("Erro: " + ex); } finally { Conexao.fecharConexao(con, stmt); } } public List<Voo> buscaTudo() { List<Voo> voos = new ArrayList<>(); String sql = "select * from voo"; PreparedStatement stmt = null; ResultSet rs; try { stmt = con.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { Voo voo = new Voo(); voo.setId(rs.getInt("id_voo")); voo.setRota(rs.getInt("rota")); voo.setAviao(rs.getString("aviao")); voo.setData(rs.getDate("data")); voo.setAss_c(rs.getInt("ass_c")); voo.setAss_e(rs.getInt("ass_esp")); voo.setPreco_c(rs.getFloat("preco_c")); voo.setPreco_e(rs.getFloat("preco_e")); voo.setOrigem(rs.getString("origem")); voo.setDestino(rs.getString("destino")); voo.setHora(rs.getString("hora")); voos.add(voo); } } catch (SQLException ex) { Logger.getLogger(VooCRUD.class.getName()).log(Level.SEVERE, null, ex); } finally { Conexao.fecharConexao(con, stmt); } return voos; } public List<Voo> procuraAvioesUtilizados(java.sql.Date data) { List<Voo> voos = new ArrayList<>(); String sql = "select aviao from voo where data = ?"; PreparedStatement stmt = null; ResultSet rs; try { stmt = con.prepareStatement(sql); stmt.setDate(1, (java.sql.Date) data); rs = stmt.executeQuery(); while (rs.next()) { Voo voo = new Voo(); voo.setAviao(rs.getString("aviao")); voos.add(voo); } } catch (SQLException ex) { Logger.getLogger(VooCRUD.class.getName()).log(Level.SEVERE, null, ex); } finally { Conexao.fecharConexao(con, stmt); } return voos; } }
33.777228
169
0.534222
8766f41c35adaedf6f92d0d22d5bedccb25e44da
3,310
/* The MIT License Copyright (c) 2016-2020 kong <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.tenio.network.netty; import com.tenio.configuration.BaseConfiguration; import com.tenio.configuration.constant.LogicEvent; import com.tenio.event.EventManager; import com.tenio.network.Connection; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; /** * Use <a href="https://netty.io/">Netty</a> to handle message. Base on the * messages' content. You can handle your own logic here. * * @author kong * */ public abstract class BaseNettyHandler extends ChannelInboundHandlerAdapter { /** * Retrieve a connection by its channel * * @param channel, see {@link Channel} * @return a connection */ protected Connection _getConnection(Channel channel) { return channel.attr(NettyConnection.KEY_THIS).get(); } /** * When a client is disconnected from your server for any reason, you can handle * it in this event * * @param ctx the channel, see {@link ChannelHandlerContext} * @param keepPlayerOnDisconnect this value can be configured in your * configurations, see {@link BaseConfiguration}. * If the value is set to true, when the client is * disconnected, its player can be held for an * interval time (you can configure this interval * time in your configurations) */ protected void _channelInactive(ChannelHandlerContext ctx, boolean keepPlayerOnDisconnect) { // get the connection first var connection = _getConnection(ctx.channel()); EventManager.getLogic().emit(LogicEvent.CONNECTION_CLOSE, connection, keepPlayerOnDisconnect); connection = null; } /** * Record the exceptions * * @param ctx the channel, see {@link ChannelHandlerContext} * @param cause the exception will occur */ protected void _exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // get the connection first var connection = _getConnection(ctx.channel()); EventManager.getLogic().emit(LogicEvent.CONNECTION_EXCEPTION, ctx.channel().id().asLongText(), connection, cause); } }
38.045977
108
0.727795
6af03f2102ef7b50592cb8d902482997a7a55296
22,153
class c9 { public boolean[][] lyzn_Z3FQSs; public mJy_kpR7_q6[][] p4gqCjpbi () { boolean Poduf_ccWcX6 = -ZiaZMoo().VajrxJ2JpT(); void[] o; int Oqb = true.rSunTjWw = null[ !true.Tc]; R1Y[ !!true[ !--ORi8CcWk[ !-false[ this[ !!( --true.qe1aO1f())._9jDiMao()]]]]]; !nuehwpoz4A9IUb().tFX2ov(); int[] s7N47P9KtPg9d0; while ( 7[ !!!new ceO().I]) if ( A.mKoKB()) { while ( new u[ X().C9TOFHfO][ new wa_7().QlE6]) ; } while ( null.TtS3RKz_5W) { while ( false[ !( !--f3u[ true[ ( !-this.IF)[ !-( --!-46837798.fzExi1())[ null.mKIMn29ye8QU]]]])[ !-!ZVYVGM().b9oo2Id_L()]]) while ( ( -!false.T2l9z)._A3H()) false[ new mD5pZphlPb[ !!!null[ !--Smr[ false.wm()]]].vDvV8hrBC()]; } int[][] CWl8m; int[] wmDUdxNpB; true.Igo4rihEa3V6(); while ( -null.O4FEu0nnk()) { ; } { void[][] y7lq; if ( hB.cQiQ6ChSPwJuSA()) ; return; { ; } } boolean[][][][][][][][][] icRwKQo; } } class R { } class WBp { public int YSMEBpoh1lZ4 (int[][][][][][][][][] Cmp, s5yEw[] bI) { int[] eOT6Y; ; int[] u; true.P_; } public boolean PDq (int kyuket899FTb, boolean[][] V2BxHbA, int[][][] i) throws HZWCIxNxPrmZC { C J42 = !new int[ !new int[ JKORMu().pc2QRqZhmzN01()].iVjqC2pSPYwfn()].DReg6UqMt() = -!this.yeIai(); ; return; if ( -!-this.eZ()) if ( KtqsnAO.b8PH6Zd3CC) { ; }else { ukAc9SfSIZ6HkL[] IRjP4d_4GQO; } boolean[] UQJbRN4; void Q2Y; -new int[ new zJjXId()[ false._zEohp_wKsMzT()]].j_j6u9g; ; boolean[] UweO6O8eJy1 = -!new e7Wt5BEuPozmb3().p = -RJbBg7KbS()[ 4236[ new eNJI().g_()]]; if ( new zYzPSTjRcFZ5().G3EIa) ;else if ( mjZO.r07VypUY_4()) if ( !tQQGEuy2MPYG().NeuzW7wkfVSduU) ; boolean[][] BS8BvX; { ; void[] KD53p9ksuzsygJ; boolean CBCvdR; void c5_gzQHSlRixR6; if ( !!( new boolean[ -null[ !PDypQeH_().MzaK()]][ new Qc5().iY2fga2m1qg]).Y9rtlYhZz1) while ( !!( true[ null.uQy()]).GdkFu) while ( ( !-ksytaIz9UW().M4zqG).ZNV07gipOEb()) while ( null.HM()) { return; } return; yMuGDLXP[] msy; boolean LAxOd; if ( true.j) ; true.UilLzXSD6kfWu2(); { return; } int[] u; while ( 3887119.Hl()) { return; } xY7h7m33[][] _ZPq; int[] MOPVJF2IJu4; { lvtTi YMRK; } while ( ( ( -!new muVJjI3UNQFLW().Bi7())[ !new OS().e5YbMpfaW]).J7PJ92) return; { int[][][][] yeUJ; } int[][][] C9XSnuXvobeS; } void[][] d14N; { { return; } } xfJ4t Ekm40 = -aAYBq().slHwLMQooIJHKg(); hcR94dvLc QZ = true[ false[ 1214[ LSCxBE().AzISWw7JTMyZ13]]]; xyV3SEuB2i h7vN8ETU = !false[ this[ !1805447[ new Aque().w2r_eG]]] = this[ !-true.ZmlYaFz1Uo]; return; } public static void a9L (String[] YlUmW) { void BYxdcBywxhw9ep; int[][][] svNQ = !new ku().oi(); while ( this.o9z8vinX15TtK()) return; OCwjPZyd s2uTjNWzmJM7; return; ih5ng0Agzu[] vB4HRxz2jNfosa; return null[ null.wjQ()]; mYXX7 tM = !false[ new int[ -this.h6I()].zpbPEYWMvi()]; int XnpmDuM; boolean[][] Z; } public void C4XACwEfxEFt (int UFrE_6YCCV, int jqba4tuxzTEZ, boolean[] hzfb2KT_k7, int[][] BcOo) throws zZXLhIRMxu5 { return !true.hI(); } public void ykU6f4CEgU () { void ltJB = -myJdK[ !----!this.Tfo2ROUOLg] = null.L7p3gws1GkH; if ( this.OfLTB) { return; }else false.fluYStPFK7_; boolean[][] fU8UDhg89GDsT = -uY6YhqFNu6()[ -this.YIX()]; ; ( -!wm().mYq3B3yRVfy)[ !194715710[ !66307[ ( -!false[ 11.z9Yr04s0alyL0])[ !--!!5386662.UZhn()]]]]; { ; if ( !new int[ !!( -BVkz0aq8RMW0E()[ new ML().dcTsYgU]).UCB()].GGEVnN3kjsHYx) ; { return; } ; y4YlKLGZk_X[] awxxsT; boolean DpxWJ_y; void[][] o; int imb7zGSKaMC; void[][][][][] dE3; LWH Kz92JZECrYthG; ; if ( -( !p_cW.vrcqb_6M())[ !T.Kdmh()]) ; return; } boolean[][][][] iQVVqkWAd5Ym; void[][][][][] Lztp = true.GqY7X(); Kdw No2LKcG = new uEAzr4uAJMqGVh().gbJqNTAGugKZfO() = !---635066134.l7k4(); boolean GCA6WqZ3nb5; void[] VzlZHzT_D; if ( true[ -( this.RVHmgTC)[ !zc().rKoHbgQJ7()]]) while ( false[ this.RXhHe8kt]) false.pyco7gsky8(); ; int H7mtD_S = -x2().zdxSYFZQv(); if ( !073247974.CiaQZBC()) { void[][] xuq3; } int[] fM5k = false[ this[ ( !!true.EH1itY())[ !this[ null.pAJHD_e]]]] = --!bBE0j3WZfS().IcIsgCI3nZzcD; F9b[] hi3yDaX = !!new boolean[ -( false[ true.f5JymeSFoOf()])[ -new fAz4tTLtA().D54na2xDULJb]].YfK2dnxvnXj = new boolean[ new rHpJ241fp_()[ -null[ -null.XF6zKiP]]].hosDIcjW(); } public cDD6[][] kF (boolean _Mj, int[][][] Rkl7ij, boolean t, boolean[][][] mAamvLX3, int[] kIXW4DiN, int[][][][] mSh_RJN9OVblN) throws qqPLfl { !--!( null.XjT_lOARN1cA()).ZP8k3Sk4(); void uVbwD85hHx; while ( this[ -new zdU[ !false.SWQRY_].YDC05()]) if ( !-!4220[ false[ ( true[ new void[ !new A().PoxS0w()][ !Uj[ null.QbGBD()]]]).BzlNzgTsiV]]) if ( -null.GTHi) return; ; false.yjqY75xBjise(); boolean[] Cf6dKoSo73KfEI; void[] HH4aJ0TfD; return; if ( -!KMC.I3j1wmZ8qkhzIf) { int wmznziQLz; }else if ( !null[ XXnMZzv6bAhRKE.BuD]) { C6[] LsjviFi3fdlRT; } } } class lGP_Y { public void SJisEwj; public void gvUZlDY_G; public void[] mkZx () { -null[ ---null.xAIx_bhTSxDx]; void avYTKwQqof9Do; ; ixNJ4kwxDJ[][] sRUnoRoZSc_; ib[][][][][] PDAjSC; JJa7 FXd; while ( -!!!-UYhj9q.gnC5W) { Yxr4 YMY8NA5_2; } void[] Gfq; ; void[][][] YahtAr = WggHTiZz.oQWnO() = -new void[ gtB7ZjHjYuIsQ[ new UWDCUQ0w[ tpT.Cow33Rdg0nyjU].mz3iwpmzG()]][ !KNA5QvfUHvyp()[ -!new void[ -!-O.uZau2WNt()].oIIvIr2()]]; fd GINl; msBz QEl; } public static void wiTOuaFx8s4M (String[] tneXCIvMQ7e) { boolean Vn_Iv; boolean[] NuGu = --null.whRZSIz() = !w8l2j()[ new MPZx4fS2[ ( --this.fAlzrUJ()).lYjv4NK76V2nG].b_TdTj]; void[][] v5Ahc6robezb = new k()[ --false.H0IjJzSMKvrC()] = !!!32.lI(); } public int aeI; public int IEOBOzOCn2tKcb (oBCTr9hHoCc[] PdlQT, int R7Zxkb, int[][][][][] xWuf) throws XVr77sUy1L4HR5 { { ; while ( ( -!!!!!false[ -!true.Gwc3Kcd8qxIhEC]).C) if ( 134[ !FsEGsxyohR.LbZpdLMmegL()]) !this[ this.S6g]; boolean[] AQijXX_8P3rI; if ( -new int[ -this.qLYQ()].Cv3dTxu()) return; ; YN0NX o8; return; { if ( new J9OMx9qltx().SWjZz73p7k) ; } int[] B2x7xFe; while ( p7xmPMBf0oou().aArColM()) return; ; if ( ( !this.AZCp9nrJ0_hA_())[ this.kPMod1bgxCi]) { { return; } } If2yGzimRQhUe2 RdtjUmIB; lN7HDYrsPIrzkY BwW7Mi68X; while ( !new sdsKv8M30()[ 63517985.Uz8jqqIOvs0()]) { hi[][] HA_c5RZII; } { while ( !---2.SwMO4_huLb()) return; } ; if ( !!-177268816[ -true[ null[ -U1.zA6tzjctMai()]]]) return; boolean jTYjb6Jzbc; } if ( !--this.dexfBfC) if ( KLMTusTKFq().TV) if ( --!new PoHMzqen[ -true.gkrj1yvdb26].Qa) return;else return; } public int[][] Jk2xtmSGttDSW (void UXhbj9Lp, void ZO5TATTM2, void[] HIx4O6Q, int BSiytK1UU9, boolean[] SUXBD) throws tKGYFN4 { new void[ i6CPXcGbDT1BAE().Fhk()].Z3s3U4tg6; while ( this.xulMSOm()) new V6D()[ fIrZ0cED.INERyfdiijY]; ; int[][] aUs7G641; int[] jolGL = !!!( new boolean[ agJSZ[ !new dibYZH().byQhvhHPdPy]].cEbH_4A2()).kRCb3OdNSmktL() = vcX1w2hDjeYlk[ !124569569.EzSVshTAxq()]; fpx[] krloby2zD6YCd = !!!73297.cUELBLMP(); F0NnpLQ7ye5[][] A5_X8c = new uCOP7XyLcXSAUD[ false.EYeDkPgQ37Y6oG].BDOm = !!-this[ -!!-true.GwHylE2gr6R3()]; { ; void[][][] VVmWQLRs; while ( -!false[ null[ !mxyhfY3Yb().IIjSVqfx()]]) ; void[][][] YrtB; return; ; prRmtR W; int z54AhgDG; GYrz9rCC7 Kn0RjxI3Mt; int OwCVKr4jwknL0i; boolean dyCYj9a; void[][][][] yPMbepU48O; ( new ZMWLwrP0f().Ciod4PPS())[ -( this.GqP).M2yqNa9lzxZ0W]; int[][][][][] YTP_jTlxbEB; this.p63BlrVL9zU; !-new IE12znCo().EtT; ; int[] AAueyr; } if ( null.iHIgu97bXnR) !!ngsSF.hmbNaCPnTSOS2v(); return !--true.qs5_m; } public void[] GxsVjMm () throws hkYmkrkg1etb3h { if ( this[ -!-( !-!!--( !297.KzemoU()).V1ZYc0jP).zaMzzXn]) while ( !-!this.Ym7aSkHBf) null[ null.R1Tc54x0bHX];else while ( -!EPVWUaO9gmlJB.EdOHJ) return; if ( EVZ()[ !-T8b().MVBtKM9EV]) return; if ( !-88[ null.pBxH9x2wosYYU]) return;else if ( !-fj()[ 910[ 3[ 105324358.ITcKlm]]]) if ( !lDIlBZt2XHOS().R6ERteDY) ; void Z6G_H5r5I = !-new H().IWwZT() = !BYcGYTOYm3e00s[ !-!( new boolean[ this.Z()][ null.MKua])[ -!!RWbS.zdJHnbc_IW()]]; Gda57R _3E1gmPaa3; int Iwu7b_gdK7q1Fh = 564.ACh3KyvM() = -true.EUi30QK4SA(); !-( j9NajanC().kAoXc()).SyWGWx3l(); null.xGO5; void[][] QfWcxxH = qK[ !!true[ rM20gpLA()[ !( !-this[ -!--null.gZVkj()]).ZLLYowD4t5Py]]] = !!!false[ !-KP0if1yQpEBCX().V2Mxv()]; } public void y8zd (void[][] zHpcVsAUK0, VR1w jS5Y7E) throws mEU821JaLFbFZK { boolean uU9 = !-!-( -T0NSP().NifFvEhPdIyJo)[ true[ !true.Raa()]]; while ( !-false.CNOo2d1HXi()) return; if ( !!new boolean[ -!876083405[ --new boolean[ new void[ this.GnzWr].JSqUGlb].EjWe7iPHhSJHj()]].b9pZbYL_S7y()) { ; } { -null.Bnh6e(); boolean IrzwWdm; void[] TxWpsgx7FlV; int[] q; { int fsIhkVOjqyW; } ; void[] PX70; if ( -!new YJ[ -this[ --!-!!-!-!false.s3_K]][ !Ob4FplQmuavO()._dr_]) ; void FpoEaZNH2; KcqF[][][] itNyj; return; { while ( null[ new I().JZaN5U2t()]) null.r; } ; return; if ( rvgLZRx4ZhyU[ fnbpktgkP()[ !---X49k99dB9k_U.iHsb5dR]]) ; boolean da6n7hmB4BtvZp; } { if ( skjttTJc0()[ !( !!!!-!--!l66.rPIo_g8DIQHo87())[ !!A().aMSkjKMA]]) !new fnQ1y0fUaT[ m()[ 059128[ new void[ exxLs66().WPCDr86W].ofNvIxZ]]].ZcIL; while ( dSVme7().wck6L40AS3gO()) return; nQQpH1[][] fn9FKo; return; { if ( -true.oEWLsSq) if ( !this.AGdNB) ; } ; int[][] _k0BgVI; new qgOlc_MD7tx[ -!-!!-!!!----!!-( !null[ !j2m1sUH().yI7Kj0QX8M]).HgNa_JdP()].NRk(); { while ( new xZMoEtj6FvYC()[ new void[ --!null.Ft9].LdwkX6S()]) !true[ W3Z72lg[ new Kt_[ -!!!new oYlcq().mSz()].A]]; } int T4tc; return; { rCM0Bx1SV3p0 yg2YAOjwk86; } while ( new boolean[ !new void[ !--i_().s7yHQVb].JblHyQmPNww()].kOlKWWV_0n) if ( !null[ !-false.fsobirLlmlc()]) { int[][][][][] s6dV5kxOCBLE2N; } int[][] FtnUn; } return jZJMC8O5owXvH.xbBtB1k; void tGRd9TYl0Na = P().lIG = true.ld98b_zq; return 523[ ( null[ --this.dWjz_()]).Ilw2VJ1()]; ; boolean[][] QJEFM4BWaAFcD = !new mCh9v4[ Wmws.mXa3ykH3iHJM][ McvkXTEV1PS().MZzOZh2eWP]; this.P17UBu7xvd; if ( CWgp.VurHLQP6nC()) return; while ( true.Q6B) return; FmXsoP IvN = this.JbOf8m = -hEU4CMvE.zltHp6b5GDKRn; void[][][][] Vb7gLVB = true[ 949955049.neNmiuRsLf2tn1()] = Yer().rkUuYOA09CCh8j; Prz3PBrGqQU[] D8txRFayepvcKD; void RP2rVQIupLrejr; boolean[] XVqblf6MQ_9qU4; } public static void CxQWxT (String[] A) throws iRgRp8cX { ; } } class AJx { } class u { public int[] a () throws E9JtnM5d { int zR0Vamy0WBDTs; while ( !( !null.ZSMBhYxHG3k9E()).Alg()) ; -null.dbyKuXDGO5ffZq; X6CO4Sg_Ex[][] BlUpPUeABZik; ; if ( new lAmGonH()[ Gn()[ b8XEfXq9HhL().qeK7qfxU9H54()]]) { { if ( -false.DjRwILCfJd) !!1349791.HGmS36K; } } aZ3ddamFF_6hT vFY = --this.wPhrUByi564() = 590522272[ XUd_w8dAtp()[ -null[ BTm6Jg03()[ -!this.X()]]]]; } public static void SiLPdK (String[] IFrWeCL1wP) throws WYAMaSr0 { if ( new EgYI99aCxhZ()[ -false.rc5()]) ;else ; ; } public int[] Q2iI; public static void aKPKNr6bHBwv (String[] zQt6x2t8zol5) { return; void[] p = --!-new int[ !-!722185167.pnAqo][ -VK_ZnR().TbgyuFuWDPz]; ; int U9An6CGY1sBS; int AU8gzjQl = !35.VVWzfQpEFhAA = ( !-true[ new URG7TcLk().agQls94zk9B])[ !41.s()]; { if ( !-new eT().r3_6) { Y1[][][] u_g; } { return; } if ( --KWqhmJnv().DCH()) if ( ---null[ new rWbIm()[ false.vNufcSfd()]]) return; boolean m58UXw; ; int[][][][] p44JGTv; if ( -!false.A6VEE4FJU()) -!!-EO0F1fybBtup_k().uG7JdLg; int mVbcNe; tgbsSG76A.comi6haNXXdOn(); !-true[ 92.MENMDtPV844pX]; while ( -!null.OGZ()) return; } void[] g5DtoM = true[ false.T] = !( ( 739[ --IPUYZ7oFm7qsf().ZgMZHEl_]).eEXmV).EF9BjPyvJ(); boolean[] hpPP = true[ !!ggL7qLXq299p[ -!!!null.nIirg0]] = --!!null[ true.akxJQB()]; boolean[][] D; int Zhlo; int FOqKCW_vgl; int iJ = null[ new rK8487().YZc4VHPf()] = -HziA_E9FclR0N()[ null.V79X()]; { void[] SqgQU; return; return; ; } bxMpItG[][][][] aeZ6; } public static void x (String[] BmOpDXg) { int gW8l; wpcm Fhdn = !null.bx(); !new fRfolp()[ -false[ !false[ false[ !!!6882[ ( this.GLwpuOuOj40bM)[ !this.R]]]]]]; { true[ !-this.c36()]; ; } return !new IyhttELX2().V_DzuGB; return; boolean[][] Ksbfq85hn; --this.eq02ax4A8Eou(); while ( -T368WqMu().rheaPPeyRMB) ; int o71BXBdUAGI6; if ( --new sl0Xd().W6Fj()) if ( null.VjQLCPdpn29()) ; boolean[][] gVgfRCo2CIEJ = -null[ TGi5SUAJvZ()[ null[ false.iKWxhX0WeAaBL]]] = 5211795.dzqhltes(); void[] vN7lJs; int TvBAze6Aj; !-new void[ 2689712.cOphQ()][ ea.fP()]; if ( !!!!-new int[ 3983582[ !y13jQm1WnZHm().QEo1y0()]][ false.pUbuBZod()]) new VW().mbtyQPH();else if ( -!null.Ko) return; } public boolean pmprlyRM39u6Vq (void B8b_J, void YAM, o0mlFXBbg4r4t WxvUwQT, boolean[] ha) { boolean[][][][] A2e85r; while ( new ym5waYnb()[ this.lpxqKaf4SMTql()]) if ( --new int[ !new OPWvDxn4DDQqR0().kgr1hYa0ssZg()].xgxK3uL()) return; void[][][] p; { { return; } { return; } return; int[][][][] vds_M; return; return; wMCa[][] fvl63dXU; int[][][] FOz7R44W; int RwI_EglVcFB7FM; void jra64rQ; if ( mGP.gJ_WiH1Hxz) if ( !-null.qk()) !this.Ghgb2S; return; return; if ( ---null.LYTIiC) !true[ ( Wr().cuU9vv()).SPF9k()]; boolean swsulEkwD; } if ( -false.JZRJBQjHH08hi0()) return;else return; { if ( -false[ new kZuIZB6().as8YWJUNmoH()]) while ( null[ 11[ du4lEtEz().L4Te1()]]) { return; } void[] m; void DLkponxR923I; return; { return; } !!-( null[ 372.Z()]).BHMQjrOOvvy_; void[][] i5Q4A; Co4OjuH1_VK AISlaVl; int[] v8H; void pfQ0g1n7iIP; boolean jD8Mqwcz9C3; ; boolean[] szlQ22; int[][] Jd4; hli55 aazegRQCm; int izsedhy8; RZJX6G[][] N1YqfxQjvkJXC; boolean[] Iooe; void[] W; void r1QR; } int A = -new cCt_szjUHoW8Hc().f_rpNRiG = true.ragJ46(); { int[][] ypuDRNYcBu; void[] LwoK1o; -375007161.lpVxwK(); if ( 65784.GdMgyg7A) if ( !-this.ABcB()) null.n_rn4Us8M; boolean[] bGRdc; HQlzVKL WMZto; !( !new void[ -!true[ this[ -!-null.GKtiCqYByEg]]].sSXHkZaAZ())[ !new PvDLz().ivrs1Ldb]; boolean wu9ZZwVdS9; return; int[] zNJBQsM0u; boolean[] KuFQ; boolean IxQFaa64Mkoou6; return; QkdEQ_ArH8[][][][] YzCa; ( true[ -false.Xu3DqYq()])[ false.z]; ; int JJuiJu; return; if ( ( --!false[ false[ new ONC[ !( -!!!this[ !new c[ null.zO5dzayPf()][ this._jr]])[ false.h3()]].AbWXvojEme9gp]])[ 766008.VI7RClIk6Ko_DT]) return; } ; ; return -GSvvmIE()._orx(); return; ; int WzW92H; int[][][][] UNwEjdwXZ; if ( new ke6bJmZDlZ87().Dn5l0T()) while ( !-906070[ !-!!new Qz2kji().Rt1()]) if ( ( !false[ --!new void[ new int[ !null.iBDxi1RqK()].FdBeAuFy].SNBVnqF5qWO()]).H28BBGL08x) ;else return; } public int V_BVdwhs1Nhg; public int[][][][] J (TzDksxHcnq R6mTQD2x, Ke7wUy gwypL8QS, OP u51DJyA) { { _ss4shps[] CY; EGU5ouahy FNxnzGiu; void g; int RN9Tp; int FBY9aYsn; ; if ( -new SFukMWvcP().WuhxyCT0ZR) !!-new r4()[ true[ new nILBtnMswUhHND().H_pSJL()]]; int[][] cqWGxZLkt; int[] Hv2ZFUkcAH; IV mxGceuoM; !-null.QtTJi0pI8X3(); int[] AJ4Lm3LfnQZ; } ; YESXf V = true[ -!-!!this[ -!!--( -true[ ( kpnA5IM[ --AWtronvveJ1obr().iWKH]).qmJEoC3]).MSlATbhbAcZz()]]; G().EwSDqFfRB9rLm(); if ( false[ 6945[ !new hBZvf_qs5ma().O2jW]]) while ( -W_d4Cn_ZgSxFwB().rri11rs6OE4M) while ( null.__tJ()) if ( -!new QXv()[ new Dsc().ueXVFFpI]) if ( false.wXieGO) return;else ; { { p W_gT1; } boolean uKxTKKzv92SgE; ; ; void[][][][] d; void MHNYa6dGq5Stwa; void z7_C; return; boolean cFfiSlmPZi8; while ( false.VrsgvozyG) new KfPsms()[ this[ F_[ ---!-!-false.mT3IQ0vN]]]; while ( true.DLT9Uh_tw()) ; while ( -true.P3AUT()) --!!-null.XWUGJuw; } } public static void ocyuC3_tXT (String[] Yg3eoQm) { boolean H29pSpVU; ( -c().F4SGE6a8())[ -new void[ this[ ( !-!-( jM2l.qNdbo2sOL78t)[ -9733.RghX5LU]).MOL_Snnc1wWfeg]].jkzG7()]; if ( mCGI()[ this.xvy]) OTKx6OPoR0NhFK().X1CklC; while ( null.OaK33OxuwwF) new G4dvBk7F().SUMPDKJ(); void O = false.hPsvt70fzym(); N40lbw g = this.oNbvCB() = !!false[ --this[ !( !!-this[ --( 098[ 09914.fS1CCSsY])[ -bRTvJlyDSD5rtP()[ new SmIe3VZ().HHlZbRqTdB80NW]]]).lU_EwC7RDjw]]; --!!-true.AOvn; int[] yN7gSqU0osA; int _e8guUDGmYi = true.qrSDgF7nrM = at2[ !--RHFG_().fKjGI]; { int C0u2wrq0t6Zf; boolean U8eOGDT; int[][] CE19MFzO5Zpy; void i30n2OC; int[][][] qLIjnsrt4plHFL; int[][][][][][] r4lpF; return; int dW3hDCZ3; I1z42[][][][] Kw8L; { while ( this.FN) ; } } return ---false.aGxmOZw(); while ( ( ( new NBlV4Rm9[ null[ !true.KdHaNBYaD]].SJ4ZYwcTfU_Cs())[ this[ wkW8dK.WQWQLpd()]])[ t38YM5()[ !null[ !-!!null[ gqHOWB[ Io0Tyt.TSF9Pm9ZngC]]]]]) while ( ---FMGSMmBIniXS().NZ7DJ0poLzhf71) if ( !true.hwI0dwo) new G38Gosg().miHyq2CUb(); int Juat = --!false.ARI_5PUB8phh2r; boolean[][] Ip7f9Z = -( D_fKA.vyuaaROhwa()).tm4BDL37bHHEm; { WY5Uwm59UyPs3[][] Y1Lnt6te; void sye2Yc; ZyGpVeOWEoXL()[ -!new void[ -false.XobB].BWuCl9eR]; int GlMeaVZynO; int[] WAiq_k_Zuybp; } } public void[] sr1; public int[][] ajB7vVgbQv () { { void[] FSiNe1fC5H; while ( LBQodqyBGBb5U[ !!!nAlxCZu0j4dRe2().pkto28()]) return; { boolean[] jtEh524BXE; } } return --!!-341879749[ !!null.jDp5Q()]; return; int ev; return -68980648[ new m[ -false.VQtqldmjemA()][ -( --!new boolean[ E96ydc7omT[ --false.WVpeXnJaxJh]].PVf6p).IZSGL]]; while ( this.w4N) -!this[ -!this.uqsyDGOhH]; } } class hwaa4wFN0Po { }
36.737977
252
0.479709
247fae13bb9949b176cea3b4a64bd2b85a7e1c16
5,169
package seedu.address.logic.commands.room; import static java.util.Objects.requireNonNull; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_PATIENT_NAME; import static seedu.address.commons.core.Messages.MESSAGE_INVALID_ROOM_NUMBER; import static seedu.address.commons.core.Messages.MESSAGE_PATIENT_NO_ROOM; import static seedu.address.logic.parser.patient.PatientCliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.room.RoomCliSyntax.PREFIX_ROOM_NUMBER; import java.util.Optional; import seedu.address.commons.core.index.Index; import seedu.address.commons.util.CollectionUtil; import seedu.address.logic.commands.Command; import seedu.address.logic.commands.CommandResult; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.patient.Name; /** * Searches a room according to the given room number. */ public class SearchRoomCommand extends Command { public static final String COMMAND_WORD = "searchroom"; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Searches the room with the given room number or with the given individual.\n" + "Only one of the parameter can be provided.\n" + "Parameters: " + PREFIX_ROOM_NUMBER + "ROOM NUMBER or " + PREFIX_NAME + "NAME \n" + "Example: " + COMMAND_WORD + " " + PREFIX_ROOM_NUMBER + "130 or " + PREFIX_NAME + "John Doe"; public static final String MESSAGE_SUCCESS = "Room has been found and listed."; private final SearchRoomDescriptor descriptor; /** * Creates a SearchRoomCommand to look for the specified room based on the inputs * in searchRoomDescriptor. * @param descriptor Details to search the room with. */ public SearchRoomCommand(SearchRoomDescriptor descriptor) { requireNonNull(descriptor); this.descriptor = descriptor; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); assert(descriptor.hasParameter()); if (descriptor.getRoomNumber().isPresent()) { Integer roomNumber = descriptor.roomNumber; Index index = model.checkIfRoomPresent(roomNumber); if (index.getZeroBased() == 0) { throw new CommandException(MESSAGE_INVALID_ROOM_NUMBER); } model.updateFilteredRoomList(room -> room.getRoomNumber() == roomNumber); return new CommandResult(MESSAGE_SUCCESS); } Name patientName = descriptor.patientName; if (model.getPatientWithName(patientName).isEmpty()) { throw new CommandException(MESSAGE_INVALID_PATIENT_NAME); } else if (!model.isPatientAssignedToRoom(patientName)) { throw new CommandException(MESSAGE_PATIENT_NO_ROOM); } model.updateFilteredRoomList(room -> room.isOccupied() && room.getPatient().getName().equals(patientName)); return new CommandResult(MESSAGE_SUCCESS); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof SearchRoomCommand // instanceof handles nulls && descriptor.equals(((SearchRoomCommand) other).descriptor)); } /** * Stores the details to search the room. * Each non-empty field value will replace the corresponding field value of the room. */ public static class SearchRoomDescriptor { private Integer roomNumber; private Name patientName; public SearchRoomDescriptor() { } /** * Constructs a SearchRoomDescriptor object with the following fields. * * @param toCopy SearchRoomDescriptor to copy the fields from. */ public SearchRoomDescriptor(SearchRoomDescriptor toCopy) { setRoomNumber(toCopy.roomNumber); setPatientName(toCopy.patientName); } public boolean hasParameter() { return CollectionUtil.isAnyNonNull(roomNumber, patientName); } public void setRoomNumber(Integer roomNumber) { this.roomNumber = roomNumber; } public Optional<Integer> getRoomNumber() { return Optional.ofNullable(roomNumber); } public void setPatientName(Name patientName) { this.patientName = patientName; } public Optional<Name> getPatientName() { return Optional.ofNullable(patientName); } @Override public boolean equals(Object other) { if (other == this) { // short circuit if same object return true; } if (!(other instanceof SearchRoomDescriptor)) { // instanceof handles nulls return false; } SearchRoomDescriptor e = (SearchRoomDescriptor) other; // state check return getRoomNumber().equals(e.getRoomNumber()) && getPatientName().equals(e.getPatientName()); } } }
36.401408
94
0.662024
5e114498e3d92a068d1775da5afd673b50b1028b
1,241
package io.payrun.helpers; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class SerializerHelper { private final ObjectMapper mapper; public SerializerHelper() { this.mapper = new ObjectMapper(); this.mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); this.mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false); this.mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE); this.mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); } public String toJson(Object toBeSerialised) { try { return mapper.writeValueAsString(toBeSerialised); } catch (Exception e) { throw new RuntimeException(e); } } public <T extends Object> T fromJson(String json, Class<T> cls) { try { return mapper.readValue(json, cls); } catch (Exception e) { throw new RuntimeException(e); } } }
33.540541
88
0.706688
00dd3854e06f0506dec5d556bcf93c76e58e21d5
4,563
package com.example.leo.starwarsapp; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by Leo on 2/17/18. */ public class MovieAdapter extends BaseAdapter { // adapter takes the app itself and a list of data to display private Context mContext; private ArrayList<Movie> mMovieList; private LayoutInflater mInflater; // constructor public MovieAdapter(Context mContext, ArrayList<Movie> mMoviesList) { // initialize instances variables this.mContext = mContext; this.mMovieList = mMoviesList; mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } // methods // a list of methods we need to override // gives you the number of recipes in the data source @Override public int getCount() { return mMovieList.size(); } // returns the item at specific position in the data source @Override public Object getItem(int position) { return mMovieList.get(position); } // returns the row id associated with the specific position in the list @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; // check if the view already exists // if yes, you don't need to inflate and findViewbyID again if (convertView == null) { // inflate convertView = mInflater.inflate(R.layout.list_item_movie, parent, false); // add the views to the holder holder = new ViewHolder(); // ViewHolder holder = new ViewHolder((TextView)v); // views //assert holder != null; holder.titleTextView = (TextView) convertView.findViewById(R.id.movie_list_title); holder.descriptionTextView = (TextView) convertView.findViewById(R.id.movie_list_description); holder.thumbnailImageView = (ImageView) convertView.findViewById(R.id.movie_list_thumbnail); holder.mainCharacterTextView = (TextView) convertView.findViewById(R.id.movie_list_characters); holder.hasSeenTextView = convertView.findViewById(R.id.has_seen); // add the holder to the view // for future use convertView.setTag(holder); } else { // get the view holder from converview holder = (ViewHolder) convertView.getTag(); } // get relavate subview of the row view TextView titleTextView = (TextView) holder.titleTextView; TextView descriptionTextView = (TextView) holder.descriptionTextView; ImageView thumbnailImageView = (ImageView) holder.thumbnailImageView; TextView mainCharacterTextView = (TextView) holder.mainCharacterTextView; // get corresonpinding recipe for each row Movie movie = (Movie) getItem(position); // update the row view's textviews and imageview to display the information // titleTextView titleTextView.setText(movie.title); // episodeTextView descriptionTextView.setText(movie.description + "Description"); // mainCharacterTextView StringBuilder Character = new StringBuilder(); for (int i = 0; i < 3; i++) { Character.append(movie.main_characters.get(i)); if(i < 2) Character.append(", "); } mainCharacterTextView.setText(Character.toString()); String hasSeenText = movie.hasSeen != null ? movie.hasSeen : "Has seen?"; holder.hasSeenTextView.setText(hasSeenText); // imageView // use Picasso library to load image from the image url Picasso.with(mContext).load(movie.imageUrl).into(thumbnailImageView); return convertView; } public class ViewHolder { public TextView titleTextView; public TextView descriptionTextView; public ImageView thumbnailImageView; public TextView mainCharacterTextView; public TextView hasSeenTextView; //titleTextView //episodeTextView //thumbnailImageView } // intent is used to pass information between activities // intent -> pacakge // sender, receiver }
31.253425
107
0.666448
1d18fed37d7cf4fe883ed94fb8085470472ab472
875
package item; public class Link extends FilesystemItem implements fsi2 { protected DataObject data ; public Link() { this.data = new DataObject(); this.data.setName("MySpecialName"); } /* (non-Javadoc) * @see item.fsi2#getSize() */ @Override public int getSize(){ data = this.getData(); return data.content.length(); } /* (non-Javadoc) * @see item.fsi2#getName() */ @Override public String getName(){ data = this.getData(); return data.name; } /* (non-Javadoc) * @see item.fsi2#setContent(java.lang.String) */ @Override public void setContent(String content) { data = this.getData(); data.content = content; } public DataObject getData() { return this.data; } /* (non-Javadoc) * @see item.fsi2#someOtherMethod() */ @Override public void someOtherMethod() { } }
17.857143
58
0.619429
08d6a28dccd38773b219ce650900397b3422a937
4,284
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.terracotta.diagnostic.server; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terracotta.diagnostic.common.DiagnosticResponse; import org.terracotta.diagnostic.server.api.DiagnosticServicesRegistration; import org.terracotta.diagnostic.server.api.Expose; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.Objects.requireNonNull; /** * @author Mathieu Carbou */ class DiagnosticServiceDescriptor<T> implements DiagnosticServicesRegistration<T> { private static final Logger LOGGER = LoggerFactory.getLogger(DiagnosticServiceDescriptor.class); private final Class<T> serviceInterface; private final T serviceImplementation; private final Set<String> mBeans = ConcurrentHashMap.newKeySet(); private final Runnable onClose; private final Function<String, Boolean> jmxExpose; DiagnosticServiceDescriptor(Class<T> serviceInterface, T serviceImplementation, Runnable onClose, Function<String, Boolean> jmxExpose) { if (!serviceInterface.isInterface()) { throw new IllegalArgumentException("Not an interface: " + serviceInterface.getName()); } this.serviceInterface = requireNonNull(serviceInterface); this.serviceImplementation = requireNonNull(serviceImplementation); this.onClose = requireNonNull(onClose); this.jmxExpose = requireNonNull(jmxExpose); } @Override public Class<T> getServiceInterface() { return serviceInterface; } @Override public boolean exposeMBean(String name) { return jmxExpose.apply(name); } @Override public void close() { onClose.run(); } T getServiceImplementation() { return serviceImplementation; } Optional<DiagnosticResponse<?>> invoke(String methodName, Object... arguments) { return findMethod(methodName).map(method -> { try { Object result = method.invoke(serviceImplementation, arguments); return new DiagnosticResponse<>(result); } catch (InvocationTargetException e) { Throwable cause = e.getTargetException(); LOGGER.error("Failed invoking method {} on diagnostic service {}: {}", methodName, serviceInterface.getName(), cause.getMessage(), cause); return new DiagnosticResponse<>(null, cause); } catch (Exception e) { LOGGER.error("Failed invoking method {} on diagnostic service {}: {}", methodName, serviceInterface.getName(), e.getMessage(), e); return new DiagnosticResponse<>(null, e); } }); } boolean matches(Class<?> serviceInterface) { return matches(serviceInterface.getName()); } private boolean matches(String serviceInterface) { return Objects.equals(serviceInterface, this.serviceInterface.getName()); } private Optional<Method> findMethod(String methodName) { List<Method> list = Stream.of(serviceInterface.getMethods()) .filter(method -> method.getName().equals(methodName)) .collect(Collectors.toList()); if (list.size() > 1) { throw new AssertionError("Method overloading not yet supported: " + serviceInterface.getName()); } return list.stream().findAny(); } Optional<String> discoverMBeanName() { return Optional.ofNullable(serviceImplementation.getClass().getAnnotation(Expose.class)).map(Expose::value); } void addMBean(String name) { mBeans.add(name); } public Set<String> getRegisteredMBeans() { return mBeans; } }
34.272
146
0.737162
72d9302b4e992ff51cd0132f0dbcb88dd6f6ead9
722
package qj.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import qj.util.funct.P0; import qj.util.funct.P1; public class SystemUtil { static BufferedReader br; public static String readLine() { if (br == null) { br = new BufferedReader(new InputStreamReader(System.in)); } try { return br.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public static void onReturn(final P1<String> p1) { ThreadUtil.runStrong(new P0() { @Override public void e() { while (true) { try { String readLine = readLine(); p1.e(readLine); } catch (Exception e1) { return; } } } }); } }
18.05
61
0.641274
0700695f52278cc5968ab1cb26c5469097c77642
3,517
package org.ossgang.commons.observables; import org.ossgang.commons.monads.Maybe; import org.ossgang.commons.observables.exceptions.UnhandledException; import java.util.function.BiConsumer; import java.util.function.Consumer; /** * Utility class to create {@link Observer} instances. */ public class Observers { private Observers() { throw new UnsupportedOperationException("static only"); } /** * Create an {@link Observer} for values and exceptions * * @param valueConsumer for values * @param exceptionConsumer for exceptions * @param <T> the type of event * @return the {@link Observer} */ public static <T> Observer<T> withErrorHandling(Consumer<T> valueConsumer, Consumer<Throwable> exceptionConsumer) { return new Observer<T>() { public void onValue(T value) { valueConsumer.accept(value); } public void onException(Throwable exception) { exceptionConsumer.accept(exception); } }; } /** * Create an {@link Observer} for {@link Maybe}s * * @param maybeConsumer for maybe * @param <T> the type of event * @return the {@link Observer} */ public static <T> Observer<T> forMaybes(Consumer<Maybe<T>> maybeConsumer) { return new Observer<T>() { public void onValue(T value) { maybeConsumer.accept(Maybe.ofValue(value)); } public void onException(Throwable exception) { maybeConsumer.accept(Maybe.ofException(exception)); } }; } /** * Create an {@link Observer} for exceptions * * @param exceptionConsumer for the exceptions * @param <T> the tupe of event * @return the {@link Observer} */ public static <T> Observer<T> forExceptions(Consumer<Throwable> exceptionConsumer) { return new Observer<T>() { public void onValue(T value) { } public void onException(Throwable exception) { exceptionConsumer.accept(exception); } }; } /** * Create an observer based on a weak reference to an object, and class method references to consumers for values * (and, optionally, exceptions). * Release the reference to the subscriber as soon as the (weak-referenced) holder object is GC'd. A common use * case for this is e.g. working with method references within a particular object: * <pre> * class Test { * public void doSubscribe(Observable&lt;String&gt; obs) { * obs.subscribe(weak(this, Test::handle)); * } * private void handle(String update) ... * } * </pre> * This will allow the "Test" instance to be GC'd, terminating the subscription; but for as long as it lives, the * subscription will be kept alive. */ public static <C, T> Observer<T> weak(C holder, BiConsumer<C, T> valueConsumer) { return new WeakMethodReferenceObserver<>(holder, valueConsumer); } /** * @see #weak(Object, BiConsumer) */ public static <C, T> Observer<T> weakWithErrorHandling(C holder, BiConsumer<? super C, T> valueConsumer, BiConsumer<? super C, Throwable> exceptionConsumer) { return new WeakMethodReferenceObserver<>(holder, valueConsumer, exceptionConsumer); } }
34.145631
119
0.605914
b7ccb59874751513c69b0c75db25ecca8f82984e
685
package com.hospital.appointmentservice.repository; import com.hospital.appointmentservice.model.Appointment; import com.hospital.appointmentservice.projection.AppointmentProjection; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Date; import java.util.List; public interface AppointmentRepository extends JpaRepository<Appointment,Long> { List<Appointment> findByDoctorIdAndAppointmentDayEquals(Long id,Date appointmentDate); List<Appointment> findByDoctorIdAndAppointmentDayBetween(Long id,Date startDate,Date endDate); List<AppointmentProjection> findProjectedByDoctorId(Long id); List<Appointment> findByUserId(Long id); }
31.136364
98
0.833577
deae1de1468373449d654f7445c649308e7e69a9
17,944
/* * ModeShape (http://www.modeshape.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.modeshape.jcr.api.sequencer; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import javax.jcr.NamespaceException; import javax.jcr.NamespaceRegistry; import javax.jcr.Node; import javax.jcr.Property; import javax.jcr.RepositoryException; import org.modeshape.jcr.api.Logger; import org.modeshape.jcr.api.nodetype.NodeTypeManager; /** * A component that reads recently-changed content (often uploaded files) and extracts additional information from the content. * <p> * Each ModeShape repository can be configured with zero or more sequencers. Each sequencer is configured with a set of match * conditions that define the acceptable patterns for the paths of changed nodes, as well as a path specification that defines * where the derived (or generated) output should be placed. Then when clients change nodes with paths that satisfy the match * conditions, the repository will create a new Session and invoke the sequencer, which is then expected to process the changed * content and generate the derived information under the supplied parent node. The session will be saved automatically or, if an * exception is thrown, discard the changes and close the session. * </p> */ public abstract class Sequencer { private final UUID uuid = UUID.randomUUID(); /** * The logger instance, set via reflection */ private Logger logger; /** * The name of this sequencer, set via reflection */ private String name; /** * The name of the repository that owns this sequencer, set via reflection */ private String repositoryName; /** * The multiple path expressions for this sequencer, set via reflection */ private Object[] pathExpressions; /** * The singular path expression of this sequencer, set via reflection */ private String pathExpression; /** * The set of MIME types that this sequencer will process. Subclasses should set call * {@link #registerDefaultMimeTypes(String...)} in the no-arg constructor to set the default MIME types for the sequencer, but * the field may be overwritten in the sequencer's configuration by setting the "acceptedMimeTypes" field to an array of * string values. */ private String[] acceptedMimeTypes = {}; private Set<String> acceptedMimeTypesSet = null; private boolean initialized = false; /** * Return the unique identifier for this sequencer. * * @return the unique identifier; never null */ public final UUID getUniqueId() { return uuid; } /** * Get the name for this sequencer. * * @return the name, or null if there is no description */ public final String getName() { return name; } /** * Get the name of the repository. * * @return the repository name; never null */ public final String getRepositoryName() { return repositoryName; } /** * Obtain the path expressions as configured on the sequencer. This method always returns a copy to prevent modification of * the values. * * @return the path expressions; never null but possibly empty */ public final String[] getPathExpressions() { String pathExpression = this.pathExpression; Object[] pathExpressions = this.pathExpressions; if (pathExpression == null && (pathExpressions == null || pathExpressions.length == 0)) { // there's none ... return new String[] {}; } if (pathExpression != null && (pathExpressions == null || pathExpressions.length == 0)) { // There's just one ... return new String[] {pathExpression}; } List<String> expressions = new ArrayList<String>(pathExpressions.length + 1); addExpression(expressions, pathExpression); for (Object value : pathExpressions) { addExpression(expressions, value); } return expressions.toArray(new String[expressions.size()]); } private void addExpression( List<String> values, Object value ) { assert !initialized : "No expressions can be added after the sequencer has been initialized"; if (value instanceof String) { String str = (String)value; str = str.trim(); if (str.length() != 0) { values.add(str); } } } /** * Initialize the sequencer. This is called automatically by ModeShape once for each Sequencer instance, and should not be * called by the sequencer. * <p> * By default this method does nothing, so it should be overridden by implementations to do a one-time initialization of any * internal components. For example, sequencers can use the supplied <code>registry</code> and <code>nodeTypeManager</code> * objects to register custom namesapces and node types required by the generated content. * </p> * * @param registry the namespace registry that can be used to register custom namespaces; never null * @param nodeTypeManager the node type manager that can be used to register custom node types; never null * @throws RepositoryException if operations on the {@link NamespaceRegistry} or {@link NodeTypeManager} fail * @throws IOException if any stream based operations fail (like importing cnd files) */ public void initialize( NamespaceRegistry registry, NodeTypeManager nodeTypeManager ) throws RepositoryException, IOException { // Subclasses may not necessarily call 'super.initialize(...)', but if they do then we can make this assertion ... assert !initialized : "The Sequencer.initialize(...) method should not be called by subclasses; ModeShape has already (and automatically) initialized the Sequencer"; } /** * Method called by the code calling {@link #initialize(NamespaceRegistry, NodeTypeManager)} (typically via reflection) to * signal that the initialize method is completed. See Sequencers.initialize() for details, and no this method is indeed used. */ @SuppressWarnings( "unused" ) private void postInitialize() { if (!initialized) { initialized = true; // ------------------------------------------------------------------------------------------------------------ // Add any code here that needs to run after #initialize(...), which will be overwritten by subclasses // ------------------------------------------------------------------------------------------------------------ // Make immutable the Set<String> of accepts MIME types ... acceptedMimeTypesSet = Collections.unmodifiableSet(getAcceptedMimeTypes()); } } /** * Execute the sequencing operation on the specified property, which has recently been created or changed. * <p> * Each sequencer is expected to process the value of the property, extract information from the value, and write a structured * representation (in the form of a node or a subgraph of nodes) using the supplied output node. Note that the output node * will either be: * <ol> * <li>the selected node, in which case the sequencer was configured to generate the output information directly under the * selected input node; or</li> * <li>a newly created node in a different location than node being sequenced (in this case, the primary type of the new node * will be 'nt:unstructured', but the sequencer can easily change that using {@link Node#setPrimaryType(String)})</li> * </ol> * </p> * <p> * The implementation is expected to always clean up all resources that it acquired, even in the case of exceptions. * </p> * <p> * Note: This method <em>must</em> be threadsafe: ModeShape will likely invoke this method concurrently in separate threads, * and the method should never modify the state or fields of the Sequencer implementation class. All initialization should be * performed in {@link #initialize(NamespaceRegistry, NodeTypeManager)}. * </p> * * @param inputProperty the property that was changed and that should be used as the input; never null * @param outputNode the node that represents the output for the derived information; never null, and will either be * {@link Node#isNew() new} if the output is being placed outside of the selected node, or will not be new when the * output is to be placed on the selected input node * @param context the context in which this sequencer is executing, and which may contain additional parameters useful when * generating the output structure; never null * @return true if the sequencer's output should be saved, or false otherwise * @throws Exception if there was a problem with the sequencer that could not be handled. All exceptions will be logged * automatically as errors by ModeShape. */ public abstract boolean execute( Property inputProperty, Node outputNode, Context context ) throws Exception; @Override public String toString() { return repositoryName + " -> " + getClass().getName() + " uuid=" + uuid + (name != null ? (" : " + name) : ""); } /** * Registers a namespace using the given {@link NamespaceRegistry}, if the namespace has not been previously registered. * * @param namespacePrefix a non-null {@code String} * @param namespaceUri a non-null {@code String} * @param namespaceRegistry a {@code NamespaceRegistry} instance. * @return true if the namespace has been registered, or false if it was already registered * @throws RepositoryException if anything fails during the registration process */ protected boolean registerNamespace( String namespacePrefix, String namespaceUri, NamespaceRegistry namespaceRegistry ) throws RepositoryException { if (namespacePrefix == null || namespaceUri == null) { throw new IllegalArgumentException("Neither the namespace prefix, nor the uri should be null"); } try { // if the call succeeds, means it was previously registered namespaceRegistry.getPrefix(namespaceUri); return false; } catch (NamespaceException e) { // namespace not registered yet namespaceRegistry.registerNamespace(namespacePrefix, namespaceUri); return true; } } /** * Registers node types from a CND file, using the given {@link NodeTypeManager}. Any namespaces defined in the CND file will * be automatically registered as well. * * @param cndFile the relative path to the cnd file, which is loaded using via {@link Class#getResourceAsStream(String)} * @param nodeTypeManager the node type manager with which the cnd will be registered * @param allowUpdate a boolean which indicates whether updates on existing node types are allowed or no. See * {@link NodeTypeManager#registerNodeType(javax.jcr.nodetype.NodeTypeDefinition, boolean)} * @throws RepositoryException if anything fails * @throws IOException if any stream related operations fail */ protected void registerNodeTypes( String cndFile, NodeTypeManager nodeTypeManager, boolean allowUpdate ) throws RepositoryException, IOException { InputStream cndStream = getClass().getResourceAsStream(cndFile); registerNodeTypes(cndStream, nodeTypeManager, allowUpdate); } /** * See {@link Sequencer#registerNodeTypes(String, org.modeshape.jcr.api.nodetype.NodeTypeManager, boolean)} * * @param cndStream the input stream containing the CND file; may not be null * @param nodeTypeManager the node type manager with which the node types in the CND file should be registered; may not be * null * @param allowUpdate a boolean which indicates whether updates on existing node types are allowed or no. See * {@link NodeTypeManager#registerNodeType(javax.jcr.nodetype.NodeTypeDefinition, boolean)} * @throws RepositoryException if anything fails * @throws IOException if any stream related operations fail */ protected void registerNodeTypes( InputStream cndStream, NodeTypeManager nodeTypeManager, boolean allowUpdate ) throws RepositoryException, IOException { if (cndStream == null) { throw new IllegalArgumentException("The stream to the given cnd file is null"); } nodeTypeManager.registerNodeTypes(cndStream, allowUpdate); } protected final Logger getLogger() { return logger; } /** * Set the MIME types that are accepted by default, if there are any. This method should be called from the * {@link #initialize(NamespaceRegistry, NodeTypeManager)} method in the subclass. * <p> * This method can be called more than once to add additional mime types. * </p> * * @param mimeTypes the array of MIME types that are accepted by this sequencer * @see #isAccepted(String) */ protected final void registerDefaultMimeTypes( String... mimeTypes ) { assert !initialized : "No default MIME types can be registered after the sequencer has been initialized"; if (mimeTypes != null && mimeTypes.length != 0 && acceptedMimeTypes.length == 0) { // There are no overridden mime types, so we can register the default MIME types ... if (acceptedMimeTypesSet == null) acceptedMimeTypesSet = new HashSet<String>(); for (String mimeType : mimeTypes) { if (mimeType == null) continue; mimeType = mimeType.trim(); if (mimeType.length() == 0) continue; acceptedMimeTypesSet.add(mimeType); } } } /** * Utility method to obtain the set of accepted MIME types. The resulting set will either be those set by default in the * subclass' overridden {@link #initialize(NamespaceRegistry, NodeTypeManager)} method or the MIME types explicitly set in the * sequencers configuration. * * @return the set of MIME types that are accepted by this Sequencer instance; never null but possibly empty if this Sequencer * instance accepts all MIME types */ protected final Set<String> getAcceptedMimeTypes() { if (acceptedMimeTypesSet == null) { // No defaults are registered, so use those non-defaults ... acceptedMimeTypesSet = new HashSet<String>(); for (String mimeType : acceptedMimeTypes) { if (mimeType == null) continue; mimeType = mimeType.trim(); if (mimeType.length() == 0) continue; acceptedMimeTypesSet.add(mimeType); } } return acceptedMimeTypesSet; } /** * Determine if this sequencer requires the content to have a specific MIME type * * @return true if this sequencer can only process certain MIME types, or false if there are no restrictions */ public final boolean hasAcceptedMimeTypes() { return !getAcceptedMimeTypes().isEmpty(); } /** * Determine if this sequencer has been configured to accept and process content with the supplied MIME type. * * @param mimeType the MIME type * @return true if content with the supplied the MIME type is to be processed (or when <code>mimeType</code> is null and * therefore not known), or false otherwise * @see #hasAcceptedMimeTypes() */ public final boolean isAccepted( String mimeType ) { if (mimeType != null && hasAcceptedMimeTypes()) { return getAcceptedMimeTypes().contains(mimeType.trim()); } return true; // accept all mime types } /** * The sequencer context represents the complete context of a sequencer invocation. Currently, this information includes the * current time of sequencer execution. */ public interface Context { /** * Get the timestamp of the sequencing. This is always the timestamp of the change event that is being processed. * * @return timestamp the "current" timestamp; never null */ Calendar getTimestamp(); /** * Returns a {@link org.modeshape.jcr.api.ValueFactory} instance which can be used to perform additional type conversions, * from what {@link javax.jcr.ValueFactory} offers * * @return a non-null value factory, using the output node's session as context */ org.modeshape.jcr.api.ValueFactory valueFactory(); } }
45.892583
173
0.656933
e68431c670acff5f990232e5fd5a5813924cce12
1,395
package com.laketravels.ch07.kafka.producer; import org.apache.kafka.clients.producer.*; import java.util.Properties; import java.util.concurrent.ExecutionException; /** * Created by pankajmisra on 3/3/17. */ public class SimpleProducer { public static void main(String[] args) throws ExecutionException, InterruptedException { Properties props = new Properties(); /* Set the list of broker addresses separated by commas. This needs to be updated with IP of your VM running Kafka broker */ props.setProperty("bootstrap.servers", "192.168.0.117:9092"); //Set the serializer for key of the message(value) props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); //Set the serializer for the message (value) props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); //Create a producer Producer<String, String> producer = new KafkaProducer<String, String>(props); //Create a message to be sent to a topic ProducerRecord message = new ProducerRecord("customer", "001", "A Sample Message..."); //send the message producer.send(message); System.out.println("Message Published"); //close the producer connection producer.close(); } }
30.326087
94
0.660932
dbfd32d533a50626ce7214fe97bafb5e76f9c41c
385
package com.eventnotifierlibgdx.event.internal; import com.eventnotifierlibgdx.event.api.Event; /** * Handles events. * * TODO: Make this public when other event handlers need to be registered, besides the event handlers created by the * event notifier initializer. */ interface EventHandler { /** * Handle the given event. */ void handleEvent(Event event); }
21.388889
116
0.722078
22d5a6de2de75b84e1f7f35c13166e1c6f17a35d
6,616
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.model; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.Expression; import org.apache.camel.Processor; import org.apache.camel.builder.ExpressionBuilder; import org.apache.camel.model.language.ExpressionDefinition; import org.apache.camel.processor.Delayer; import org.apache.camel.spi.Metadata; import org.apache.camel.spi.RouteContext; /** * Delays processing for a specified length of time * * @version */ @Metadata(label = "eip,routing") @XmlRootElement(name = "delay") @XmlAccessorType(XmlAccessType.FIELD) public class DelayDefinition extends ExpressionNode implements ExecutorServiceAwareDefinition<DelayDefinition> { // TODO: Camel 3.0 Should extend NoOutputExpressionNode @XmlTransient private ExecutorService executorService; @XmlAttribute private String executorServiceRef; @XmlAttribute @Metadata(defaultValue = "false") private Boolean asyncDelayed; @XmlAttribute @Metadata(defaultValue = "true") private Boolean callerRunsWhenRejected; public DelayDefinition() { } public DelayDefinition(Expression delay) { super(delay); } @Override public String getLabel() { return "delay[" + getExpression() + "]"; } @Override public String toString() { return "Delay[" + getExpression() + " -> " + getOutputs() + "]"; } @Override public Processor createProcessor(RouteContext routeContext) throws Exception { Processor childProcessor = this.createChildProcessor(routeContext, false); Expression delay = createAbsoluteTimeDelayExpression(routeContext); boolean async = getAsyncDelayed() != null && getAsyncDelayed(); boolean shutdownThreadPool = ProcessorDefinitionHelper.willCreateNewThreadPool(routeContext, this, async); ScheduledExecutorService threadPool = ProcessorDefinitionHelper.getConfiguredScheduledExecutorService(routeContext, "Delay", this, async); Delayer answer = new Delayer(routeContext.getCamelContext(), childProcessor, delay, threadPool, shutdownThreadPool); if (getAsyncDelayed() != null) { answer.setAsyncDelayed(getAsyncDelayed()); } if (getCallerRunsWhenRejected() == null) { // should be default true answer.setCallerRunsWhenRejected(true); } else { answer.setCallerRunsWhenRejected(getCallerRunsWhenRejected()); } return answer; } private Expression createAbsoluteTimeDelayExpression(RouteContext routeContext) { ExpressionDefinition expr = getExpression(); if (expr != null) { return expr.createExpression(routeContext); } return null; } // Fluent API // ------------------------------------------------------------------------- /** * Sets the delay time in millis to delay * * @param delay delay time in millis * @return the builder */ public DelayDefinition delayTime(Long delay) { setExpression(ExpressionNodeHelper.toExpressionDefinition(ExpressionBuilder.constantExpression(delay))); return this; } /** * Whether or not the caller should run the task when it was rejected by the thread pool. * <p/> * Is by default <tt>true</tt> * * @param callerRunsWhenRejected whether or not the caller should run * @return the builder */ public DelayDefinition callerRunsWhenRejected(boolean callerRunsWhenRejected) { setCallerRunsWhenRejected(callerRunsWhenRejected); return this; } /** * Enables asynchronous delay which means the thread will <b>noy</b> block while delaying. */ public DelayDefinition asyncDelayed() { setAsyncDelayed(true); return this; } /** * To use a custom Thread Pool if asyncDelay has been enabled. */ public DelayDefinition executorService(ExecutorService executorService) { setExecutorService(executorService); return this; } /** * Refers to a custom Thread Pool if asyncDelay has been enabled. */ public DelayDefinition executorServiceRef(String executorServiceRef) { setExecutorServiceRef(executorServiceRef); return this; } // Properties // ------------------------------------------------------------------------- /** * Expression to define how long time to wait (in millis) */ @Override public void setExpression(ExpressionDefinition expression) { // override to include javadoc what the expression is used for super.setExpression(expression); } public Boolean getAsyncDelayed() { return asyncDelayed; } public void setAsyncDelayed(Boolean asyncDelayed) { this.asyncDelayed = asyncDelayed; } public Boolean getCallerRunsWhenRejected() { return callerRunsWhenRejected; } public void setCallerRunsWhenRejected(Boolean callerRunsWhenRejected) { this.callerRunsWhenRejected = callerRunsWhenRejected; } public ExecutorService getExecutorService() { return executorService; } public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } public String getExecutorServiceRef() { return executorServiceRef; } public void setExecutorServiceRef(String executorServiceRef) { this.executorServiceRef = executorServiceRef; } }
33.414141
146
0.690901
92683ea6632bf1d12496f7d8ccafbd20fef8978e
2,360
/* * Copyright (C) 2010 Heed Technology Inc. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.archivemanager.services.search.parsing.plugins; import java.util.ArrayList; import java.util.List; import org.archivemanager.models.dictionary.Model; import org.archivemanager.models.system.QName; import org.archivemanager.services.dictionary.DataDictionaryService; import org.archivemanager.services.search.Definition; import org.archivemanager.services.search.DictionaryPlugin; import org.archivemanager.services.search.dictionary.QNameDefinition; public class QNameDictionaryPlugin implements DictionaryPlugin { private DataDictionaryService dictionaryService; private String entityName; private int limit; public List<Definition> getDefinitions() { List<Definition> defs = new ArrayList<Definition>(); try { QName entityQname = QName.createQualifiedName(entityName); List<Model> models = dictionaryService.getChildModels(entityQname); if(models != null && models.size() > 0) { for(Model child : models) { defs.add(new QNameDefinition(child.getQName().getLocalName(), "localName:"+child.getQName().getLocalName())); } } } catch(Exception e) { e.printStackTrace(); } return defs; } public String getEntity() { return entityName; } public void setEntity(String entityName) { this.entityName = entityName; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } public void setDictionaryService(DataDictionaryService dictionaryService) { this.dictionaryService = dictionaryService; } }
33.239437
115
0.736017
bf7ed336a553f7462ff8404f519dec3760a24945
8,582
/* * GridGain Community Edition Licensing * Copyright 2019 GridGain Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause * Restriction; you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. * * Commons Clause Restriction * * The Software is provided to you by the Licensor under the License, as defined below, subject to * the following condition. * * Without limiting other conditions in the License, the grant of rights under the License will not * include, and the License does not grant to you, the right to Sell the Software. * For purposes of the foregoing, “Sell” means practicing any or all of the rights granted to you * under the License to provide to third parties, for a fee or other consideration (including without * limitation fees for hosting or consulting/ support services related to the Software), a product or * service whose value derives, entirely or substantially, from the functionality of the Software. * Any license notice or attribution required by the License must also include this Commons Clause * License Condition notice. * * For purposes of the clause above, the “Licensor” is Copyright 2019 GridGain Systems, Inc., * the “License” is the Apache License, Version 2.0, and the Software is the GridGain Community * Edition software provided with this notice. */ package org.apache.ignite.internal.processors.cache; import java.util.ArrayList; import java.util.Collection; import org.apache.ignite.IgniteCache; import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.cache.CacheMode; import org.apache.ignite.cache.CachePeekMode; import org.apache.ignite.cache.CacheWriteSynchronizationMode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.testframework.MvccFeatureChecker; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** * This test checks that entries count metrics, calculated by method * {@link org.apache.ignite.internal.processors.cache.CacheMetricsImpl#getEntriesStat()} (which uses one iteration * over local partitions to get all set of metrics), have the same values as metrics, calculated by individual methods * (which use iteration over local partition per each method call). */ @RunWith(JUnit4.class) public class CacheMetricsEntitiesCountTest extends GridCommonAbstractTest { /** Grid count. */ private static final int GRID_CNT = 3; /** Cache prefix. */ private static final String CACHE_PREFIX = "CACHE"; /** Entities cnt. */ private static final int ENTITIES_CNT = 100; /** Onheap peek modes. */ private static final CachePeekMode[] ONHEAP_PEEK_MODES = new CachePeekMode[] { CachePeekMode.ONHEAP, CachePeekMode.PRIMARY, CachePeekMode.BACKUP, CachePeekMode.NEAR}; /** Cache count. */ private static int cacheCnt = 4; /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); Collection<CacheConfiguration> ccfgs = new ArrayList<>(4); ccfgs.add(new CacheConfiguration<>() .setName(CACHE_PREFIX + 0) .setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC) .setCacheMode(CacheMode.REPLICATED) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)); ccfgs.add(new CacheConfiguration<>() .setName(CACHE_PREFIX + 1) .setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC) .setCacheMode(CacheMode.PARTITIONED) .setBackups(1) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)); ccfgs.add(new CacheConfiguration<>() .setName(CACHE_PREFIX + 2) .setWriteSynchronizationMode(CacheWriteSynchronizationMode.FULL_SYNC) .setCacheMode(CacheMode.PARTITIONED) .setBackups(1) .setNearConfiguration(new NearCacheConfiguration<>()) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)); if (!MvccFeatureChecker.forcedMvcc() || MvccFeatureChecker.isSupported(MvccFeatureChecker.Feature.LOCAL_CACHE)) { ccfgs.add(new CacheConfiguration<>() .setName(CACHE_PREFIX + 3) .setCacheMode(CacheMode.LOCAL) .setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL)); } cacheCnt = ccfgs.size(); cfg.setCacheConfiguration(U.toArray(ccfgs, new CacheConfiguration[cacheCnt])); return cfg; } /** {@inheritDoc} */ @Override protected void beforeTestsStarted() throws Exception { startGrids(GRID_CNT); } /** * Test entities count, calculated by different implementations. */ @Test public void testEnitiesCount() throws Exception { awaitPartitionMapExchange(); for (int igniteIdx = 0; igniteIdx < GRID_CNT; igniteIdx++) for (int cacheIdx = 0; cacheIdx < cacheCnt; cacheIdx++) fillCache(igniteIdx, cacheIdx); for (int igniteIdx = 0; igniteIdx < GRID_CNT; igniteIdx++) for (int cacheIdx = 0; cacheIdx < cacheCnt; cacheIdx++) checkCache(igniteIdx, cacheIdx); } /** * @param igniteIdx Ignite index. * @param cacheIdx Cache index. */ private void fillCache(int igniteIdx, int cacheIdx) { log.info("Filling cache, igniteIdx=" + igniteIdx + ", cacheIdx=" + cacheIdx); IgniteCache cache = grid(igniteIdx).cache(CACHE_PREFIX + cacheIdx); for (int i = 0; i < ENTITIES_CNT; i++) cache.put("key" + igniteIdx + "-" + i, i); } /** * @param igniteIdx Ignite index. * @param cacheIdx Cache index. */ private void checkCache(int igniteIdx, int cacheIdx) throws IgniteCheckedException { IgniteInternalCache internalCache = grid(igniteIdx).cachex(CACHE_PREFIX + cacheIdx); GridCacheContext cctx = internalCache.context(); GridCacheAdapter cache = cctx.cache(); CacheMetricsImpl metrics = cache.metrics0(); CacheMetricsImpl.EntriesStatMetrics entriesStatMetrics = metrics.getEntriesStat(); long offHeapEntriesCnt = cache.offHeapEntriesCount(); long offHeapPrimaryEntriesCnt = cctx.offheap().cacheEntriesCount(cctx.cacheId(), true, false, cctx.affinity().affinityTopologyVersion()); long offHeapBackupEntriesCnt = cctx.offheap().cacheEntriesCount(cctx.cacheId(), false, true, cctx.affinity().affinityTopologyVersion()); long heapEntriesCnt = cache.localSizeLong(ONHEAP_PEEK_MODES); int size = cache.size(); int keySize = size; boolean isEmpty = cache.isEmpty(); String cacheInfo = "igniteIdx=" + igniteIdx + ", cacheIdx=" + cacheIdx + " "; log.info("Checking cache, " + cacheInfo); assertEquals(cacheInfo + " offHeapEntriesCnt", offHeapEntriesCnt, entriesStatMetrics.offHeapEntriesCount()); assertEquals(cacheInfo + " offHeapBackupEntriesCnt", offHeapBackupEntriesCnt, entriesStatMetrics.offHeapBackupEntriesCount()); assertEquals(cacheInfo + " offHeapPrimaryEntriesCnt", offHeapPrimaryEntriesCnt, entriesStatMetrics.offHeapPrimaryEntriesCount()); assertEquals(cacheInfo + " heapEntriesCnt", heapEntriesCnt, entriesStatMetrics.heapEntriesCount()); assertEquals(cacheInfo + " size", size, entriesStatMetrics.size()); assertEquals(cacheInfo + " keySize", keySize, entriesStatMetrics.keySize()); assertEquals(cacheInfo + " isEmpty", isEmpty, entriesStatMetrics.isEmpty()); } }
41.863415
121
0.704614
943b0718e6a5684457c25e7ea76760ee97ea9bdc
5,629
package vdsMain; import bitcoin.BaseBlob; import bitcoin.UInt256; import generic.io.StreamWriter; import generic.serialized.SeriableData; import java.io.IOException; import java.util.Arrays; import java.util.Locale; //bsf public class SaplingPaymentAddress extends SeriableData implements CTxDestination { /* renamed from: a */ public DiversifierT f12218a = new DiversifierT(); /* renamed from: b */ public UInt256 f12219b = new UInt256(); /* renamed from: c */ private int f12220c = 0; public SaplingPaymentAddress() { mo43016d(); } public SaplingPaymentAddress(byte[] bArr, int i) { if (bArr != null) { if (bArr.length - i >= 43) { this.f12218a.mo42953a(bArr, i); this.f12219b.set(bArr, i + 11); } else { throw new IllegalArgumentException(String.format(Locale.getDefault(), "Invalidate sapling payment addr len: %d", new Object[]{Integer.valueOf(bArr.length - i)})); } } mo43016d(); } public SaplingPaymentAddress(SeriableData seriableData) { super(seriableData); if (seriableData instanceof SaplingPaymentAddress) { mo43013a((SaplingPaymentAddress) seriableData); } else if (seriableData instanceof SaplingExtendedFullViewingKey) { mo43012a((SaplingExtendedFullViewingKey) seriableData); } else { mo43016d(); } } public SaplingPaymentAddress(DiversifierT DiversifierT, UInt256 uInt256) { this.f12218a.mo42952a(DiversifierT); this.f12219b.set((BaseBlob) uInt256); mo43016d(); } /* renamed from: a */ public void mo43013a(SaplingPaymentAddress SaplingPaymentAddress) { if (SaplingPaymentAddress == null) { this.f12218a.mo42956c(); this.f12219b.clear(); this.f12220c = 0; } else { this.f12218a.mo42952a(SaplingPaymentAddress.f12218a); this.f12219b.set((BaseBlob) SaplingPaymentAddress.f12219b); } mo43016d(); } /* renamed from: a */ public void mo43014a(byte[] bArr, int i) { if (bArr == null) { this.f12218a.mo42956c(); this.f12219b.clear(); } else { this.f12218a.mo42953a(bArr, i); this.f12219b.set(bArr, i + 11); } mo43016d(); } /* renamed from: a */ public void mo43012a(SaplingExtendedFullViewingKey brv) { mo43013a(brv.mo42971a()); } public void writeSerialData(StreamWriter streamWriter) throws IOException { this.f12218a.serialToStream(streamWriter); this.f12219b.serialToStream(streamWriter); } public void onDecodeSerialData() { this.f12218a.decodeSerialStream((SeriableData) this); this.f12219b.decodeSerialStream((SeriableData) this); mo43016d(); } public boolean equals(Object obj) { boolean z = true; if (obj == this) { return true; } if (!(obj instanceof SaplingPaymentAddress) || obj.hashCode() != this.f12220c) { return false; } SaplingPaymentAddress SaplingPaymentAddress = (SaplingPaymentAddress) obj; if (!SaplingPaymentAddress.f12219b.equals(this.f12219b) || !SaplingPaymentAddress.f12218a.equals(this.f12218a)) { z = false; } return z; } /* access modifiers changed from: protected */ /* renamed from: d */ public void mo43016d() { byte[] bArr = new byte[43]; System.arraycopy(this.f12218a.mo42954a(), 0, bArr, 0, 11); System.arraycopy(this.f12219b.data(), 0, bArr, 11, 32); this.f12220c = Arrays.hashCode(bArr); } public int hashCode() { return this.f12220c; } public boolean isNull() { return this.f12218a.mo42957d() && this.f12219b.isNull(); } /* renamed from: e */ public void mo43017e() { this.f12218a.mo42956c(); this.f12219b.clear(); } //getCTxDestinationType public CTxDestinationType getCTxDestinationType() { return CTxDestinationType.ANONYMOUST_KEY; } public byte[] data() { byte[] bArr = new byte[43]; m10500b(bArr, 0); return bArr; } /* renamed from: b */ private void m10500b(byte[] bArr, int i) { System.arraycopy(this.f12218a.mo42954a(), 0, bArr, i, 11); System.arraycopy(this.f12219b.data(), 0, bArr, i + 11, 32); } /* renamed from: a */ public void writeTypeAndData(StreamWriter streamWriter) throws IOException { streamWriter.write((byte) getCTxDestinationType().getValue()); super.serialToStream(streamWriter); } /* renamed from: a */ public void mo9424a(SeriableData seriableData, boolean z) throws IOException { if (z) { CTxDestinationType a = CTxDestinationType.getDesType(seriableData.readByte()); if (a != CTxDestinationType.ANONYMOUST_KEY) { throw new IOException(String.format(Locale.getDefault(), "CTxDestination type %s not ANONYMOUST_KEY", new Object[]{a.name()})); } } super.decodeSerialStream(seriableData); mo43016d(); } /* renamed from: c */ public String getHash() { byte[] bArr = new byte[44]; bArr[0] = (byte) getCTxDestinationType().getValue(); m10500b(bArr, 1); return StringToolkit.bytesToString(bArr); } /* renamed from: b */ public CTxDestination clone() { return new SaplingPaymentAddress(this); } }
30.592391
178
0.610233
4b99dce308f3c403ce3218cdf3a37b3dde5f3f77
599
/** * Jakarta Bean Validation TCK * * License: Apache License, Version 2.0 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>. */ package org.hibernate.beanvalidation.tck.tests.constraints.application.method; import jakarta.validation.Valid; import jakarta.validation.constraints.NotNull; /** * @author Gunnar Morling */ public class User { @NotNull private String name; @Valid private final Account account; public User() { this.account = null; } public User(Account account) { this.name = "Bob"; this.account = account; } }
18.71875
98
0.719533
f8e8053fca10e6e24da59994ec09040ce2e1fd4b
1,552
/* * Copyright 2011 Goldman Sachs. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.gs.collections.impl.block.procedure; import java.util.Collection; import com.gs.collections.api.block.procedure.Procedure; /** * CollectionAddProcedure adds elements to the specified collection when one of the block methods are called. */ public final class CollectionAddProcedure<T> implements Procedure<T> { private static final long serialVersionUID = 1L; private final Collection<T> collection; public CollectionAddProcedure(Collection<T> newCollection) { this.collection = newCollection; } public static <T> CollectionAddProcedure<T> on(Collection<T> newCollection) { return new CollectionAddProcedure<T>(newCollection); } public void value(T object) { this.collection.add(object); } public Collection<T> getResult() { return this.collection; } @Override public String toString() { return "Collection.add()"; } }
26.758621
109
0.709407
cdeec66d736778bbdf77ff13ba717e9afe3c86b1
3,819
package eu.asterics.component.actuator.gui_tester; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JPanel; /* * AsTeRICS - Assistive Technology Rapid Integration and Construction Set * * * d8888 88888888888 8888888b. 8888888 .d8888b. .d8888b. * d88888 888 888 Y88b 888 d88P Y88b d88P Y88b * d88P888 888 888 888 888 888 888 Y88b. * d88P 888 .d8888b 888 .d88b. 888 d88P 888 888 "Y888b. * d88P 888 88K 888 d8P Y8b 8888888P" 888 888 "Y88b. * d88P 888 "Y8888b. 888 88888888 888 T88b 888 888 888 "888 * d8888888888 X88 888 Y8b. 888 T88b 888 Y88b d88P Y88b d88P * d88P 888 88888P' 888 "Y8888 888 T88b 8888888 "Y8888P" "Y8888P" * * * homepage: http://www.asterics.org * * This project has been partly funded by the European Commission, * Grant Agreement Number 247730 * * * Dual License: MIT or GPL v3.0 with "CLASSPATH" exception * (please refer to the folder LICENSE) * */ /** * @author Konstantinos Kakousis * This class is part of the gui_tester plugin and demonstrates how Java * Graphics can be created and diplayed on the AsTeRICS Desktop. * * Date: Sep 16, 2011 */ public class PanelWithGraphics extends JPanel { private int X_MARGIN, Y_MARGIN, W_OFFSET, H_OFFSET, CHARS; private int x, y, w, h; public PanelWithGraphics() { setLayout (new FlowLayout(FlowLayout.LEFT)); //setBorder(BorderFactory.createTitledBorder("Graphics")); } //Each time the position changes we reset the coordinates so that our //graphics are always painted inside the parent container. public void repaint (int x, int y, int w, int h) { X_MARGIN = (int) (0.05 * w); Y_MARGIN = (int) (0.1 * w); W_OFFSET = (int) (0.1 * w); H_OFFSET = (int) (0.17 * h); this.x =x+X_MARGIN; this.y =y+Y_MARGIN; this.w = w-W_OFFSET; this.h = h-H_OFFSET; super.repaint(); } /** * Overrides the paintComponent method of JPanel. * It is called every time a repaint is called. * For this example we paint a rectangle as a frame, a string as title * and random circles */ public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //set color to black g.setColor(Color.BLACK); //draw a rectangle g.drawRect(x, y, w, h); for (int i = 0; i < 20; i++) { //set random color g.setColor(new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255))); g.fillOval(randomNumber(x, w+x-X_MARGIN, 1), randomNumber(y, h+y-Y_MARGIN, 1), W_OFFSET, W_OFFSET); } //set color to black g.setColor(Color.RED); //draw a string: the font size must be defined in terms of the //characters we wish to paint and the available space. CHARS = 25; int fontSize = y-x/CHARS; g2d.setFont(new Font ("Arial", 0, fontSize)); g.drawString("AsTeRICS Painting", x, y); } /** * Helper method that generates random numbers in the given range * @param min * @param max * @param offset * @return */ private int randomNumber (int min, int max, int offset) { int num = min + (int)(Math.random() * ((max - min) + offset)); return num; } }
29.604651
78
0.596491
7a1fae59510be7f57d5ec7c368e4f7f607c11a09
1,680
package com.example.commontask.ui; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import com.example.commontask.R; public class AddConversationDialogFragment extends DialogFragment { public static DialogFragment newInstance() { AddConversationDialogFragment addConversationDialogFragment = new AddConversationDialogFragment(); Bundle bundle = new Bundle(); addConversationDialogFragment.setArguments(bundle); return addConversationDialogFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getActivity().getLayoutInflater(); View rootView = inflater.inflate(R.layout.add_chat, null); /* Inflate and set the layout for the dialog */ /* Pass null as the parent view because its going in the dialog layout*/ builder.setView(rootView) /* Add action buttons */ .setPositiveButton("Create", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }); return builder.create(); } }
33.6
106
0.68869
9183fcaf3a4a70583df107cdf830e72330488f82
360
package me.sargunvohra.mcmods.alwaysdroploot.test; import net.minecraft.gametest.framework.GameTestHelper; public class TestUtil { public static void runCommand(GameTestHelper helper, String command) { var server = helper.getLevel().getServer(); server .getCommands() .performCommand(server.createCommandSourceStack(), command); } }
25.714286
72
0.752778
a7ecdf6478389aecfddbd8e6dfb1f6154047c59a
231
package com.qmt.okhttplibrary.network.downLoadFile; /** * Created by sunch on 2018/3/22. */ public interface ProgressListener { //已完成的 总的文件长度 是否完成 void onProgress(long currentBytes, long contentLength, boolean done); }
21
73
0.74026
ff62df73195bd4305d09458c1c72a1e92b276f73
5,473
package no.unit.nva.publication; import static java.lang.Integer.parseInt; import static no.unit.nva.publication.PublicationServiceConfig.dtoObjectMapper; import static nva.commons.core.attempt.Try.attempt; import com.fasterxml.jackson.databind.JsonNode; import java.net.URI; import no.unit.nva.identifiers.SortableIdentifier; import no.unit.nva.publication.exception.BadRequestException; import no.unit.nva.publication.storage.model.UserInstance; import nva.commons.apigateway.RequestInfo; import nva.commons.apigateway.exceptions.ApiGatewayException; import nva.commons.core.attempt.Try; import org.apache.logging.log4j.util.Strings; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public final class RequestUtil { public static final String IDENTIFIER = "identifier"; public static final String IDENTIFIER_IS_NOT_A_VALID_UUID = "Identifier is not a valid UUID: "; public static final String PAGESIZE_IS_NOT_A_VALID_POSITIVE_INTEGER = "pageSize is not a valid positive integer: "; public static final String AUTHORIZER_CLAIMS = "/authorizer/claims/"; public static final String CUSTOM_FEIDE_ID = "custom:feideId"; public static final String CUSTOM_CUSTOMER_ID = "custom:customerId"; public static final String MISSING_CLAIM_IN_REQUEST_CONTEXT = "Missing claim in requestContext: "; public static final String PAGESIZE = "pagesize"; public static final int DEFAULT_PAGESIZE = 10; private static final Logger logger = LoggerFactory.getLogger(RequestUtil.class); public static final String USING_DEFAULT_VALUE = ", using default value: "; private RequestUtil() { } /** * Get identifier from request path parameters. * * @param requestInfo requestInfo * @return the identifier * @throws ApiGatewayException exception thrown if value is missing */ public static SortableIdentifier getIdentifier(RequestInfo requestInfo) throws ApiGatewayException { String identifier = null; try { logger.info("Trying to read Publication identifier..."); identifier = requestInfo.getPathParameters().get(IDENTIFIER); logger.info("Requesting publication metadata for ID:" + identifier); return new SortableIdentifier(identifier); } catch (Exception e) { throw new BadRequestException(IDENTIFIER_IS_NOT_A_VALID_UUID + identifier, e); } } /** * Get customerId from requestContext authorizer claims. * * @param requestInfo requestInfo. * @return the customerId * @throws ApiGatewayException exception thrown if value is missing */ public static URI getCustomerId(RequestInfo requestInfo) throws ApiGatewayException { return requestInfo.getCustomerId() .map(attempt(URI::create)) .flatMap(Try::toOptional) .orElseThrow(() -> logErrorAndThrowException(requestInfo)); } private static BadRequestException logErrorAndThrowException(RequestInfo requestInfo) { String requestInfoJsonString = attempt(() -> dtoObjectMapper.writeValueAsString(requestInfo)).orElseThrow(); logger.debug("RequestInfo object:" + requestInfoJsonString); return new BadRequestException(MISSING_CLAIM_IN_REQUEST_CONTEXT + CUSTOM_CUSTOMER_ID); } /** * Get owner from requestContext authorizer claims. * * @param requestInfo requestInfo. * @return the owner * @throws ApiGatewayException exception thrown if value is missing */ public static String getOwner(RequestInfo requestInfo) throws ApiGatewayException { JsonNode jsonNode = requestInfo.getRequestContext().at(AUTHORIZER_CLAIMS + CUSTOM_FEIDE_ID); if (!jsonNode.isMissingNode()) { return jsonNode.textValue(); } throw new BadRequestException(MISSING_CLAIM_IN_REQUEST_CONTEXT + CUSTOM_FEIDE_ID, null); } /** * Get pagesize from request query parameters. * * @param requestInfo requestInfo * @return the pagesize if given, otherwise DEFAULT_PAGESIZE * @throws ApiGatewayException exception thrown if value is not legal positive integer */ public static int getPageSize(RequestInfo requestInfo) throws ApiGatewayException { String pagesizeString = null; try { logger.debug("Trying to read pagesize..."); pagesizeString = requestInfo.getQueryParameters().get(PAGESIZE); if (!Strings.isEmpty(pagesizeString)) { logger.debug("got pagesize='" + pagesizeString + "'"); int pageSize = parseInt(pagesizeString); if (pageSize > 0) { return pageSize; } else { throw new BadRequestException(PAGESIZE_IS_NOT_A_VALID_POSITIVE_INTEGER + pagesizeString, null); } } else { logger.debug(USING_DEFAULT_VALUE + DEFAULT_PAGESIZE); return DEFAULT_PAGESIZE; } } catch (Exception e) { throw new BadRequestException(PAGESIZE_IS_NOT_A_VALID_POSITIVE_INTEGER + pagesizeString, e); } } public static UserInstance extractUserInstance(RequestInfo requestInfo) { URI customerId = requestInfo.getCustomerId().map(URI::create).orElse(null); String useIdentifier = requestInfo.getFeideId().orElse(null); return new UserInstance(useIdentifier, customerId); } }
43.436508
119
0.701992
282d9be76657c47c17489707f35d379261bced9e
97
package miniprogram.server.service; public interface AllService { public void getcode(); }
13.857143
35
0.752577
1ea0897ccd90ec57f13c7a5aac512c2b730abeca
3,714
package uk.ac.ebi.interpro.scan.model; import javax.xml.bind.annotation.XmlTransient; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Implementation to assist with 'chunking' of long text fields. * Performs the tasks of splitting very long strings into * chunks and putting them back together again. * <p/> * Implemented as a Singleton, as this class has no state. * * @author Phil Jones * @version $Id$ * @since 1.0 */ @XmlTransient public class ChunkerSingleton implements Chunker { private static ChunkerSingleton ourInstance = new ChunkerSingleton(); public static ChunkerSingleton getInstance() { return ourInstance; } private ChunkerSingleton() { } /** * Concatenates a single String and a List of String into a single long * String. * * @param start first part of the String * @param chunks being the List<String> to concatenate * @return the concatenated String. */ public String concatenate(String start, List<String> chunks) { StringBuffer buf; if (start == null) { buf = new StringBuffer(); } else { buf = new StringBuffer(start); } if (chunks != null) { for (String chunk : chunks) { if (chunk != null) { buf.append(chunk); } } } return (buf.length() == 0) ? null : buf.toString(); } /** * Takes the String 'text' argument and splits * it into chunks, placed into the chunks List<String> * * @param text the long String to be 'chunked'. * @return List<String> into which the chunks are placed. */ public List<String> chunkIntoList(String text) { List<String> chunks = new ArrayList<String>(); if (text == null) { return Collections.emptyList(); } int chunkCount = (text.length() - 1) / CHUNK_SIZE; // The resulting value is one less than the number of chunks, but using this in the loop which starts at 0. for (int offset = 0; offset <= chunkCount; offset++) { if (offset < chunkCount) { chunks.add( text.substring(offset * CHUNK_SIZE, offset * CHUNK_SIZE + CHUNK_SIZE) ); } else { chunks.add( text.substring(offset * CHUNK_SIZE) ); } } return chunks; } /** * Takes a List<String> and returns the first * element, or null if not present. * * @param chunks from which first will be returned * @return the first * element, or null if not present. */ @Override public String firstChunk(List<String> chunks) { if (chunks == null || chunks.size() == 0) { return null; } return chunks.get(0); } /** * Takes a List<String> and returns all but the * first element in a new List<String>. * <p/> * Checks that the argument is not null and contains * more than one element, otherwise returns null. * * @param chunks to split. * @return a List<String> and returns all but the * first element in a new List<String>. * <p/> * Checks that the argument is not null and contains * more than one element, otherwise returns null. */ @Override public List<String> latterChunks(List<String> chunks) { if (chunks == null || chunks.size() < 2) { return null; } return new ArrayList<String>(chunks.subList(1, chunks.size())); } }
30.195122
168
0.572967
b64b05b67629a547ff6b264d00a6e8f375ec885c
1,933
package com.socion.entity.config; import com.socion.entity.dao.IamDao; import com.socion.entity.dao.KeycloakDao; import com.socion.entity.dao.RegistryDao; import okhttp3.OkHttpClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; import java.util.concurrent.TimeUnit; @Configuration public class ServiceConfiguration { @Autowired AppContext appContext; private OkHttpClient setClient() { OkHttpClient.Builder httpClient = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30L, TimeUnit.SECONDS) .writeTimeout(30L, TimeUnit.SECONDS); return httpClient.build(); } @Bean public IamDao initIam() { Retrofit retrofit = new Retrofit.Builder() .client(setClient()) .baseUrl(appContext.getIamBaseUrl()) .addConverterFactory(JacksonConverterFactory.create()) .build(); return retrofit.create(IamDao.class); } @Bean public RegistryDao initRegistry() { Retrofit retrofit = new Retrofit.Builder() .client(setClient()) .baseUrl(appContext.getRegistryBaseUrl()) .addConverterFactory(JacksonConverterFactory.create()) .build(); return retrofit.create(RegistryDao.class); } @Bean public KeycloakDao initKeyCloak() { Retrofit retrofit = new Retrofit.Builder() .client(setClient()) .baseUrl(appContext.getKeyCloakServiceUrl()) .addConverterFactory(JacksonConverterFactory.create()) .build(); return retrofit.create(KeycloakDao.class); } }
31.177419
70
0.662183
aad1e051dcad3f9d203011df78e861890e470f9a
352
package com.faasj.builder.dao; import com.faasj.builder.dto.BuildDto; import java.util.*; public interface BuildRepository { void save(UUID buildId, BuildDto buildDto); void delete(UUID buildId); Optional<String> findLogs(UUID buildId); Set<Map.Entry<UUID, String>> findLogs(); Optional<BuildDto> findBuild(UUID buildId); }
18.526316
47
0.724432
a240610e851c8d27480bf4ffe19005900457beb6
352
package org.gluu.casa.plugins.inwebo; enum CodeType { VALID_IMMEDIATELY_FOR_15_MINS(0), CODE_INATIVE_VALID_FOR_3_WEEEKS(1), ACTIVATION_LINK_VALID_FOR_3_WEEKS(2); private long codeType; private CodeType(final int codeType) { this.codeType = codeType; } public long getCodeType() { return codeType; } }
20.705882
42
0.693182
2644928beb834dc69880188b0e5bd4f0df9da183
1,147
package com.sweetpotatoclock.service.impl; import com.sweetpotatoclock.dao.GoalDayCompleteMapper; import com.sweetpotatoclock.entity.GoalComplete; import com.sweetpotatoclock.entity.GoalDayComplete; import com.sweetpotatoclock.service.GoalDayCompleteService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; import java.util.List; @Service public class GoalDayCompleteServiceimpl implements GoalDayCompleteService { @Autowired private GoalDayCompleteMapper goalDayCompleteMapper; @Autowired private GoalComplete goalComplete; @Override public List<GoalDayComplete> getGoalDayCompleteByUserId(String userId) { return goalDayCompleteMapper.selectByUserId(userId); } @Override public Boolean addGoalDayComplete(GoalDayComplete goalDayComplete) { Date date= new Date(); java.sql.Date date1 = new java.sql.Date(date.getTime()); goalDayComplete.setCompleteDate(date1); if(goalDayCompleteMapper.insert(goalDayComplete)==1){ return true; } return false; } }
31.861111
76
0.766347
30d31f1b4b9adbf9696faa186f05678be24273e5
4,001
package com.sparta.golam.model; import com.sparta.golam.controller.DateFormatter; import com.sparta.golam.controller.FilterIDs; import com.sparta.golam.model.Employee; import java.time.LocalDate; import java.util.ArrayList; public class EmployeeList { static ArrayList<String[]> startingData = FilterIDs.findOriginalIDs(); public static int dataSetSize = startingData.size(); static Employee[] employeeArray = new Employee[dataSetSize]; static Employee[] employeesq1; static Employee[] employeesq2; static Employee[] employeesq3; static Employee[] employeesq4; public static Employee[] createEmployeeArray() { for (int i = 0; i < dataSetSize; i++) { String[] data = startingData.get(i); int ID = Integer.parseInt(data[0]); int salary = Integer.parseInt(data[9]); LocalDate birth = DateFormatter.clean(data[7]); LocalDate join = DateFormatter.clean(data[8]); Employee employee = new Employee(ID, data[1], data[2], data[3], data[4], data[5], data[6], birth, join, salary); employeeArray[i] = employee; } return employeeArray; } public static void quarterArrays() { int dataQuarterSize = dataSetSize/4; int fourthArraySize = dataSetSize - (dataQuarterSize * 3); employeesq1 = new Employee[dataQuarterSize]; employeesq2 = new Employee[dataQuarterSize]; employeesq3 = new Employee[dataQuarterSize]; employeesq4 = new Employee[fourthArraySize]; for (int i = 0; i < dataSetSize; i++) { String[] data = startingData.get(i); int ID = Integer.parseInt(data[0]); int salary = Integer.parseInt(data[9]); LocalDate birth = DateFormatter.clean(data[7]); LocalDate join = DateFormatter.clean(data[8]); Employee employee = new Employee(ID, data[1], data[2], data[3], data[4], data[5], data[6], birth, join, salary); if (i < dataQuarterSize) { employeesq1[i] = employee; } else if (i < (dataQuarterSize * 2)) { employeesq2[i - (dataQuarterSize)] = employee; } else if (i >= (dataQuarterSize * 2) && i < (dataQuarterSize * 3)) { employeesq3[i - (dataQuarterSize * 2)] = employee; } else { employeesq4[i - (dataQuarterSize * 3)] = employee; } } } public static Employee[] customArray(int numberOfThreads, int start) { int blockSize = dataSetSize/numberOfThreads; Employee[] employees = new Employee[blockSize]; for (int i = start; i < (start+blockSize);i++) { String[] data = startingData.get(i); int ID = Integer.parseInt(data[0]); int salary = Integer.parseInt(data[9]); LocalDate birth = DateFormatter.clean(data[7]); LocalDate join = DateFormatter.clean(data[8]); Employee employee = new Employee(ID, data[1], data[2], data[3], data[4], data[5], data[6], birth, join, salary); employees[i - start] = employee; } return employees; } public static Employee[] leftOver(int numberOfThreads) { int blockSize = dataSetSize/numberOfThreads; int leftOverSize = dataSetSize - (blockSize*(numberOfThreads-1)); Employee[] employees = new Employee[leftOverSize]; int start = dataSetSize - leftOverSize; for (int i = start; i < dataSetSize; i++) { String[] data = startingData.get(i); int ID = Integer.parseInt(data[0]); int salary = Integer.parseInt(data[9]); LocalDate birth = DateFormatter.clean(data[7]); LocalDate join = DateFormatter.clean(data[8]); Employee employee = new Employee(ID, data[1], data[2], data[3], data[4], data[5], data[6], birth, join, salary); employees[i - start] = employee; } return employees; } }
42.56383
124
0.604599
97d7c9d0dada4f0714548d57eacaaa65ee46c5b4
1,362
package ba.wave.wavebackend.model.user; import com.fasterxml.jackson.annotation.JsonBackReference; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Set; @Entity public class Role { @Id @Column(name = "ID") @GeneratedValue(strategy = GenerationType.AUTO, generator = "native") @GenericGenerator(name = "native", strategy = "native") private Long id; @Column(name = "NAME", length = 50, unique = true) @NotNull @Enumerated(EnumType.STRING) private RoleName name; @JsonBackReference @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE}) private Set<User> users; public Role() { } public Role(final RoleName name) { this.name = name; } public Role(RoleName name, Set<User> users) { this.name = name; this.users = users; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public RoleName getName() { return name; } public void setName(RoleName name) { this.name = name; } public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
20.953846
111
0.631424
24a99739d2ed7b987d943552feff5965493347bc
1,571
package com.agonyforge.core.model; import org.hibernate.annotations.GenericGenerator; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import java.util.Objects; import java.util.UUID; @Entity public class Creature { @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Column(columnDefinition = "BINARY(16)") private UUID id; private String name; @OneToOne(cascade = CascadeType.ALL) private Connection connection; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Connection getConnection() { return connection; } public void setConnection(Connection connection) { this.connection = connection; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Creature)) return false; Creature creature = (Creature) o; return Objects.equals(getId(), creature.getId()) && Objects.equals(getName(), creature.getName()) && Objects.equals(getConnection(), creature.getConnection()); } @Override public int hashCode() { return Objects.hash(getId(), getName(), getConnection()); } }
23.80303
70
0.653724
14175ac73ac684b9cb35826b65b54baf97335357
2,415
package com.xxmassdeveloper.mpchartexample.realm; import android.os.Bundle; import android.view.WindowManager; import com.github.mikephil.charting.animation.Easing; import com.github.mikephil.charting.charts.ScatterChart; import com.github.mikephil.charting.data.ScatterData; import com.github.mikephil.charting.data.realm.implementation.RealmScatterDataSet; import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet; import com.github.mikephil.charting.utils.ColorTemplate; import com.xxmassdeveloper.mpchartexample.R; import com.xxmassdeveloper.mpchartexample.custom.RealmDemoData; import java.util.ArrayList; import io.realm.RealmResults; /** * Created by Philipp Jahoda on 21/10/15. */ public class RealmDatabaseActivityScatter extends RealmBaseActivity { private ScatterChart mChart; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_scatterchart_noseekbar); mChart = (ScatterChart) findViewById(R.id.chart1); setup(mChart); mChart.getAxisLeft().setDrawGridLines(false); mChart.getXAxis().setDrawGridLines(false); mChart.setPinchZoom(true); } @Override protected void onResume() { super.onResume(); // setup realm // write some demo-data into the realm.io database writeToDB(45); // add data to the chart setData(); } private void setData() { RealmResults<RealmDemoData> result = mRealm.where(RealmDemoData.class).findAll(); RealmScatterDataSet<RealmDemoData> set = new RealmScatterDataSet<RealmDemoData>(result, "xValue", "yValue"); set.setLabel("Realm ScatterDataSet"); set.setScatterShapeSize(9f); set.setColor(ColorTemplate.rgb("#CDDC39")); set.setScatterShape(ScatterChart.ScatterShape.CIRCLE); ArrayList<IScatterDataSet> dataSets = new ArrayList<IScatterDataSet>(); dataSets.add(set); // add the dataset // create a data object with the dataset list ScatterData data = new ScatterData(dataSets); styleData(data); // set data mChart.setData(data); mChart.animateY(1400, Easing.EasingOption.EaseInOutQuart); } }
32.635135
116
0.720911
a0baab210987ea13e15e547674f179e0c02436b1
7,799
package vivo.learn.rime.pedomap; import android.Manifest; import android.content.pm.PackageManager; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map.BaiduMap; import com.baidu.mapapi.map.MapStatusUpdate; import com.baidu.mapapi.map.MapStatusUpdateFactory; import com.baidu.mapapi.map.MapView; import com.baidu.mapapi.map.MyLocationData; import com.baidu.mapapi.model.LatLng; public class MainActivity extends AppCompatActivity { //view TextView mBaiduLocationText; TextView mSensorText; //sensor SensorManager mSensorManager; Sensor mStepCountSensor; Sensor mStepDetectSensor; SensorEventListener mSensorEventListener; //map private MapView mMapView = null; private BaiduMap mBaiduMap = null; private LocationClient mLocationClient = null; //location listener private BDLocationListener baiduLocationListener; //first open app private boolean isFirstLocate = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); //view mBaiduLocationText = (TextView) findViewById(R.id.text_baidu_location); mSensorText = (TextView) findViewById(R.id.text_step_count); //Sensor mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mStepCountSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER); mStepDetectSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR); mSensorEventListener = new MyListener(); //baidumap mMapView = (MapView) findViewById(R.id.map_view_baidu); mBaiduMap = mMapView.getMap(); initMap(); //location mLocationClient = new LocationClient(getApplicationContext()); mBaiduMap.setMyLocationEnabled(true); //location listener baiduLocationListener = new BaiduLocationListener(); } @Override protected void onStart() { super.onStart(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } //baidu map mLocationClient.registerLocationListener(baiduLocationListener); initLocation(); mLocationClient.start(); } @Override protected void onResume() { super.onResume(); mMapView.onResume(); mSensorManager.registerListener(mSensorEventListener, mStepDetectSensor, SensorManager.SENSOR_DELAY_NORMAL); mSensorManager.registerListener(mSensorEventListener, mStepCountSensor, SensorManager.SENSOR_DELAY_NORMAL); } @Override protected void onPause() { super.onPause(); mMapView.onPause(); mSensorManager.unregisterListener(mSensorEventListener); } @Override protected void onStop() { mLocationClient.stop(); mLocationClient.unRegisterLocationListener(baiduLocationListener); super.onStop(); } @Override protected void onDestroy() { super.onDestroy(); mBaiduMap.setMyLocationEnabled(false); mMapView.onDestroy(); } /* * baidu map initialize */ private void initMap() { mMapView.showZoomControls(false); } /* * baidu location client initialize */ private void initLocation() { LocationClientOption option = new LocationClientOption(); option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy); option.setCoorType("bd09ll"); option.setScanSpan(1000); option.setOpenGps(true); option.setLocationNotify(true); option.setIsNeedAddress(true); mLocationClient.setLocOption(option); } /* * map move to a location */ private void navigateTo(BDLocation bdLocation) { if (isFirstLocate) { LatLng latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude()); float zoomLevel = 19f; MapStatusUpdate update = MapStatusUpdateFactory.newLatLngZoom(latLng, zoomLevel); mBaiduMap.animateMapStatus(update); isFirstLocate = false; } MyLocationData.Builder locationBuilder = new MyLocationData.Builder(); locationBuilder.latitude(bdLocation.getLatitude()); locationBuilder.longitude(bdLocation.getLongitude()); MyLocationData locationData = locationBuilder.build(); mBaiduMap.setMyLocationData(locationData); } /* * sensor listener */ private class MyListener implements SensorEventListener { @Override public void onSensorChanged(SensorEvent sensorEvent) { int sensorType = sensorEvent.sensor.getType(); switch (sensorType) { case Sensor.TYPE_STEP_COUNTER: // mSensorText.setText(String.valueOf((int) sensorEvent.values[0])); break; case Sensor.TYPE_STEP_DETECTOR: mSensorText.append(String.valueOf((int) sensorEvent.values[0])); break; default: } } @Override public void onAccuracyChanged(Sensor sensor, int i) { } } /* * Baidu location listener */ private class BaiduLocationListener implements BDLocationListener { @Override public void onReceiveLocation(final BDLocation bdLocation) { runOnUiThread(new Runnable() { @Override public void run() { double longitude = bdLocation.getLongitude(); double latitude = bdLocation.getLatitude(); navigateTo(bdLocation); String lon = String.format("%.6f", longitude); String lat = String.format("%.6f", latitude); mBaiduLocationText.setText("baidu-(" + lon + "," + lat + ")\n"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(bdLocation.getLocationDescribe()); stringBuilder.append(bdLocation.getDistrict() + "\n"); stringBuilder.append(bdLocation.getLocTypeDescription() + "\n"); stringBuilder.append(String.valueOf(bdLocation.getSatelliteNumber()) + "\n"); stringBuilder.append(bdLocation.getLocationDescribe()); mBaiduLocationText.append(stringBuilder.toString()); } }); } } }
35.940092
259
0.660341
bdd7547270111cb9c7d9f3859113d233875e867b
405
package space.pxls.palette; import java.util.List; public class Palette { protected List<Color> colors; protected byte defaultColorIndex; public Palette(List<Color> colors, byte defaultColorIndex) { this.colors = colors; this.defaultColorIndex = defaultColorIndex; } public List<Color> getColors() { return colors; } public byte getDefaultColorIndex() { return defaultColorIndex; } }
18.409091
61
0.753086
00bfc9bc17345ac2d8fd993637974238188cc90d
15,421
package com.example.nctai_trading; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.gson.Gson; import com.mongodb.BasicDBObject; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import net.sargue.mailgun.Configuration; import net.sargue.mailgun.Mail; import org.bson.Document; import org.bson.types.ObjectId; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.regex.*; public class signUpPage extends AppCompatActivity { Button confirmButton; Button backButton; EditText usernameText; EditText emailText; EditText passwordText; EditText confirmPasswordText; EditText firstNameText; EditText lastNameText; private String hashedPassword = ""; private Object invokeObject; // TODO: [SIGN UP PAGE] run a thread in the background if they type in a password that isn't valid then it tells them and also if they type in a different password in confirm password @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AlertDialog.Builder emailInvalidAlert = new AlertDialog.Builder(this); emailInvalidAlert.setTitle("Email invalid"); emailInvalidAlert.setMessage("Email provided was invalid."); AlertDialog.Builder emailLengthAlert = new AlertDialog.Builder(this); emailLengthAlert.setTitle("Email invalid"); emailLengthAlert.setMessage("Provide an email address"); AlertDialog.Builder emailAlreadyExistsAlert = new AlertDialog.Builder(this); emailAlreadyExistsAlert.setTitle("Email invalid"); emailAlreadyExistsAlert.setMessage("Email already exists"); AlertDialog.Builder usernameLengthAlert = new AlertDialog.Builder(this); usernameLengthAlert.setTitle("Username Invalid"); usernameLengthAlert.setMessage("Username must contain characters"); AlertDialog.Builder passwordLengthAlert = new AlertDialog.Builder(this); passwordLengthAlert.setTitle("Password Invalid"); passwordLengthAlert.setMessage("Password must contain characters"); AlertDialog.Builder firstNameLengthAlert = new AlertDialog.Builder(this); firstNameLengthAlert.setTitle("First Name Input Invalid"); firstNameLengthAlert.setMessage("First Name length must be > 0"); AlertDialog.Builder lastNameLengthAlert = new AlertDialog.Builder(this); lastNameLengthAlert.setTitle("Last Name Input Invalid"); lastNameLengthAlert.setMessage("Last Name length must be > 0"); AlertDialog.Builder confirmPasswordAlert = new AlertDialog.Builder(this); confirmPasswordAlert.setTitle("Password invalid"); confirmPasswordAlert.setMessage("Both passwords must be the same"); setContentView(R.layout.activity_sign_up_page); confirmButton = findViewById(R.id.signUpPageConfirmBtn); backButton = findViewById(R.id.signUpPageBackBtn); usernameText = findViewById(R.id.signUpUsernameEditText); emailText = findViewById(R.id.signUpEmailEditText); passwordText = findViewById(R.id.signUpPasswordEditText); confirmPasswordText = findViewById(R.id.signUpConfirmPasswordEditText); firstNameText = findViewById(R.id.signUpFirstNameEditText); lastNameText = findViewById(R.id.signUpLastNameEditText); Pattern emailValidator = Pattern.compile("^(.+)@(.+)$"); // TODO: [SIGN UP PAGE] Create confirm button to operate correctly (if operating uncorrectly) // TODO: [SIGN UP PAGE] Create back button to operate correctly (if operating uncorrectly) confirmButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ String usernameContent = usernameText.getText().toString().trim(); String emailContent = emailText.getText().toString().trim(); String passwordContent = passwordText.getText().toString().trim(); String confirmPasswordContent = confirmPasswordText.getText().toString().trim(); String firstNameContent = firstNameText.getText().toString().trim(); String lastNameContent = lastNameText.getText().toString().trim(); if(!passwordContent.equals(confirmPasswordContent)){ confirmPasswordAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(signUpPage.this,"Passwords must be the same",Toast.LENGTH_SHORT).show(); } }); confirmPasswordAlert.setCancelable(true); confirmPasswordAlert.create().show(); return ; } MongoClientURI uri = new MongoClientURI("mongodb://admin:CompeteToWin*[email protected]:27017,cluster0-shard-00-01.jhtaz.mongodb.net:27017,cluster0-shard-00-02.jhtaz.mongodb.net:27017/test?ssl=true&replicaSet=atlas-79gy36-shard-0&authSource=admin&retryWrites=true&w=majority"); MongoClient mongoClient = new MongoClient(uri); MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> coll = null; for(String name: database.listCollectionNames()){ if(name.equals("user")){ coll = database.getCollection(name); break; } } BasicDBObject emailQuery = new BasicDBObject(); emailQuery.put("email",emailContent); FindIterable<Document> emailID = coll.find(emailQuery); Document emailResult = emailID.first(); if(!(emailResult == null)){ emailAlreadyExistsAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(signUpPage.this,"The email already exists",Toast.LENGTH_SHORT).show(); } }); emailAlreadyExistsAlert.setCancelable(true); emailAlreadyExistsAlert.create().show(); return ; } Matcher emailMatcher = emailValidator.matcher(emailContent); //if(!emailMatcher.matches() || !Patterns.EMAIL_ADDRESS.matcher(emailContent).matches()){ // emailInvalidAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialog, int which) { // Toast.makeText(signUpPage.this,"Please edit your email",Toast.LENGTH_SHORT).show(); // } // }); // emailInvalidAlert.setCancelable(true); // emailInvalidAlert.create().show(); // return ; //} if(emailContent.length() < 1){ emailLengthAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(signUpPage.this,"Please enter an email address",Toast.LENGTH_LONG).show(); } }); emailLengthAlert.setCancelable(true); emailLengthAlert.create().show(); return ; } if(usernameContent.length() < 1){ // || username does not confine to standards usernameLengthAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(signUpPage.this,"The username must contain characters",Toast.LENGTH_SHORT).show(); } }); usernameLengthAlert.setCancelable(true); usernameLengthAlert.create().show(); return ; } if(passwordContent.length() < 1){ // TODO: [SIGN UP PAGE] || !passwordContent.equals(confirmPasswordContent) || password does not confine to standards passwordLengthAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(signUpPage.this,"Password must contain characters",Toast.LENGTH_SHORT).show(); } }); passwordLengthAlert.setCancelable(true); passwordLengthAlert.create().show(); return ; } if(firstNameContent.length() < 1){ firstNameLengthAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(signUpPage.this,"First name must contain characters",Toast.LENGTH_SHORT).show(); } }); firstNameLengthAlert.setCancelable(true); firstNameLengthAlert.create().show(); return ; } if(lastNameContent.length() < 1){ lastNameLengthAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(signUpPage.this,"Last name length must be > 0",Toast.LENGTH_SHORT).show(); } }); lastNameLengthAlert.setCancelable(true); lastNameLengthAlert.create().show(); return ; } Class c = null; Method method = null; com.example.nctai_trading.passwordFormula passwordFormulaInstance = new passwordFormula(); try { c = Class.forName("com.example.nctai_trading.passwordFormula"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { Object obj = c.newInstance(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } try { method = c.getDeclaredMethod("passwordHasher",new Class[]{String.class}); } catch (NoSuchMethodException e) { e.printStackTrace(); } method.setAccessible(true); // make sure try { signUpPage.this.invokeObject = method.invoke(passwordFormulaInstance,passwordContent); signUpPage.this.hashedPassword = signUpPage.this.invokeObject.toString(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } /// TODO: [IMPORTANT : SIGN UP PAGE] initiate putting username and password into database, along with firstname and lastname, then switch back to sign in screen, //List<Document> documentList = new ArrayList<>(); // TODO: [MAILGUN IMPLEMENTATION] Display message saying that an email has been sent to their email address, then add a link and that will verify them, or add an code and then I will create a separate page which will have two credentials to be entered: email and verification code, if they enter the correct verification code then the data in the database is switched to verified ObjectId _id = new ObjectId(); ObjectId userID = new ObjectId(); ObjectId wallet = new ObjectId(); Gson gson = new Gson(); Document createdUser = new Document("_id",_id); //createdUser.append("twoFactor",new Object[]{new Document("active",false),new Document("secret","")}); createdUser.append("email",emailContent); createdUser.append("password",hashedPassword); createdUser.append("wallet",wallet); createdUser.append("userID",userID); SharedPreferences sharedPreferences = getSharedPreferences("test",MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); String _idStr = gson.toJson(_id); String userIdStr = gson.toJson(userID); editor.putString("MongoUserId",userIdStr); editor.putString("Mongo_ID",_idStr); editor.apply(); editor.commit(); //documentList.add(createdUser); //coll.insertMany(documentList); coll.insertOne(createdUser); //Configuration configuration = new Configuration() // .domain("nextcapitaltech.com") // .apiKey("key-XXXXXX") // .from("Test account", "[email protected]"); //Mail.using(configuration) // .to(emailContent) // .subject("Next Capital Tech Verification Email") // .text("Verification code : ######") // .build() // .send(); // createdUser.append("emailVerify", false); // updated username when credentials are created Intent toMainActivity = new Intent(getApplicationContext(),MainActivity.class); startActivity(toMainActivity); } }); backButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent toMainActivity2 = new Intent(getApplicationContext(),MainActivity.class); startActivity(toMainActivity2); } }); } }
44.313218
395
0.591985
ddc1b990362f0a2345f786cf1d76e89b6447eca0
360
package com.claireshu.nysearchtimes_; import android.content.Context; import android.graphics.Typeface; /** * Created by claireshu on 6/23/16. */ public class StaticUtils { public static Typeface sTypeFace(Context context) { Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/sourcesanspro.otf"); return font; } }
24
97
0.725
822a756bf0180af313b462bfbd3f16d968689f99
4,223
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands; import java.util.List; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.controller.RamseteController; import edu.wpi.first.math.controller.SimpleMotorFeedforward; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.trajectory.Trajectory; import edu.wpi.first.math.trajectory.TrajectoryConfig; import edu.wpi.first.math.trajectory.TrajectoryGenerator; import edu.wpi.first.math.trajectory.constraint.DifferentialDriveVoltageConstraint; import edu.wpi.first.wpilibj2.command.RamseteCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import frc.robot.Constants; import frc.robot.subsystems.Carousel; import frc.robot.subsystems.DriveTrain; import frc.robot.subsystems.Intake; import frc.robot.subsystems.Shooter; public class EightBallAuto extends SequentialCommandGroup implements AutoCommandInterface { Pose2d m_initialPose; public EightBallAuto( DriveTrain robotDrive, Shooter shooter, Intake intake, DeployIntake deployIntake, Carousel carousel, DriveCommand driveCommand, CarouselCommand carouselCommand ) { driveCommand.cancel(); intake.run(0.4); // IntakeCommand intakeCommand = new IntakeCommand(intake, 0.5); TurnAndShoot shoot1 = new TurnAndShoot(robotDrive, shooter, carousel, carouselCommand, driveCommand, false); TurnAndShoot shoot2 = new TurnAndShoot(robotDrive, shooter, carousel, carouselCommand, driveCommand, false); var autoVoltageConstraint = new DifferentialDriveVoltageConstraint( new SimpleMotorFeedforward(Constants.ksVolts, Constants.kvVoltSecondsPerMeter, Constants.kaVoltSecondsSquaredPerMeter), Constants.kDriveKinematics, 10); TrajectoryConfig configForward = new TrajectoryConfig(Constants.kMaxSpeed, Constants.kMaxAcceleration) .setKinematics(Constants.kDriveKinematics) .addConstraint(autoVoltageConstraint); TrajectoryConfig configBackward = new TrajectoryConfig(Constants.kMaxSpeed, Constants.kMaxAcceleration) .setKinematics(Constants.kDriveKinematics) .addConstraint(autoVoltageConstraint) .setReversed(true); Trajectory comeBackTrajectory = TrajectoryGenerator.generateTrajectory( // Start at the origin facing the +X direction new Pose2d(-6.5, -0.63, new Rotation2d(-10)), List.of( //new Translation2d(-1.2, -0.63) ), new Pose2d(-4.2, -0.63, Rotation2d.fromDegrees(10)), configForward ); RamseteCommand ramseteCommand = new RamseteCommand( comeBackTrajectory, robotDrive::getPose, new RamseteController(Constants.kRamseteB, Constants.kRamseteZeta), new SimpleMotorFeedforward(Constants.ksVolts, Constants.kvVoltSecondsPerMeter, Constants.kaVoltSecondsSquaredPerMeter), Constants.kDriveKinematics, robotDrive::getWheelSpeeds, new PIDController(Constants.kPDriveVel, 0, 0), new PIDController(Constants.kPDriveVel, 0, 0), robotDrive::tankDriveVolts, robotDrive ); addCommands( deployIntake.alongWith(shoot1), new EBInitialTrajectory(robotDrive, configBackward).andThen(() -> robotDrive.tankDriveVolts(0, 0)), ramseteCommand.andThen(() -> robotDrive.tankDriveVolts(0, 0)), shoot2 ); } public Pose2d getInitialPose() { return m_initialPose; } }
42.656566
112
0.655932
453ac0528afdf399bcec2d0adb03d6664c46e728
2,612
package com.tryme; import java.io.IOException; import java.io.PrintWriter; import java.text.DecimalFormat; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.tryme.*;; /** * Servlet implementation class DemoServlet */ @WebServlet("/demo") public class DemoServlet extends HttpServlet { static int age; static double weight; static double height; static String activity; static double morning; static double lunch; static double dinner; static int minutes; static double met; static int x; public void service(HttpServletRequest req, HttpServletResponse res) throws IOException { DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(2); PrintWriter out=res.getWriter(); age= Integer.parseInt(req.getParameter("age")); weight= Double.parseDouble(req.getParameter("weight")); height= Double.parseDouble(req.getParameter("height")); // activity= req.getParameter("activities"); activity="active"; morning= Double.parseDouble(req.getParameter("morning")); lunch= Double.parseDouble(req.getParameter("lunch")); dinner= Double.parseDouble(req.getParameter("dinner")); minutes= Integer.parseInt(req.getParameter("minutes")); //call //AboutmeServlet.tee(); //AboutmeServlet.consumed_calories(morning, lunch, dinner); //AboutmeServlet.activities_calories(minutes, weight); // store the values of methods // double everyday_calorie= Integer.parseInt((df.format(AboutmeServlet.tee()))); // double consumed_calorie= Integer.parseInt((df.format(AboutmeServlet.consumed_calories(morning,lunch,dinner)))); // double activities_calorie= Integer.parseInt((df.format(AboutmeServlet.activities_calories(minutes,weight)))); // set value so it can be forwarded to JSP // req.setAttribute("everyday_calorie",everyday_calorie); // req.setAttribute("consumed_calorie",consumed_calorie); // req.setAttribute("activities_calorie",activities_calorie); // forward it to JSP RequestDispatcher disp = req.getRequestDispatcher("/plan.jsp"); try { disp.forward(req, res); } catch (ServletException | IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
30.729412
125
0.692956
41484463b522183301fd3e02b6758050e232f7d0
7,848
1、CardView 的使用方法: (1)本质上是 FrameLayout, 只不过多了圆角和阴影等效果。 (2)布局代码如下: <?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/cardview" app:elevation="5dp" app:cardCornerRadius="4dp"> <TextView android:id="@+id/info_text" android:text="dumin" android:layout_width="match_parent" android:layout_height="wrap_content" /> </android.support.v7.widget.CardView> 2、AppBarLayout 的使用方法: (1)本质上是垂直的 LinearLayout,内部做了很多事件的封装。 (2)布局代码如下: <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:layout_scrollFlags="scroll|enterAlways|snap" /> </android.support.design.widget.AppBarLayout> (3)代码解析: app:layout_scrollFlags="scroll|enterAlways|snap" /> -> scroll: RecycleView 向上滚动时,Toolbar 会跟着向上滚动并实现隐藏。 -> enterAlways:RecycleView 向下滚动时,Toolbar 会跟着向下滚动并重新显示。 -> snap:当 Toolbar 还没有完全显示或者隐藏时,会根据滚动距离自动选择隐藏还是显示。 3、SwipeRefreshLayout 的使用方法: (1)布局代码如下: <android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swipe_refresh" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <android.support.v7.widget.RecyclerView android:id="@+id/recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.v4.widget.SwipeRefreshLayout> (2)刷新的监听事件代码如下: swipeRefresh = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh); swipeRefresh.setColorSchemeResources(R.color.colorPrimary);//设置刷新进度条的颜色 swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshFruits(); } }); 4、CollapsingToolbarLayout 的使用方法: (1)布局代码如下: <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:id="@+id/appBar" android:layout_width="match_parent" android:layout_height="250dp" android:fitsSystemWindows="true"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="match_parent" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" android:fitsSystemWindows="true" app:contentScrim="?attr/colorPrimary" //趋于折叠状态以及折叠之后的背景色 app:layout_scrollFlags="scroll|exitUntilCollapsed"> <ImageView android:id="@+id/fruit_image_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop" android:fitsSystemWindows="true" app:layout_collapseMode="parallax" /> //折叠模式:parallax表示在折叠过程中会产生一定的位移。 <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" /> //折叠模式:pin表示在折叠过程中位置不发生改变。 </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="35dp" app:cardCornerRadius="4dp"> <TextView android:id="@+id/fruit_content_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" /> </android.support.v7.widget.CardView> </LinearLayout> </android.support.v4.widget.NestedScrollView> <android.support.design.widget.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:src="@drawable/ic_comment" app:layout_anchor="@id/appBar" app:layout_anchorGravity="bottom|end" /> </android.support.design.widget.CoordinatorLayout> (2)刷新的监听事件代码如下: 5、NestedScrollView 的使用方法: (1)布局代码如下: <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="15dp" android:layout_marginLeft="15dp" android:layout_marginRight="15dp" android:layout_marginTop="35dp" app:cardCornerRadius="4dp"> <TextView android:id="@+id/fruit_content_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" /> </android.support.v7.widget.CardView> </LinearLayout> </android.support.v4.widget.NestedScrollView> (2)刷新的监听事件代码如下:
46.43787
101
0.585754
0bbafc38f26f65c8423658bec6f27c21b506d6b4
3,797
package com.arun.externaldatabsedemo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; public class DataBaseHelper extends SQLiteOpenHelper { private static SQLiteDatabase sqliteDb; private static DataBaseHelper instance; private static final int DATABASE_VERSION = 1; private Context context; static Cursor cursor = null; DataBaseHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); this.context = context; } private static void initialize(Context context, String databaseName) { if (instance == null) { if (!checkDatabase(context, databaseName)) { try { copyDataBase(context, databaseName); } catch (IOException e) { System.out.println( databaseName + " does not exists "); } } instance = new DataBaseHelper(context, databaseName, null, DATABASE_VERSION); sqliteDb = instance.getWritableDatabase(); System.out.println("instance of " + databaseName + " created "); } } public static final DataBaseHelper getInstance(Context context, String databaseName) { initialize(context, databaseName); return instance; } public SQLiteDatabase getDatabase() { return sqliteDb; } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } private static void copyDataBase(Context aContext, String databaseName) throws IOException { InputStream myInput = aContext.getAssets().open(databaseName); String outFileName = getDatabasePath(aContext, databaseName); File f = new File("/data/data/" + aContext.getPackageName() + "/databases/"); if (!f.exists()) f.mkdir(); OutputStream myOutput = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } myOutput.flush(); myOutput.close(); myInput.close(); System.out.println(databaseName + " copied"); } public static boolean checkDatabase(Context aContext, String databaseName) { SQLiteDatabase checkDB = null; try { String myPath = getDatabasePath(aContext, databaseName); checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); checkDB.close(); } catch (SQLiteException e) { System.out.println(databaseName + " does not exists"); } return checkDB != null ? true : false; } private static String getDatabasePath(Context aContext, String databaseName) { return "/data/data/" + aContext.getPackageName() + "/databases/" + databaseName; } public static Cursor rawQuery(String query) { try { if (sqliteDb.isOpen()) { sqliteDb.close(); } sqliteDb = instance.getWritableDatabase(); cursor = null; cursor = sqliteDb.rawQuery(query, null); } catch (Exception e) { System.out.println("DB ERROR " + e.getMessage()); e.printStackTrace(); } return cursor; } public static void execute(String query) { try { if (sqliteDb.isOpen()) { sqliteDb.close(); } sqliteDb = instance.getWritableDatabase(); sqliteDb.execSQL(query); } catch (Exception e) { System.out.println("DB ERROR " + e.getMessage()); e.printStackTrace(); } } }
24.980263
80
0.687121
33ce5528acb9bc2539c4b46a2bd853b248e74850
637
package edu.sru.brian.tictactoegame; /** * File: AIInterface.java * @author Brian * * Description: Provides an interface for Tic Tac Toe AI. Classes can * implement new AI implementations. * */ public interface AIInterface { /** * Called when it is the AI players turn. Pass in the Game of Tic Tac Toe, * The Opponent's marker and the opponent's move as a 1 Dimensional position * of the board. * @param game * @param oppMark * @param oppMove * @return */ public int calculateNextMove(Game game, Markers oppMark, int oppMove); /** * Called when the game class is reset. */ public void reset(); }
21.233333
77
0.682889
1729f9b5f9b5cfc8f84c01559ad480e11d8b860e
2,063
/* (C) 2021 DragonSkulle */ package org.dragonskulle.renderer; import static org.dragonskulle.utils.Env.envInt; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.dragonskulle.settings.Settings; /** * Configurable renderer settings. * * @author Aurimas Blažulionis */ @Accessors(prefix = "m") @EqualsAndHashCode public class RendererSettings { /** * Target number of MSAA samples. If the picked physical device does not support this number of * samples, the highest number (that is not higher than the one provided) will be picked */ @Getter @Setter private int mMSAACount = envInt("MSAA_SAMPLES", 4); /** Target vertical blank (sync) mode. */ @Getter @Setter private VBlankMode mVBlankMode = VBlankMode.SINGLE_BUFFER; /** Constructor for {@link RendererSettings}. */ public RendererSettings() {} /** * Copy constructor fro {@link RendererSettings}. * * @param o other renderer settings instance. */ public RendererSettings(RendererSettings o) { mMSAACount = o.mMSAACount; mVBlankMode = o.mVBlankMode; } /** * Constructor for {@link RendererSettings}. * * @param sets settings instance to read the settings from. */ public RendererSettings(Settings sets) { int oldMSAA = mMSAACount; mMSAACount = sets.retrieveInteger("MSAA", mMSAACount); if (mMSAACount < 1) { mMSAACount = oldMSAA; } VBlankMode old = mVBlankMode; mVBlankMode = VBlankMode.fromInt(sets.retrieveInteger("VSync", mVBlankMode.getValue())); if (mVBlankMode == null) { mVBlankMode = old; } } /** * Write current renderer settings values to a settings instance. * * @param sets settings instance to write the values to. */ public void writeSettings(Settings sets) { sets.saveValue("MSAA", mMSAACount); sets.saveValue("VSync", mVBlankMode.getValue(), true); } }
29.471429
99
0.661173
33a161294d97e87e35f3418ded8cdc7d6f218e9f
1,253
package duke.data; import duke.exception.DukeException; import duke.exception.DukeFatalException; import duke.ui.card.ResultCard; import duke.ui.context.Context; public class Result extends Evidence { /** * Represents results of an investigation based on the treatment prescribed for a patient. * A Result object corresponds to the result of an investigation into the symptoms of a Patient, * the particular impression, as well as an integer between 1-4 representing the priority * or significance of the result. * Attributes: * @param name the result * @param impression the impression object the result is tagged to * @param summary a summary of the result * @param priority the priority level of the evidence */ public Result(String name, Impression impression, int priority, String summary) throws DukeException { super(name, impression, priority, summary); } //TODO return string in proper format @Override public String toReportString() { return toString(); } public ResultCard toCard() throws DukeFatalException { return new ResultCard(this); } @Override public Context toContext() { return Context.RESULT; } }
31.325
106
0.706305
3d92629470744e58ba2f92fe92e9dd50d57dc0ed
1,845
package tech.aistar.day14.practice; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * @author: Merlin * @time: 2020/8/7 16:06 */ public class MapPractice { public static void main(String[] args) throws ParseException { Scanner scanner = new Scanner(System.in); String value = scanner.nextLine(); int pairs = Integer.valueOf(value); Map<String, Date> map = new HashMap<>(); for (int i = 0; i < pairs; i++) { String no = scanner.nextLine(); String date = scanner.nextLine(); map.put(no, stringToDate(date)); } Date curDate = stringToDate("01/01/2014"); Calendar calendar = Calendar.getInstance(); calendar.setTime(curDate); calendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR) - 60); Set<String> empSet = map.keySet(); Iterator<String> empIterator = empSet.iterator(); List<String> setEmp = new ArrayList<>(); while (empIterator.hasNext()) { String empNo = empIterator.next(); Date birthDate = map.get(empNo); Calendar calendar1 = Calendar.getInstance(); calendar1.setTime(birthDate); if (calendar.compareTo(calendar1) >= 0) { setEmp.add(empNo); } } setEmp.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.compareTo(o2); } }); for (String s : setEmp) { System.out.println(s); } } public static Date stringToDate(String dataStr) throws ParseException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); return simpleDateFormat.parse(dataStr); } }
29.758065
79
0.58374
1e3f52a94807b03eedf93bcd36e59f2ff764c4f9
296
package engine.gameObject; /** * Interface allows an Object to be set to an Enabled or Disabled State * Also gets the ID of the Object. * @author Will * */ public interface IEnabled { public void enable (); public void disable (); public boolean isEnabled (); }
16.444444
71
0.64527
0120e59093e3b6345246effc989a1a66ead437b5
178
module jpasswd { requires java.sql; requires javafx.controls; requires javafx.fxml; opens com.halfegg.jpasswd to javafx.fxml; exports com.halfegg.jpasswd; }
19.777778
45
0.707865
7ed2a18142136fe4f6efaddecf260b15730b3392
388
package com.pdp.manager.service; import java.util.List; import com.pdp.manager.pojo.PsychotropicDrugDict; import com.pdp.manager.pojo.RecipelDrug; /** * 处方内药品业务接口 * @author LIXr * @date 20/11/17 */ public interface IRecipelDrugSerevice { public List<PsychotropicDrugDict> init(); public List<RecipelDrug> getRecipelDrugListByCardId(String patientIdcard); }
20.421053
76
0.737113
67901edbf3fa758fe847fea6f7c10b742b3f134e
2,801
import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class GrahamScan { static class Point { public double x; public double y; public Point(double x, double y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (!(o instanceof Point)) return false; Point p = (Point)o; return p.x == this.x && p.y == this.y; } } static double ccw(Point a, Point b, Point c) { return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); } static double polarAngle(Point origin, Point p) { return Math.atan2(p.y - origin.y, p.x - origin.x); } static List<Point> grahamScan(List<Point> gift) { gift = gift.stream() .distinct() .sorted(Comparator.comparingDouble(point -> -point.y)) .collect(Collectors.toList()); Point pivot = gift.get(0); // Sort the remaining Points based on the angle between the pivot and itself List<Point> hull = gift.subList(1, gift.size()); hull.sort(Comparator.comparingDouble(point -> polarAngle(point, pivot))); // The pivot is always on the hull hull.add(0, pivot); int n = hull.size(); int m = 1; for (int i = 2; i < n; i++) { while (ccw(hull.get(m - 1), hull.get(m), hull.get(i)) <= 0) { if (m > 1) { m--; } else if (m == 1) { break; } else { i++; } } m++; Point temp = hull.get(i); hull.set(i, hull.get(m)); hull.set(m, temp); } return hull.subList(0, m + 1); } public static void main(String[] args) { ArrayList<Point> points = new ArrayList<>(); points.add(new Point(-5, 2)); points.add(new Point(5, 7)); points.add(new Point(-6, -12)); points.add(new Point(-14, -14)); points.add(new Point(9, 9)); points.add(new Point(-1, -1)); points.add(new Point(-10, 11)); points.add(new Point(-6, 15)); points.add(new Point(-6, -8)); points.add(new Point(15, -9)); points.add(new Point(7, -7)); points.add(new Point(-2, -9)); points.add(new Point(6, -5)); points.add(new Point(0, 14)); points.add(new Point(2, 8)); List<Point> convexHull = grahamScan(points); convexHull.forEach(p -> System.out.printf("% 1.0f, % 1.0f\n", p.x, p.y)); } }
29.177083
84
0.489111
affc2c67c0c2000a575c5373213a799e0d129271
3,569
package org.ukettle.basics.page.dialect.db; import java.util.List; import org.ukettle.basics.page.Sorting; import org.ukettle.basics.page.dialect.Dialect; import org.ukettle.basics.page.plugin.BaseParameter; import org.ukettle.www.toolkit.StringUtils; /** * Sql 2005的方言实现 * * @author Kimi Liu * @Date Aug 18, 2014 * @Time 11:50:21 * @email [email protected] * @version 1.0 * @since JDK 1.6 */ public class SQLServer2005Dialect implements Dialect { @Override public boolean limit() { return true; } @Override public String getLimit(String sql, int offset, int limit) { return getLimit(sql, offset, limit, Integer.toString(limit)); } /** * Add a LIMIT clause to the given SQL SELECT * <p/> * The LIMIT SQL will look like: * <p/> * WITH query AS (SELECT TOP 100 percent ROW_NUMBER() OVER (ORDER BY * CURRENT_TIMESTAMP) as __row_number__, * from table_name) SELECT * FROM * query WHERE __row_number__ BETWEEN :offset and :lastRows ORDER BY * __row_number__ * * @param querySqlString * The SQL statement to base the limit query off of. * @param offset * Offset of the first row to be returned by the query * (zero-based) * @param limit * Maximum number of rows to be returned by the query * @param limitPlaceholder * limitPlaceholder * @return A new SQL statement with the LIMIT clause applied. */ private String getLimit(String querySqlString, int offset, int limit, String limitPlaceholder) { StringBuilder pagingBuilder = new StringBuilder(); String orderby = getOrderByPart(querySqlString); String distinctStr = ""; String loweredString = querySqlString.toLowerCase(); String sqlPartString = querySqlString; if (loweredString.trim().startsWith("select")) { int index = 6; if (loweredString.startsWith("select distinct")) { distinctStr = "DISTINCT "; index = 15; } sqlPartString = sqlPartString.substring(index); } pagingBuilder.append(sqlPartString); // if no ORDER BY is specified use fake ORDER BY field to avoid errors if (StringUtils.isEmpty(orderby)) { orderby = "ORDER BY CURRENT_TIMESTAMP"; } StringBuilder result = new StringBuilder(); result.append("WITH query AS (SELECT ").append(distinctStr) .append("TOP 100 PERCENT ").append(" ROW_NUMBER() OVER (") .append(orderby).append(") as __row_number__, ") .append(pagingBuilder) .append(") SELECT * FROM query WHERE __row_number__ BETWEEN ") .append(offset).append(" AND ").append(offset + limit) .append(" ORDER BY __row_number__"); return result.toString(); } static String getOrderByPart(String sql) { String loweredString = sql.toLowerCase(); int orderByIndex = loweredString.indexOf("order by"); if (orderByIndex != -1) { // if we find a new "order by" then we need to ignore // the previous one since it was probably used for a subquery return sql.substring(orderByIndex); } else { return ""; } } @Override public String getCount(String sql) { return "select count(1) from (" + BaseParameter.removeOrders(sql) + ") as dialect"; } @Override public String getSort(String sql, List<Sorting> sort) { if (sort == null || sort.isEmpty()) { return sql; } StringBuffer buffer = new StringBuffer("select * from (").append(sql) .append(") dialect order by "); for (Sorting s : sort) { buffer.append(s.getColumn()).append(" ").append(s.getSort()) .append(", "); } buffer.delete(buffer.length() - 2, buffer.length()); return buffer.toString(); } }
29.254098
74
0.684505
247f19eb103a2777f615c7e5fbc2a9ab23db685a
3,365
package gr.sperfect.djuqbox.webapp.server.youtube; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.PlaylistItem; import com.google.api.services.youtube.model.PlaylistItemListResponse; import com.google.api.services.youtube.model.SearchListResponse; import com.google.api.services.youtube.model.SearchResult; //http://developers.google.com/apis-explorer/?hl=en_US#p/youtube/v3/ public class YoutubeSearcher extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/plain"); resp.getWriter().println("Hello, world"); try { // YouTube youtube = new YouTube.Builder(UrlFetchTransport.getDefaultInstance(), // JacksonFactory.getDefaultInstance(), new HttpRequestInitializer() { // public void initialize(HttpRequest request) throws IOException { // } // }).setApplicationName("djuqbox").build(); YouTube youtube = YoutubeApi.youtubeInst; YouTube.Search.List search = youtube.search().list("id,snippet"); String queryTerm = "radiohead"; search.setKey(YoutubeApi.getKey()); // created on 25/02/2015 search.setQ(queryTerm); search.setType("video"); search.setVideoCategoryId("10"); // search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)"); search.setMaxResults((long) 50); SearchListResponse searchResponse = search.execute(); List<SearchResult> searchResultList = searchResponse.getItems(); if (searchResultList != null) { // resp.getWriter().println( // prettyPrint(searchResultList.iterator(), queryTerm)); for (SearchResult searchResult : searchResultList) { resp.getWriter().println("----"); resp.getWriter().println(searchResult.getSnippet().getTitle()); YoutubeApi.getVideoInfo(searchResult.getId().getVideoId().toString()); List<PlaylistItem> playlistItemList = new ArrayList<PlaylistItem>(); YouTube.PlaylistItems.List playlistItemRequest = youtube.playlistItems().list( "id,contentDetails,snippet"); playlistItemRequest.setPlaylistId("RD" + searchResult.getId().getVideoId()); playlistItemRequest.setKey(YoutubeApi.getKey()); playlistItemRequest.setMaxResults((long) 50); PlaylistItemListResponse playlistItemResult = playlistItemRequest.execute(); playlistItemList.addAll(playlistItemResult.getItems()); Iterator<PlaylistItem> playlistEntries = playlistItemList.iterator(); while (playlistEntries.hasNext()) { PlaylistItem playlistItem = playlistEntries.next(); resp.getWriter().println(" video name = " + playlistItem.getSnippet().getTitle()); } } Logger.getGlobal().log(Level.INFO, "OK"); } } catch (Exception ex) { // resp.getWriter().println(ex.getCause()); resp.getWriter().println(ex.getMessage()); } } }
33.316832
98
0.713522
d3505ca07fd9a2eacbf72a3213372969031bb2d6
1,144
package com.alibaba.alink.operator.common.fm; import java.util.List; import com.alibaba.alink.common.lazy.ExtractModelInfoBatchOp; import com.alibaba.alink.operator.batch.BatchOperator; import org.apache.flink.api.common.typeinfo.TypeInformation; import org.apache.flink.ml.api.misc.param.Params; import org.apache.flink.types.Row; /** * FmRegressorModelInfoBatchOp can be linked to the output of BaseFmTrainBatchOp to info the Fm model. */ public class FmRegressorModelInfoBatchOp extends ExtractModelInfoBatchOp<FmRegressorModelInfo, FmRegressorModelInfoBatchOp> { private TypeInformation labelType; public FmRegressorModelInfoBatchOp(TypeInformation labelType) { this(new Params()); this.labelType = labelType; } /** * construct function. * @param params */ public FmRegressorModelInfoBatchOp(Params params) { super(params); } @Override protected FmRegressorModelInfo createModelInfo(List<Row> rows) { return new FmRegressorModelInfo(rows, labelType); } @Override protected BatchOperator<?> processModel() { return this; } }
27.902439
102
0.73514
15c86e345857e1dd06fba2157a6d8d3d7340cabb
1,674
package com.github.ibole.infrastructure.common.exception; /********************************************************************************************* * . * * * <p>Copyright 2016, iBole Inc. All rights reserved. * * <p> * </p> *********************************************************************************************/ /** * @author bwang ([email protected]) * */ public class HttpStatusException extends Exception { private static final long serialVersionUID = 1L; /* the HTTP error code */ private final int errorCode; /** * Constructor. * * @param errorCode the HTTP status code for this exception * @param msg human readable message * @param cause reason for this exception */ public HttpStatusException(final int errorCode, final String msg, final Throwable cause) { super(msg, cause); this.errorCode = errorCode; } /** * Constructor. * * @param errorCode the HTTP status code for this exception * @param cause reason for this exception */ public HttpStatusException(final int errorCode, final Throwable cause) { super(String.valueOf(errorCode), cause); this.errorCode = errorCode; } /** * Constructor. * * @param errorCode the HTTP status code for this exception * @param msg human readable message */ public HttpStatusException(final int errorCode, final String msg) { super(msg); this.errorCode = errorCode; } /** * Return the HTTP status code for this exception. * * @return the HTTP status code */ public int getErrorCode() { return errorCode; } }
24.985075
96
0.5681
f449b114fbe2f89e6806f8aaf1d579d6b0fd4d96
189
package com.tvd12.ezyfoxserver.entity; import com.tvd12.ezyfox.constant.EzyConstant; public interface EzyDisconnectReasonAware { void setDisconnectReason(EzyConstant reason); }
18.9
49
0.798942
f9bb5e649837d08d12b76e7810b1dd782b548cd6
3,461
/* * Copyright (C) 2016 Singular Studios (a.k.a Atom Tecnologia) - www.opensingular.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opensingular.flow.core.variable; import org.junit.Test; import org.opensingular.flow.core.SingularFlowException; import java.util.Date; import static org.junit.Assert.*; import static org.opensingular.internal.lib.commons.test.SingularTestUtil.assertException; /** * @author Daniel C. Bordin on 26/03/2017. */ public class TestVarInstanceMap { @Test public void empty() { VarInstanceMap empty = VarInstanceMap.empty(); assertTrue(empty.isEmpty()); assertNull(empty.getVariable("any")); assertEquals(0, empty.size()); assertTrue(empty.asCollection().isEmpty()); assertException(() -> empty.onValueChanged(null), SingularFlowException.class, "Método não suportado"); assertException(() -> empty.addDefinition(null), SingularFlowException.class, "Método não suportado"); assertException(() -> empty.getVarService(), SingularFlowException.class, "Método não suportado"); } @Test public void testGetValue() { DefaultVarDefinitionMap defs = new DefaultVarDefinitionMap(DefaultVarService.DEFAULT_VAR_SERVICE); defs.addVariableString("ref", "Ref"); VarInstanceMapImpl vars = new VarInstanceMapImpl(defs); assertNull(vars.getValue("ref")); assertEquals("x", vars.getValue("ref", "x")); assertException(() -> vars.setValue("f", "x"), SingularFlowException.class, "não está definida"); assertException(() -> vars.getValue("f"), SingularFlowException.class, "não está definida"); assertException(() -> vars.getValue("f", "x"), SingularFlowException.class, "não está definida"); assertEquals(1, vars.stream().count()); assertEquals("w", vars.getValueType("ref", String.class, "w")); vars.setValue("ref", "y"); assertException(() -> vars.getValueType("ref", Integer.class), SingularFlowException.class, "é do tipo"); } @Test public void testDinamicAdd() { DefaultVarDefinitionMap defs = new DefaultVarDefinitionMap(DefaultVarService.DEFAULT_VAR_SERVICE); VarInstanceMapImpl vars = new VarInstanceMapImpl(defs); vars.addValueString("a", "x"); assertEquals("x", vars.getValueString("a")); assertEquals("x", vars.getValueString("a", "y")); vars.addValueBoolean("b", Boolean.TRUE); assertEquals(Boolean.TRUE, vars.getValueBoolean("b")); assertEquals(Boolean.TRUE, vars.getValueBoolean("b", Boolean.FALSE)); vars.addValueInteger("i", 10); assertEquals((Integer) 10, vars.getValueInteger("i")); assertEquals((Integer) 10, vars.getValueInteger("i", 20)); Date now = new Date(); vars.addValueDate("d", now); assertEquals(now, vars.getValueDate("d")); vars.addValueInteger("i", 10); } }
38.88764
113
0.682751
326fff6e5659ca165156dadb2a01e69fd368bb93
3,103
package com.wuhulala.service; import com.wuhulala.auth.JwtManager; import com.wuhulala.dal.mapper.AccountMapper; import com.wuhulala.dal.model.Account; import com.wuhulala.util.PasswordUtil; import com.wuhulala.util.TokenUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletRequest; import java.util.Date; /** * @author Wuhulala * @version 1.0 * @updateTime 2016/12/25 */ @Service public class AccountService { private static final Logger LOGGER = LoggerFactory.getLogger(AccountService.class); private final JwtManager jwtManager; private final AccountMapper accountMapper; @Autowired public AccountService(AccountMapper accountMapper,JwtManager jwtManager) { this.accountMapper = accountMapper; this.jwtManager = jwtManager; } @Transactional public Account login(Account account, HttpServletRequest request) { String newPass = PasswordUtil.createPassword(account.getPassword()); account.setPassword(newPass); Account result = accountMapper.login(account); if (null != result) { String token = TokenUtils.generateToken(result.getId(), result.getName(), getRolesString(result.getId())); result.setToken(token); jwtManager.addJwt(result.getId() + "", token); result.setLastLogin(new Date()); accountMapper.updateLastLogin(result); return result; } return null; } /** * 注册 * * @return 1 用户名已存在 * 2 数据库错误 * 3 注册成功 */ @Transactional public int register(String name, String password) { if (accountMapper.findByName(name) != null) { return 1; } String newPass = PasswordUtil.createPassword(password); Account account = new Account(name, newPass); accountMapper.insert(account); return account.getId() == null ? 2 : 3; } /** * 修改密码 * * @return 0 用户不存在 * 1 原密码错误 * 2 修改成功 */ @Transactional public int editPassword(Long id, String password, String newPassword) { Account account = accountMapper.findById(id); if (null != account) { if (PasswordUtil.authenticatePassword(account.getPassword(), password)) return 1; account.setPassword(PasswordUtil.createPassword(newPassword)); accountMapper.updatePassword(account); jwtManager.delJwt(id +""); return 2; } return 0; } /** * 删除session * <p> * 0 已删除或不存在 * 1 删除成功 */ public int deleteSession(Long accountId) { boolean flag = jwtManager.delJwt(accountId+""); if (flag) { LOGGER.info("用户" + accountId + "退出登录"); return 1; } return 0; } public String getRolesString(Long userId) { return "user"; } }
26.982609
118
0.639059
da098f33074a21e88b5026d876c180e82c17ce4b
11,732
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * See the License for the specific language governing permissions * and * limitations under the License. */ package android.security.cts; /** * Run "./cts/tools/utils/java-cert-list-generator.sh > * cts/tests/tests/security/src/android/security/cts/CertificateData.java" * to generate this file. */ class CertificateData { static final String[] CERTIFICATE_DATA = { "91:C6:D6:EE:3E:8A:C8:63:84:E5:48:C2:99:29:5C:75:6C:81:7B:81", "4A:65:D5:F4:1D:EF:39:B8:B8:90:4A:4A:D3:64:81:33:CF:C7:A1:D1", "16:32:47:8D:89:F9:21:3A:92:00:85:63:F5:A4:A7:D3:12:40:8A:D6", "4D:23:78:EC:91:95:39:B5:00:7F:75:8F:03:3B:21:1E:C5:4D:8B:CF", "E7:B4:F6:9D:61:EC:90:69:DB:7E:90:A7:40:1A:3C:F4:7D:4F:E8:EE", "DD:E1:D2:A9:01:80:2E:1D:87:5E:84:B3:80:7E:4B:B1:FD:99:41:34", "92:5A:8F:8D:2C:6D:04:E0:66:5F:59:6A:FF:22:D8:63:E8:25:6F:3F", "75:E0:AB:B6:13:85:12:27:1C:04:F8:5F:DD:DE:38:E4:B7:24:2E:FE", "40:9D:4B:D9:17:B5:5C:27:B6:9B:64:CB:98:22:44:0D:CD:09:B8:89", "E1:9F:E3:0E:8B:84:60:9E:80:9B:17:0D:72:A8:C5:BA:6E:14:09:BD", "DA:C9:02:4F:54:D8:F6:DF:94:93:5F:B1:73:26:38:CA:6A:D7:7C:13", "4F:99:AA:93:FB:2B:D1:37:26:A1:99:4A:CE:7F:F0:05:F2:93:5D:1E", "74:20:74:41:72:9C:DD:92:EC:79:31:D8:23:10:8D:C2:81:92:E2:BB", "40:54:DA:6F:1C:3F:40:74:AC:ED:0F:EC:CD:DB:79:D1:53:FB:90:1D", "F4:8B:11:BF:DE:AB:BE:94:54:20:71:E6:41:DE:6B:BE:88:2B:40:B9", "58:E8:AB:B0:36:15:33:FB:80:F7:9B:1B:6D:29:D3:FF:8D:5F:00:F0", "55:A6:72:3E:CB:F2:EC:CD:C3:23:74:70:19:9D:2A:BE:11:E3:81:D1", "D6:9B:56:11:48:F0:1C:77:C5:45:78:C1:09:26:DF:5B:85:69:76:AD", "78:6A:74:AC:76:AB:14:7F:9C:6A:30:50:BA:9E:A8:7E:FE:9A:CE:3C", "09:3C:61:F3:8B:8B:DC:7D:55:DF:75:38:02:05:00:E1:25:F5:C8:36", "8E:1C:74:F8:A6:20:B9:E5:8A:F4:61:FA:EC:2B:47:56:51:1A:52:C6", "27:96:BA:E6:3F:18:01:E2:77:26:1B:A0:D7:77:70:02:8F:20:EE:E4", "AD:7E:1C:28:B0:64:EF:8F:60:03:40:20:14:C3:D0:E3:37:0E:B5:8A", "8D:17:84:D5:37:F3:03:7D:EC:70:FE:57:8B:51:9A:99:E6:10:D7:B0", "AE:50:83:ED:7C:F4:5C:BC:8F:61:C6:21:FE:68:5D:79:42:21:15:6E", "DA:FA:F7:FA:66:84:EC:06:8F:14:50:BD:C7:C2:81:A5:BC:A9:64:57", "74:F8:A3:C3:EF:E7:B3:90:06:4B:83:90:3C:21:64:60:20:E5:DF:CE", "85:B5:FF:67:9B:0C:79:96:1F:C8:6E:44:22:00:46:13:DB:17:92:84", "3E:2B:F7:F2:03:1B:96:F3:8C:E6:C4:D8:A8:5D:3E:2D:58:47:6A:0F", "A3:F1:33:3F:E2:42:BF:CF:C5:D1:4E:8F:39:42:98:40:68:10:D1:A0", "5F:43:E5:B1:BF:F8:78:8C:AC:1C:C7:CA:4A:9A:C6:22:2B:CC:34:C6", "A8:98:5D:3A:65:E5:E5:C4:B2:D7:D6:6D:40:C6:DD:2F:B1:9C:54:36", "59:22:A1:E1:5A:EA:16:35:21:F8:98:39:6A:46:46:B0:44:1B:0F:A9", "D4:DE:20:D0:5E:66:FC:53:FE:1A:50:88:2C:78:DB:28:52:CA:E4:74", "02:FA:F3:E2:91:43:54:68:60:78:57:69:4D:F5:E4:5B:68:85:18:68", "D8:C5:38:8A:B7:30:1B:1B:6E:D4:7A:E6:45:25:3A:6F:9F:1A:27:61", "93:05:7A:88:15:C6:4F:CE:88:2F:FA:91:16:52:28:78:BC:53:64:17", "59:AF:82:79:91:86:C7:B4:75:07:CB:CF:03:57:46:EB:04:DD:B7:16", "50:30:06:09:1D:97:D4:F5:AE:39:F7:CB:E7:92:7D:7D:65:2D:34:31", "FE:45:65:9B:79:03:5B:98:A1:61:B5:51:2E:AC:DA:58:09:48:22:4D", "1B:4B:39:61:26:27:6B:64:91:A2:68:6D:D7:02:43:21:2D:1F:1D:96", "77:47:4F:C6:30:E4:0F:4C:47:64:3F:84:BA:B8:C6:95:4A:8A:41:EC", "8C:F4:27:FD:79:0C:3A:D1:66:06:8D:E8:1E:57:EF:BB:93:22:72:D4", "2F:78:3D:25:52:18:A7:4A:65:39:71:B5:2C:A2:9C:45:15:6F:E9:19", "97:81:79:50:D8:1C:96:70:CC:34:D8:09:CF:79:44:31:36:7E:F4:74", "85:A4:08:C0:9C:19:3E:5D:51:58:7D:CD:D6:13:30:FD:8C:DE:37:BF", "58:11:9F:0E:12:82:87:EA:50:FD:D9:87:45:6F:4F:78:DC:FA:D6:D4", "6B:2F:34:AD:89:58:BE:62:FD:B0:6B:5C:CE:BB:9D:D9:4F:4E:39:F3", "9B:AA:E5:9F:56:EE:21:CB:43:5A:BE:25:93:DF:A7:F0:40:D1:1D:CB", "36:79:CA:35:66:87:72:30:4D:30:A5:FB:87:3B:0F:A7:7B:B7:0D:54", "1B:8E:EA:57:96:29:1A:C9:39:EA:B8:0A:81:1A:73:73:C0:93:79:67", "B4:35:D4:E1:11:9D:1C:66:90:A7:49:EB:B3:94:BD:63:7B:A7:82:B7", "A9:E9:78:08:14:37:58:88:F2:05:19:B0:6D:2B:0D:2B:60:16:90:7D", "60:D6:89:74:B5:C2:65:9E:8A:0F:C1:88:7C:88:D2:46:69:1B:18:2C", "D2:32:09:AD:23:D3:14:23:21:74:E4:0D:7F:9D:62:13:97:86:63:3A", "66:31:BF:9E:F7:4F:9E:B6:C9:D5:A6:0C:BA:6A:BE:D1:F7:BD:EF:7B", "DE:3F:40:BD:50:93:D3:9B:6C:60:F6:DA:BC:07:62:01:00:89:76:C9", "22:D5:D8:DF:8F:02:31:D1:8D:F7:9D:B7:CF:8A:2D:64:C9:3F:6C:3A", "F3:73:B3:87:06:5A:28:84:8A:F2:F3:4A:CE:19:2B:DD:C7:8E:9C:AC", "06:08:3F:59:3F:15:A1:04:A0:69:A4:6B:A9:03:D0:06:B7:97:09:91", "43:13:BB:96:F1:D5:86:9B:C1:4E:6A:92:F6:CF:F6:34:69:87:82:37", "F1:8B:53:8D:1B:E9:03:B6:A6:F0:56:43:5B:17:15:89:CA:F3:6B:F2", "05:63:B8:63:0D:62:D7:5A:BB:C8:AB:1E:4B:DF:B5:A8:99:B2:4D:43", "62:52:DC:40:F7:11:43:A2:2F:DE:9E:F7:34:8E:06:42:51:B1:81:18", "70:17:9B:86:8C:00:A4:FA:60:91:52:22:3F:9F:3E:32:BD:E0:05:62", "A0:A1:AB:90:C9:FC:84:7B:3B:12:61:E8:97:7D:5F:D3:22:61:D3:CC", "85:37:1C:A6:E5:50:14:3D:CE:28:03:47:1B:DE:3A:09:E8:F8:77:0F", "7E:78:4A:10:1C:82:65:CC:2D:E1:F1:6D:47:B4:40:CA:D9:0A:19:45", "D1:EB:23:A4:6D:17:D6:8F:D9:25:64:C2:F1:F1:60:17:64:D8:E3:49", "A1:DB:63:93:91:6F:17:E4:18:55:09:40:04:15:C7:02:40:B0:AE:6B", "B8:01:86:D1:EB:9C:86:A5:41:04:CF:30:54:F3:4C:52:B7:E5:58:C6", "2E:14:DA:EC:28:F0:FA:1E:8E:38:9A:4E:AB:EB:26:C0:0A:D3:83:C3", "DE:28:F4:A4:FF:E5:B9:2F:A3:C5:03:D1:A3:49:A7:F9:96:2A:82:12", "80:25:EF:F4:6E:70:C8:D4:72:24:65:84:FE:40:3B:8A:8D:6A:DB:F5", "CA:3A:FB:CF:12:40:36:4B:44:B2:16:20:88:80:48:39:19:93:7C:F7", "69:BD:8C:F4:9C:D3:00:FB:59:2E:17:93:CA:55:6A:F3:EC:AA:35:FB", "13:2D:0D:45:53:4B:69:97:CD:B2:D5:C3:39:E2:55:76:60:9B:5C:C6", "5F:B7:EE:06:33:E2:59:DB:AD:0C:4C:9A:E6:D3:8F:1A:61:C7:DC:25", "49:0A:75:74:DE:87:0A:47:FE:58:EE:F6:C7:6B:EB:C6:0B:12:40:99", "25:01:90:19:CF:FB:D9:99:1C:B7:68:25:74:8D:94:5F:30:93:95:42", "79:98:A3:08:E1:4D:65:85:E6:C2:1E:15:3A:71:9F:BA:5A:D3:4A:D9", "B5:1C:06:7C:EE:2B:0C:3D:F8:55:AB:2D:92:F4:FE:39:D4:E7:0F:0E", "29:36:21:02:8B:20:ED:02:F5:66:C5:32:D1:D6:ED:90:9F:45:00:2F", "37:9A:19:7B:41:85:45:35:0C:A6:03:69:F3:3C:2E:AF:47:4F:20:79", "FA:B7:EE:36:97:26:62:FB:2D:B0:2A:F6:BF:03:FD:E8:7C:4B:2F:9B", "8B:AF:4C:9B:1D:F0:2A:92:F7:DA:12:8E:B9:1B:AC:F4:98:60:4B:6F", "9F:74:4E:9F:2B:4D:BA:EC:0F:31:2C:50:B6:56:3B:8E:2D:93:C3:11", "A1:4B:48:D9:43:EE:0A:0E:40:90:4F:3C:E0:A4:C0:91:93:51:5D:3F", "C9:A8:B9:E7:55:80:5E:58:E3:53:77:A7:25:EB:AF:C3:7B:27:CC:D7", "1F:49:14:F7:D8:74:95:1D:DD:AE:02:C0:BE:FD:3A:2D:82:75:51:85", "B5:61:EB:EA:A4:DE:E4:25:4B:69:1A:98:A5:57:47:C2:34:C7:D9:71", "07:E0:32:E0:20:B7:2C:3F:19:2F:06:28:A2:59:3A:19:A7:0F:06:9E", "B9:42:94:BF:91:EA:8F:B6:4B:E6:10:97:C7:FB:00:13:59:B6:76:CB", "D6:DA:A8:20:8D:09:D2:15:4D:24:B5:2F:CB:34:6E:B2:58:B2:8A:58", "32:3C:11:8E:1B:F7:B8:B6:52:54:E2:E2:10:0D:D6:02:90:37:F0:96", "E7:A1:90:29:D3:D5:52:DC:0D:0F:C6:92:D3:EA:88:0D:15:2E:1A:6B", "67:65:0D:F1:7E:8E:7E:5B:82:40:A4:F4:56:4B:CF:E2:3D:69:C6:F0", "FE:B8:C4:32:DC:F9:76:9A:CE:AE:3D:D8:90:8F:FD:28:86:65:64:7D", "4A:BD:EE:EC:95:0D:35:9C:89:AE:C7:52:A1:2C:5B:29:F6:D6:AA:0C", "33:9B:6B:14:50:24:9B:55:7A:01:87:72:84:D9:E0:2F:C3:D2:D8:E9", "DD:FB:16:CD:49:31:C9:73:A2:03:7D:3F:C8:3A:4D:7D:77:5D:05:E4", "2A:B6:28:48:5E:78:FB:F3:AD:9E:79:10:DD:6B:DF:99:72:2C:96:E5", "36:B1:2B:49:F9:81:9E:D7:4C:9E:BC:38:0F:C6:56:8F:5D:AC:B2:F7", "37:F7:6D:E6:07:7C:90:C5:B1:3E:93:1A:B7:41:10:B4:F2:E4:9A:27", "AA:DB:BC:22:23:8F:C4:01:A1:27:BB:38:DD:F4:1D:DB:08:9E:F0:12", "3B:C4:9F:48:F8:F3:73:A0:9C:1E:BD:F8:5B:B1:C3:65:C7:D8:11:B3", "AC:ED:5F:65:53:FD:25:CE:01:5F:1F:7A:48:3B:6A:74:9F:61:78:C6", "28:90:3A:63:5B:52:80:FA:E6:77:4C:0B:6D:A7:D6:BA:A6:4A:F2:E8", "9C:BB:48:53:F6:A4:F6:D3:52:A4:E8:32:52:55:60:13:F5:AD:AF:65", "B1:BC:96:8B:D4:F4:9D:62:2A:A8:9A:81:F2:15:01:52:A4:1D:82:9C", "20:D8:06:40:DF:9B:25:F5:12:25:3A:11:EA:F7:59:8A:EB:14:B5:47", "CF:9E:87:6D:D3:EB:FC:42:26:97:A3:B5:A3:7A:A0:76:A9:06:23:48", "2B:B1:F5:3E:55:0C:1D:C5:F1:D4:E6:B7:6A:46:4B:55:06:02:AC:21", "47:BE:AB:C9:22:EA:E8:0E:78:78:34:62:A7:9F:45:C2:54:FD:E6:8B", "39:21:C1:15:C1:5D:0E:CA:5C:CB:5B:C4:F0:7D:21:D8:05:0B:56:6A", "3A:44:73:5A:E5:81:90:1F:24:86:61:46:1E:3B:9C:C4:5F:F5:3A:1B", "B3:1E:B1:B7:40:E3:6C:84:02:DA:DC:37:D4:4D:F5:D4:67:49:52:F9", "E0:AB:05:94:20:72:54:93:05:60:62:02:36:70:F7:CD:2E:FC:66:66", "D3:C0:63:F2:19:ED:07:3E:34:AD:5D:75:0B:32:76:29:FF:D5:9A:F2", "F5:17:A2:4F:9A:48:C6:C9:F8:A2:00:26:9F:DC:0F:48:2C:AB:30:89", "3B:C0:38:0B:33:C3:F6:A6:0C:86:15:22:93:D9:DF:F5:4B:81:C0:04", "C8:EC:8C:87:92:69:CB:4B:AB:39:E9:8D:7E:57:67:F3:14:95:73:9D", "03:9E:ED:B8:0B:E7:A0:3C:69:53:89:3B:20:D2:D9:32:3A:4C:2A:FD", "DF:3C:24:F9:BF:D6:66:76:1B:26:80:73:FE:06:D1:CC:8D:4F:82:A4", "51:C6:E7:08:49:06:6E:F3:92:D4:5C:A0:0D:6D:A3:62:8F:C3:52:39", "B8:23:6B:00:2F:1D:16:86:53:01:55:6C:11:A4:37:CA:EB:FF:C3:BB", "10:1D:FA:3F:D5:0B:CB:BB:9B:B5:60:0C:19:55:A4:1A:F4:73:3A:04", "87:82:C6:C3:04:35:3B:CF:D2:96:92:D2:59:3E:7D:44:D9:34:FF:11", "59:0D:2D:7D:88:4F:40:2E:61:7E:A5:62:32:17:65:CF:17:D8:94:E9", "AE:C5:FB:3F:C8:E1:BF:C4:E5:4F:03:07:5A:9A:E8:00:B7:F7:B6:FA", "5F:3B:8C:F2:F8:10:B3:7D:78:B4:CE:EC:19:19:C3:73:34:B9:C7:74", "2A:C8:D5:8B:57:CE:BF:2F:49:AF:F2:FC:76:8F:51:14:62:90:7A:41", "F1:7F:6F:B6:31:DC:99:E3:A3:C8:7F:FE:1C:F1:81:10:88:D9:60:33", "96:C9:1B:0B:95:B4:10:98:42:FA:D0:D8:22:79:FE:60:FA:B9:16:83", "D8:A6:33:2C:E0:03:6F:B1:85:F6:63:4F:7D:6A:06:65:26:32:28:27", "9F:AD:91:A6:CE:6A:C6:C5:00:47:C4:4E:C9:D4:A5:0D:92:D8:49:79", "CC:AB:0E:A0:4C:23:01:D6:69:7B:DD:37:9F:CD:12:EB:24:E3:94:9D", "48:12:BD:92:3C:A8:C4:39:06:E7:30:6D:27:96:E6:A4:CF:22:2E:7D", "F9:B5:B6:32:45:5F:9C:BE:EC:57:5F:80:DC:E9:6E:2C:C7:B2:78:B7", "5F:3A:FC:0A:8B:64:F6:86:67:34:74:DF:7E:A9:A2:FE:F9:FA:7A:51", "E6:21:F3:35:43:79:05:9A:4B:68:30:9D:8A:2F:74:22:15:87:EC:79", "DA:40:18:8B:91:89:A3:ED:EE:AE:DA:97:FE:2F:9D:F5:B7:D1:8A:41", "89:DF:74:FE:5C:F4:0F:4A:80:F9:E3:37:7D:54:DA:91:E1:01:31:8E", "E0:B4:32:2E:B2:F6:A5:68:B6:54:53:84:48:18:4A:50:36:87:43:84", "61:57:3A:11:DF:0E:D8:7E:D5:92:65:22:EA:D0:56:D7:44:B3:23:71", "7E:04:DE:89:6A:3E:66:6D:00:E6:87:D3:3F:FA:D9:3B:E8:3D:34:9E", "99:A6:9B:E6:1A:FE:88:6B:4D:2B:82:00:7C:B8:54:FC:31:7E:15:39", "6E:3A:55:A4:19:0C:19:5C:93:84:3C:C0:DB:72:2E:31:30:61:F0:B1", "31:F1:FD:68:22:63:20:EE:C6:3B:3F:9D:EA:4A:3E:53:7C:7C:39:17", "F9:CD:0E:2C:DA:76:24:C1:8F:BD:F0:F0:AB:B6:45:B8:F7:FE:D5:7A", "23:88:C9:D3:71:CC:9E:96:3D:FF:7D:3C:A7:CE:FC:D6:25:EC:19:0D", "8C:96:BA:EB:DD:2B:07:07:48:EE:30:32:66:A0:F3:98:6E:7C:AE:58", "7F:8A:B0:CF:D0:51:87:6A:66:F3:36:0F:47:C8:8D:8C:D3:35:FC:74", "4E:B6:D5:78:49:9B:1C:CF:5F:58:1E:AD:56:BE:3D:9B:67:44:A5:E5", "A0:73:E5:C5:BD:43:61:0D:86:4C:21:13:0A:85:58:57:CC:9C:EA:46", "B1:2E:13:63:45:86:A4:6F:1A:B2:60:68:37:58:2D:C4:AC:FD:94:97", "04:83:ED:33:99:AC:36:08:05:87:22:ED:BC:5E:46:00:E3:BE:F9:D7", }; }
62.737968
74
0.590948
fc6fba72e5b70935adc88d762d852fd1399b33a6
1,458
package gov.dot.its.datahub.webapi.model; import java.util.Date; import com.fasterxml.jackson.annotation.JsonProperty; public class DHEngagementPopup { private String id; private boolean isActive; private String name; private String description; private Date lastModified; private String content; private String controlsColor; private String controlsShadow; public String getId() { return id; } public void setId(String id) { this.id = id; } @JsonProperty("isActive") public boolean isActive() { return isActive; } public void setActive(boolean isActive) { this.isActive = isActive; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getLastModified() { return lastModified; } public void setLastModified(Date lastModified) { this.lastModified = lastModified; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getControlsColor() { return controlsColor; } public void setControlsColor(String controlsColor) { this.controlsColor = controlsColor; } public String getControlsShadow() { return controlsShadow; } public void setControlsShadow(String controlsShadow) { this.controlsShadow = controlsShadow; } }
21.761194
55
0.748971
bf11c2ec49069e49ac9833e73914190dc3dc3b14
5,356
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.storage.samples; import com.microsoft.azure.management.Azure; import com.microsoft.azure.management.resources.fluentcore.arm.Region; import com.microsoft.azure.management.samples.Utils; import com.microsoft.azure.management.storage.StorageAccount; import com.microsoft.azure.management.storage.StorageAccountKey; import com.microsoft.azure.management.storage.StorageAccounts; import com.microsoft.rest.LogLevel; import java.io.File; import java.util.List; /** * Azure Storage sample for managing storage accounts - * - Create a storage account * - Get | regenerate storage account access keys * - Create another storage account * - List storage accounts * - Delete a storage account. */ public final class ManageStorageAccount { /** * Main function which runs the actual sample. * @param azure instance of the azure client * @return true if sample runs successfully */ public static boolean runSample(Azure azure) { final String storageAccountName = Utils.createRandomName("sa"); final String storageAccountName2 = Utils.createRandomName("sa2"); final String rgName = Utils.createRandomName("rgSTMS"); try { // ============================================================ // Create a storage account System.out.println("Creating a Storage Account"); StorageAccount storageAccount = azure.storageAccounts().define(storageAccountName) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); System.out.println("Created a Storage Account:"); Utils.print(storageAccount); // ============================================================ // Get | regenerate storage account access keys System.out.println("Getting storage account access keys"); List<StorageAccountKey> storageAccountKeys = storageAccount.getKeys(); Utils.print(storageAccountKeys); System.out.println("Regenerating first storage account access key"); storageAccountKeys = storageAccount.regenerateKey(storageAccountKeys.get(0).keyName()); Utils.print(storageAccountKeys); // ============================================================ // Create another storage account System.out.println("Creating a 2nd Storage Account"); StorageAccount storageAccount2 = azure.storageAccounts().define(storageAccountName2) .withRegion(Region.US_EAST) .withNewResourceGroup(rgName) .create(); System.out.println("Created a Storage Account:"); Utils.print(storageAccount2); // ============================================================ // List storage accounts System.out.println("Listing storage accounts"); StorageAccounts storageAccounts = azure.storageAccounts(); List<StorageAccount> accounts = storageAccounts.listByResourceGroup(rgName); StorageAccount sa; for (int i = 0; i < accounts.size(); i++) { sa = (StorageAccount) accounts.get(i); System.out.println("Storage Account (" + i + ") " + sa.name() + " created @ " + sa.creationTime()); } // ============================================================ // Delete a storage account System.out.println("Deleting a storage account - " + storageAccount.name() + " created @ " + storageAccount.creationTime()); azure.storageAccounts().deleteById(storageAccount.id()); System.out.println("Deleted storage account"); return true; } catch (Exception f) { System.out.println(f.getMessage()); f.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azure.resourceGroups().deleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (Exception e) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } } return false; } /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); Azure azure = Azure.configure() .withLogLevel(LogLevel.BODY) .authenticate(credFile) .withDefaultSubscription(); // Print selected subscription System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private ManageStorageAccount() { } }
35.236842
102
0.571882
f02cc62a7f0d75237b7eabc1fd82088641b81e33
385
package com.NowakArtur97.WorldOfManga.feature.user; import lombok.RequiredArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor class UserMapper { private final ModelMapper modelMapper; User mapUserDTOToUser(UserDTO userDTO) { return modelMapper.map(userDTO, User.class); } }
21.388889
52
0.792208
c7cab9b99bae7c348d97450ede09946b258a7a08
4,684
/* * Copyright Debezium Authors. * * Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package io.debezium.connector.db2; import java.sql.SQLException; import java.util.List; import org.apache.kafka.connect.source.SourceRecord; import org.fest.assertions.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.debezium.config.Configuration; import io.debezium.connector.db2.Db2ConnectorConfig.SnapshotMode; import io.debezium.connector.db2.util.TestHelper; import io.debezium.embedded.AbstractConnectorTest; import io.debezium.util.Collect; import io.debezium.util.Testing; /** * Transaction metadata test for the Debezium DB2 Server connector. * * @author Jiri Pechanec */ public class TransactionMetadataIT extends AbstractConnectorTest { private Db2Connection connection; @Before public void before() throws SQLException { connection = TestHelper.testConnection(); connection.execute("DELETE FROM ASNCDC.IBMSNAP_REGISTER"); connection.execute( "CREATE TABLE tablea (id int not null, cola varchar(30), primary key (id))", "CREATE TABLE tableb (id int not null, colb varchar(30), primary key (id))", "INSERT INTO tablea VALUES(1, 'a')"); TestHelper.enableTableCdc(connection, "TABLEA"); TestHelper.enableTableCdc(connection, "TABLEB"); initializeConnectorTestFramework(); Testing.Files.delete(TestHelper.DB_HISTORY_PATH); Testing.Print.enable(); } @After public void after() throws SQLException { if (connection != null) { TestHelper.disableDbCdc(connection); TestHelper.disableTableCdc(connection, "TABLEB"); TestHelper.disableTableCdc(connection, "TABLEA"); connection.execute("DROP TABLE tablea", "DROP TABLE tableb"); connection.execute("DELETE FROM ASNCDC.IBMSNAP_REGISTER"); connection.execute("DELETE FROM ASNCDC.IBMQREP_COLVERSION"); connection.execute("DELETE FROM ASNCDC.IBMQREP_TABVERSION"); connection.close(); } } @Test public void transactionMetadata() throws Exception { final int RECORDS_PER_TABLE = 5; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(Db2ConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(Db2ConnectorConfig.PROVIDE_TRANSACTION_METADATA, true) .build(); start(Db2Connector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); TestHelper.enableDbCdc(connection); connection.execute("UPDATE ASNCDC.IBMSNAP_REGISTER SET STATE = 'A' WHERE SOURCE_OWNER = 'DB2INST1'"); TestHelper.refreshAndWait(connection); connection.setAutoCommit(false); final String[] inserts = new String[RECORDS_PER_TABLE * 2]; for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; inserts[2 * i] = "INSERT INTO tablea VALUES(" + id + ", 'a')"; inserts[2 * i + 1] = "INSERT INTO tableb VALUES(" + id + ", 'b')"; } connection.execute(inserts); connection.setAutoCommit(true); connection.execute("INSERT INTO tableb VALUES(1000, 'b')"); TestHelper.refreshAndWait(connection); // BEGIN, data, END, BEGIN, data final SourceRecords records = consumeRecordsByTopic(1 + RECORDS_PER_TABLE * 2 + 1 + 1 + 1); final List<SourceRecord> tableA = records.recordsForTopic("testdb.DB2INST1.TABLEA"); final List<SourceRecord> tableB = records.recordsForTopic("testdb.DB2INST1.TABLEB"); final List<SourceRecord> tx = records.recordsForTopic("testdb.transaction"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE + 1); Assertions.assertThat(tx).hasSize(3); final List<SourceRecord> all = records.allRecordsInOrder(); final String txId = assertBeginTransaction(all.get(0)); long counter = 1; for (int i = 1; i <= 2 * RECORDS_PER_TABLE; i++) { assertRecordTransactionMetadata(all.get(i), txId, counter, (counter + 1) / 2); counter++; } assertEndTransaction(all.get(2 * RECORDS_PER_TABLE + 1), txId, 2 * RECORDS_PER_TABLE, Collect.hashMapOf("DB2INST1.TABLEA", RECORDS_PER_TABLE, "DB2INST1.TABLEB", RECORDS_PER_TABLE)); stopConnector(); } }
39.694915
114
0.668446
ddf776342f874abf1719a309fb90fd3c7bcfea5e
3,148
/** * * Copyright (c) Microsoft and contributors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. package com.microsoft.azure.management.sql.models; /** * Represents the properties of an Azure SQL Database. */ public class ServerProperties { private String administratorLogin; /** * Optional. Gets administrator username for the server. * @return The AdministratorLogin value. */ public String getAdministratorLogin() { return this.administratorLogin; } /** * Optional. Gets administrator username for the server. * @param administratorLoginValue The AdministratorLogin value. */ public void setAdministratorLogin(final String administratorLoginValue) { this.administratorLogin = administratorLoginValue; } private String administratorLoginPassword; /** * Optional. Gets the administrator login password. * @return The AdministratorLoginPassword value. */ public String getAdministratorLoginPassword() { return this.administratorLoginPassword; } /** * Optional. Gets the administrator login password. * @param administratorLoginPasswordValue The AdministratorLoginPassword * value. */ public void setAdministratorLoginPassword(final String administratorLoginPasswordValue) { this.administratorLoginPassword = administratorLoginPasswordValue; } private String fullyQualifiedDomainName; /** * Optional. Gets the fully qualified domain name of the server. * @return The FullyQualifiedDomainName value. */ public String getFullyQualifiedDomainName() { return this.fullyQualifiedDomainName; } /** * Optional. Gets the fully qualified domain name of the server. * @param fullyQualifiedDomainNameValue The FullyQualifiedDomainName value. */ public void setFullyQualifiedDomainName(final String fullyQualifiedDomainNameValue) { this.fullyQualifiedDomainName = fullyQualifiedDomainNameValue; } private String version; /** * Optional. Gets the version of the server. * @return The Version value. */ public String getVersion() { return this.version; } /** * Optional. Gets the version of the server. * @param versionValue The Version value. */ public void setVersion(final String versionValue) { this.version = versionValue; } }
30.563107
93
0.702351
87c02f1504d3fbe9ea9d898aefb7c1a6a032a31a
345
package systems.v.wallet.utils; import android.content.pm.ApplicationInfo; import android.util.Log; import com.alibaba.fastjson.JSON; import systems.v.wallet.App; import systems.v.wallet.basic.utils.JsonUtil; public class LogUtil { public static void Log(String tag, Object... args){ Log.d(tag, JSON.toJSONString(args)); } }
21.5625
55
0.73913
b23a2826a69d4837284d01937a9ad803d8fb11e6
1,395
/* * * Copyright (c) 2006-2020, Speedment, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); You may not * use this file except in compliance with the License. You may obtain a copy of * the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.speedment.runtime.core.internal.db; import com.speedment.common.logger.Level; import com.speedment.common.logger.Logger; import java.util.List; import java.util.stream.Collectors; public final class SqlQueryLoggerUtil { private SqlQueryLoggerUtil() {} public static void logOperation(Logger logger, final String sql, final List<?> values) { if (logger.getLevel().isEqualOrLowerThan(Level.DEBUG)) { final String text = sql + " " + values.stream() .map(o -> o == null ? "null" : o.getClass().getSimpleName() + " " + o.toString()) .collect(Collectors.joining(", ", "[", "]")); logger.debug(text); } } }
34.875
92
0.650179
70e6e6e2c6869d96d05f5d10eb56a53e9cee36bc
1,205
package mazegame; public class Monkey extends Sprite implements Moveable { /** Score of the player, initially set at 0. */ private int score = 0; /** Number of moves of a monkey made. */ private int numMoves; /** * Create a monkey with symbol "1" for player1, and symbol "2" for player2 * at the give row and column position. * @param symbol the symbol of unvisited hallway * @param row row position * @param col column position */ public Monkey(char symbol, int row, int col) { super(symbol, row, col); } /** * Score adds banana's value if a player ate an banana. * @param score the score this player has */ public void eatBanana(int score) { this.score += score; } /** * Return the score of this player. * @return the score of this player. */ public int getScore() { return score; } /** * Return the number of moves by this player. * @return the number of moves by this player */ public int getNumMoves() { return numMoves; } /** * Move this player to the given row and column position. * Add one to this play's number of moves. */ public void move(int row, int col) { this.row = row; this.column = col; numMoves += 1; } }
21.517857
75
0.658921
e7c5c503b6add11407eb5f5fa20d26aafc82999d
904
package ObjectOrientedDesign.RideSharingApplication; public class Ride { private Integer id; private Integer origin; private Integer destination; private Integer noOfSeats; private RideStatus rideStatus; public RideStatus getRideStatus() { return rideStatus; } public void setRideStatus(RideStatus rideStatus) { this.rideStatus = rideStatus; } public Ride(Integer origin, Integer destination, Integer noOfSeats) { this.origin = origin; this.destination = destination; this.noOfSeats = noOfSeats; this.rideStatus = RideStatus.CREATED; } public void setOrigin(Integer origin) { this.origin = origin; } public void setDestination(Integer destination) { this.destination = destination; } public void setNoOfSeats(Integer noOfSeats) { this.noOfSeats = noOfSeats; } public Integer calculateRideAmount(){ return null; } }
20.545455
71
0.72677
a22ce5c78939bec9330f291402278850ca596bbd
529
package org.openvasp.transfer.account; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.openvasp.client.config.LocalTestModule; /** * @author [email protected] */ @Tag("transfer") public class LocalAccountTransferIT extends BaseAccountTransferIT { public LocalAccountTransferIT() { super(LocalTestModule.module1, LocalTestModule.module2, LocalTestModule.module3); } @Test public void checkMultipleTransfers() { super.checkMultipleTransfers(); } }
23
89
0.746692
e42ef1d195dd154209a0350df9ebe424d5ff5cbe
622
package com.example.iavanish.popularmovies.util; import java.io.IOException; /** * Created by iavanish on 16/9/16. */ public class NetworkConnection { public static boolean isOnline() { Runtime runtime = Runtime.getRuntime(); try { Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); int exitValue = ipProcess.waitFor(); return (exitValue == 0); } catch(IOException e) { e.printStackTrace(); } catch(InterruptedException e) { e.printStackTrace(); } return false; } }
21.448276
78
0.569132
e7b519c58b873a842fcb1b9e3f889068623a376a
70
package pl.thecode.helper.chat; enum ChatUser { NEEDY, VOLUNTEER }
11.666667
31
0.742857
3b1d860932f1552baac0c520a02af26a66e4d903
1,055
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author dwigh */ public class Console { public static void main(String[] args) { Scanner in = new Scanner(System.in); MeerkeuzeVraag mkv = new MeerkeuzeVraag("Wat zit er op een 4 kazen pizza?", new String[]{"kaas", "screams of the damned", "bloed", "liefde"}, 0); int index = -1; while(!mkv.controleer(index)){ System.out.println(mkv.getVraag()); String[] antwoorden = mkv.getAntwoorden(); for (int i = 0; i < antwoorden.length; i++) { System.out.println(i + ": " + antwoorden[i]); } System.out.println("Say the index!"); index = in.nextInt(); if (!mkv.controleer(index)) System.out.println("WRONG"); } System.out.println("Well done! Shutting off."); } }
31.029412
153
0.575355
66212a667679a407fee83bae57447a65d26db048
9,091
/* * Copyright (C) 2009 The Sipdroid Open Source Project * Copyright (C) 2006 The Android Open Source Project * * This file is part of Sipdroid (http://www.sipdroid.org) * * Sipdroid is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This source code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this source code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.sipdroid.sipua.phone; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import org.sipdroid.sipua.*; public class PhoneUtils { private static final String LOG_TAG = "PhoneUtils"; private static final boolean DBG = false; /** * Class returned by the startGetCallerInfo call to package a temporary * CallerInfo Object, to be superceded by the CallerInfo Object passed * into the listener when the query with token mAsyncQueryToken is complete. */ public static class CallerInfoToken { /**indicates that there will no longer be updates to this request.*/ public boolean isFinal; public CallerInfo currentInfo; public CallerInfoAsyncQuery asyncQuery; } /** * Start a CallerInfo Query based on the earliest connection in the call. */ static CallerInfoToken startGetCallerInfo(Context context, Call call, CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { Connection conn = call.getEarliestConnection(); return startGetCallerInfo(context, conn, listener, cookie); } /** * place a temporary callerinfo object in the hands of the caller and notify * caller when the actual query is done. */ static CallerInfoToken startGetCallerInfo(Context context, Connection c, CallerInfoAsyncQuery.OnQueryCompleteListener listener, Object cookie) { CallerInfoToken cit; if (c == null) { //TODO: perhaps throw an exception here. cit = new CallerInfoToken(); cit.asyncQuery = null; return cit; } // There are now 3 states for the userdata. // 1. Uri - query has not been executed yet // 2. CallerInfoToken - query is executing, but has not completed. // 3. CallerInfo - query has executed. // In each case we have slightly different behaviour: // 1. If the query has not been executed yet (Uri or null), we start // query execution asynchronously, and note it by attaching a // CallerInfoToken as the userData. // 2. If the query is executing (CallerInfoToken), we've essentially // reached a state where we've received multiple requests for the // same callerInfo. That means that once the query is complete, // we'll need to execute the additional listener requested. // 3. If the query has already been executed (CallerInfo), we just // return the CallerInfo object as expected. // 4. Regarding isFinal - there are cases where the CallerInfo object // will not be attached, like when the number is empty (caller id // blocking). This flag is used to indicate that the // CallerInfoToken object is going to be permanent since no // query results will be returned. In the case where a query // has been completed, this flag is used to indicate to the caller // that the data will not be updated since it is valid. // // Note: For the case where a number is NOT retrievable, we leave // the CallerInfo as null in the CallerInfoToken. This is // something of a departure from the original code, since the old // code manufactured a CallerInfo object regardless of the query // outcome. From now on, we will append an empty CallerInfo // object, to mirror previous behaviour, and to avoid Null Pointer // Exceptions. Object userDataObject = c.getUserData(); if (userDataObject instanceof Uri) { //create a dummy callerinfo, populate with what we know from URI. cit = new CallerInfoToken(); cit.currentInfo = new CallerInfo(); cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, (Uri) userDataObject, sCallerInfoQueryListener, c); cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); cit.isFinal = false; c.setUserData(cit); if (DBG) log("startGetCallerInfo: query based on Uri: " + userDataObject); } else if (userDataObject == null) { // No URI, or Existing CallerInfo, so we'll have to make do with // querying a new CallerInfo using the connection's phone number. String number = c.getAddress(); cit = new CallerInfoToken(); cit.currentInfo = new CallerInfo(); if (DBG) log("startGetCallerInfo: number = " + number); // handling case where number is null (caller id hidden) as well. if (!TextUtils.isEmpty(number)) { cit.currentInfo.phoneNumber = number; cit.asyncQuery = CallerInfoAsyncQuery.startQuery(QUERY_TOKEN, context, number, c.getAddress2(), sCallerInfoQueryListener, c); cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); cit.isFinal = false; } else { // This is the case where we are querying on a number that // is null or empty, like a caller whose caller id is // blocked or empty (CLIR). The previous behaviour was to // throw a null CallerInfo object back to the user, but // this departure is somewhat cleaner. if (DBG) log("startGetCallerInfo: No query to start, send trivial reply."); cit.isFinal = true; // please see note on isFinal, above. } c.setUserData(cit); if (DBG) log("startGetCallerInfo: query based on number: " + number); } else if (userDataObject instanceof CallerInfoToken) { // query is running, just tack on this listener to the queue. cit = (CallerInfoToken) userDataObject; // handling case where number is null (caller id hidden) as well. if (cit.asyncQuery != null) { cit.asyncQuery.addQueryListener(QUERY_TOKEN, listener, cookie); if (DBG) log("startGetCallerInfo: query already running, adding listener: " + listener.getClass().toString()); } else { if (DBG) log("startGetCallerInfo: No query to attach to, send trivial reply."); if (cit.currentInfo == null) { cit.currentInfo = new CallerInfo(); } cit.isFinal = true; // please see note on isFinal, above. } } else { cit = new CallerInfoToken(); cit.currentInfo = (CallerInfo) userDataObject; cit.asyncQuery = null; cit.isFinal = true; // since the query is already done, call the listener. if (DBG) log("startGetCallerInfo: query already done, returning CallerInfo"); } return cit; } /** * Implemented for CallerInfo.OnCallerInfoQueryCompleteListener interface. * Updates the connection's userData when called. */ private static final int QUERY_TOKEN = -1; static CallerInfoAsyncQuery.OnQueryCompleteListener sCallerInfoQueryListener = new CallerInfoAsyncQuery.OnQueryCompleteListener () { public void onQueryComplete(int token, Object cookie, CallerInfo ci){ if (DBG) log("query complete, updating connection.userdata"); ((Connection) cookie).setUserData(ci); } }; /** * Returns a single "name" for the specified given a CallerInfo object. * If the name is null, return defaultString as the default value, usually * context.getString(R.string.unknown). */ static String getCompactNameFromCallerInfo(CallerInfo ci, Context context) { if (DBG) log("getCompactNameFromCallerInfo: info = " + ci); String compactName = null; if (ci != null) { compactName = ci.name; if (compactName == null) { compactName = ci.phoneNumber; } } // TODO: figure out UNKNOWN, PRIVATE numbers? if (compactName == null) { compactName = context.getString(R.string.unknown); } return compactName; } private static void log(String msg) { Log.d(LOG_TAG, "[PhoneUtils] " + msg); }}
42.882075
92
0.656473
8ca581409c7c2430e4567d52c4114eb8f2be5082
2,736
/* * Copyright 2013-2015 Sergey Ignatov, Alexander Zolotov, Florin Patan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.goide.refactor; import com.goide.psi.GoBlock; import com.goide.psi.GoStatement; import com.goide.psi.impl.GoPsiImplUtil; import com.intellij.codeInsight.PsiEquivalenceUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiRecursiveElementVisitor; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.List; public class GoRefactoringUtil { @NotNull public static List<PsiElement> getLocalOccurrences(@NotNull PsiElement element) { return getOccurrences(element, PsiTreeUtil.getTopmostParentOfType(element, GoBlock.class)); } @NotNull public static List<PsiElement> getOccurrences(@NotNull final PsiElement pattern, @Nullable PsiElement context) { if (context == null) return Collections.emptyList(); final List<PsiElement> occurrences = ContainerUtil.newArrayList(); PsiRecursiveElementVisitor visitor = new PsiRecursiveElementVisitor() { public void visitElement(@NotNull PsiElement element) { if (PsiEquivalenceUtil.areElementsEquivalent(element, pattern)) { occurrences.add(element); return; } super.visitElement(element); } }; context.acceptChildren(visitor); return occurrences; } @Nullable public static PsiElement findLocalAnchor(@NotNull List<PsiElement> occurrences) { return findAnchor(occurrences, PsiTreeUtil.getNonStrictParentOfType(PsiTreeUtil.findCommonParent(occurrences), GoBlock.class)); } @Nullable public static PsiElement findAnchor(@NotNull List<PsiElement> occurrences, @Nullable PsiElement context) { PsiElement first = ContainerUtil.getFirstItem(occurrences); PsiElement statement = PsiTreeUtil.getNonStrictParentOfType(first, GoStatement.class); while (statement != null && statement.getParent() != context) { statement = statement.getParent(); } return statement == null ? GoPsiImplUtil.getTopLevelDeclaration(first) : statement; } }
38
131
0.762427
0c0d3a496d4044f04a3c6872b86a119c323aa0c5
2,331
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.profitbricks.binder.storage; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import org.jclouds.profitbricks.domain.Storage; import org.testng.annotations.Test; @Test(groups = "unit", testName = "ConnectStorageToServerRequestBinderTest") public class ConnectStorageToServerRequestBinderTest { @Test public void testCreatePayload() { ConnectStorageToServerRequestBinder binder = new ConnectStorageToServerRequestBinder(); Storage.Request.ConnectPayload payload = Storage.Request.connectingBuilder() .serverId("qwertyui-qwer-qwer-qwer-qwertyyuiiop") .storageId("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh") .busType(Storage.BusType.VIRTIO) .deviceNumber(2) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); } private final String expectedPayload = (" <ws:connectStorageToServer>\n" + " <request>\n" + " <storageId>qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh</storageId>\n" + " <serverId>qwertyui-qwer-qwer-qwer-qwertyyuiiop</serverId>\n" + " <busType>VIRTIO</busType>\n" + " <deviceNumber>2</deviceNumber>\n" + " </request>\n" + " </ws:connectStorageToServer>") .replaceAll("\\s+", ""); }
41.625
93
0.679108
9c7274693969be656a56dac23f9576f50624c5a5
6,156
/* * Copyright 2018 jd.com * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.yihaodian.architecture.kira.manager.dao.mybatis; import com.yihaodian.architecture.kira.manager.criteria.JobHistoryCriteria; import com.yihaodian.architecture.kira.manager.dao.JobHistoryDao; import com.yihaodian.architecture.kira.manager.domain.JobHistory; import com.yihaodian.architecture.kira.manager.domain.JobHistoryDetailData; import com.yihaodian.architecture.kira.manager.util.Paging; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.springframework.dao.DataAccessException; import org.springframework.util.Assert; public class JobHistoryDaoImpl implements JobHistoryDao { private SqlSession sqlSession; public void setSqlSession(SqlSession sqlSession) { this.sqlSession = sqlSession; } public void insert(JobHistory jobHistory) throws DataAccessException { sqlSession.insert("JobHistory.insert", jobHistory); } public int update(JobHistory jobHistory) throws DataAccessException { int actualRowsAffected = 1; sqlSession.update("JobHistory.update", jobHistory); return actualRowsAffected; } public int delete(String id) throws DataAccessException { int actualRowsAffected = 1; sqlSession.delete("JobHistory.delete", id); return actualRowsAffected; } public JobHistory select(String id) throws DataAccessException { return (JobHistory) sqlSession.selectOne("JobHistory.select", id); } @SuppressWarnings("unchecked") public List<JobHistory> list(JobHistoryCriteria jobHistoryCriteria) throws DataAccessException { Assert.notNull(jobHistoryCriteria, "jobHistoryCriteria must not be null"); return sqlSession.selectList("JobHistory.list", jobHistoryCriteria); } @SuppressWarnings("unchecked") public List<JobHistory> listOnPage(JobHistoryCriteria jobHistoryCriteria) throws DataAccessException { Assert.notNull(jobHistoryCriteria, "jobHistoryCriteria must not be null"); Assert.notNull(jobHistoryCriteria.getPaging(), "paging must not be null"); int totalResults = count(jobHistoryCriteria); Paging paging = jobHistoryCriteria.getPaging(); paging.setTotalResults(totalResults); RowBounds rowBounds = new RowBounds(paging.getFirstResult(), paging.getMaxResults()); return sqlSession.selectList("JobHistory.list", jobHistoryCriteria, rowBounds); } public int count(JobHistoryCriteria jobHistoryCriteria) throws DataAccessException { Assert.notNull(jobHistoryCriteria, "jobHistoryCriteria must not be null"); return ((Integer) sqlSession.selectOne("JobHistory.count", jobHistoryCriteria)).intValue(); } @Override public List<JobHistoryDetailData> getJobHistoryDetailDataListOnPage( JobHistoryCriteria jobHistoryCriteria) throws DataAccessException { Assert.notNull(jobHistoryCriteria, "jobHistoryCriteria must not be null"); Assert.notNull(jobHistoryCriteria.getPaging(), "paging must not be null"); int totalResults = countJobHistoryDetailDataList(jobHistoryCriteria); Paging paging = jobHistoryCriteria.getPaging(); paging.setTotalResults(totalResults); RowBounds rowBounds = new RowBounds(paging.getFirstResult(), paging.getMaxResults()); return sqlSession .selectList("JobHistory.getJobHistoryDetailDataList", jobHistoryCriteria, rowBounds); } @Override public int countJobHistoryDetailDataList( JobHistoryCriteria jobHistoryCriteria) throws DataAccessException { Assert.notNull(jobHistoryCriteria, "jobHistoryCriteria must not be null"); return ((Integer) sqlSession .selectOne("JobHistory.countJobHistoryDetailDataList", jobHistoryCriteria)).intValue(); } @Override public int createArchiveTableAndDataForJobHistoryTable( String newTableNameSuffix, Date startTime, Date endTime) { Map<String, Object> map = new HashMap<String, Object>(); map.put("newTableNameSuffix", newTableNameSuffix); map.put("startTime", startTime); map.put("endTime", endTime); return sqlSession.update("JobHistory.createArchiveTableAndDataForJobHistoryTable", map); } @Override public int createArchiveTableForJobHistoryTableIfNeeded( String newTableNameSuffix) { Map<String, Object> map = new HashMap<String, Object>(); map.put("newTableNameSuffix", newTableNameSuffix); return sqlSession.update("JobHistory.createArchiveTableForJobHistoryTableIfNeeded", map); } @Override public Object insertDataToJobHistoryArchiveTable(String newTableNameSuffix, Date startTime, Date endTime) { Map<String, Object> map = new HashMap<String, Object>(); map.put("newTableNameSuffix", newTableNameSuffix); map.put("startTime", startTime); map.put("endTime", endTime); return sqlSession.insert("JobHistory.insertDataToJobHistoryArchiveTable", map); } @Override public int deleteJobHistoryData(Date startTime, Date endTime) { Map<String, Object> map = new HashMap<String, Object>(); map.put("startTime", startTime); map.put("endTime", endTime); return sqlSession.delete("JobHistory.deleteJobHistoryData", map); } @Override public Date getDateOfOldestJobHistory() { Date dateOfOldestJobHistory = null; dateOfOldestJobHistory = (Date) sqlSession.selectOne("JobHistory.getDateOfOldestJobHistory"); return dateOfOldestJobHistory; } }
39.210191
99
0.75
a3d71efc302b57a3fbdea2001340de46d3304f4f
573
package com.bmsoft.canteensystem.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; /** * 店铺表 * @author guoguo */ @AllArgsConstructor @NoArgsConstructor @Data @Accessors(chain = true) public class Shop implements Serializable { private Integer shopId;//店铺id private String shopName;//店铺名 private String shopMorning;//当日早餐最晚下单时间 private String shopNoon;//当日午餐最晚下单时间 private String shopEvening;//当日晚餐最晚下单时间 private User user;//用户 }
21.222222
44
0.767888
622594f42ad955064c20c383177b2909eae5ad59
2,277
package com.touchableheroes.drafts.spacerx.ui.binding; import android.content.Context; import android.support.v4.app.Fragment; import android.view.View; import com.touchableheroes.drafts.spacerx.dom.SyntheticDOM; import com.touchableheroes.drafts.spacerx.dom.SyntheticDomFactory; import com.touchableheroes.drafts.spacerx.dom.values.Getter; import com.touchableheroes.drafts.spacerx.ui.builder.ChangeValueBindingBuilder; import com.touchableheroes.drafts.spacerx.ui.builder.ViewBindingBuilder; import java.io.Serializable; import java.lang.ref.WeakReference; /** * Created by asiebert on 12.04.2017. */ public abstract class AbstractUIBinder<T> implements HasOwner<T> { private final SyntheticDOM synthDom; private final WeakReference<T> owner; protected abstract View view(); public AbstractUIBinder(T owner) { this.owner = new WeakReference<T>(owner); this.synthDom = SyntheticDomFactory.create(); } @Override public T owner() { final T rval = (T) owner.get(); if( rval == null ) { throw new IllegalStateException( "Backref.Fragement is broken/ maybe destroyed." ); } return rval; } public SyntheticDOM syntheticDom() { return synthDom; } public abstract void bind(); public abstract void init(final Context ctx); public void destroy() { this.syntheticDom().unbind(); } protected <T extends Serializable> void getter( final Enum key, final Getter<T> getterImpl) { syntheticDom().register(key, getterImpl); } protected ViewBindingBuilder bind(final int id) { final View view = view().findViewById(id); if( view == null ) { throw new IllegalStateException( ("View not found. ID = " + id) ); } try { return new ViewBindingBuilder( view, syntheticDom() ); } catch (final ClassCastException ccx) { throw new IllegalStateException( "Cast not correct. View is of type [= " + view.getClass().getName() + "]" ); } } protected ChangeValueBindingBuilder onChange(final Enum... changes) { return new ChangeValueBindingBuilder( syntheticDom(), changes); } }
26.788235
121
0.662714
6c996cb6f884f866137487ecbebac6b23f84722e
593
package com.cs.scu.service.impl; import com.cs.scu.entity.User; import com.cs.scu.mapper.UserMapper; import com.cs.scu.service.LoginService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class LoginServiceImpl implements LoginService { @Autowired private UserMapper userMapper; public User doUserLogin(User user) throws Exception { return userMapper.doUserLogin(user); } public User doUserVerify(User user) throws Exception { return userMapper.doUserVerify(user); } }
25.782609
62
0.763912
b5e3250d861dfc9aee5117896e396d5cc425b891
246
package io.github.thecursedfabricproject.cursedfluidapi; public enum Simulation { SIMULATE, ACT; public boolean isSimulate() { return this == SIMULATE; } public boolean isAct() { return this == ACT; } }
16.4
56
0.626016
fdb6eb8c79ad32954137010f629032650504c091
371
package com.sourcesense.joyce.sink.mongodb.service; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; public interface ResourceLoader { default Path loadResource(String name) throws URISyntaxException { URL res = this.getClass().getClassLoader().getResource(name); return Paths.get(res.toURI()); } }
24.733333
67
0.778976
abf5ad5ce9cfd6130a3e2411c3845116179c369f
11,006
package com.github.ryan.data_structure.concurrent; import java.lang.Runnable; import java.security.AccessControlContext; import static java.lang.Thread.currentThread; /** * When a Java Virtual Machine starts up, there is usually a single * non-daemon thread (which typically calls the method named main of * some designated class). The Java Virtual Machine continues to execute * threads until either of the following occurs: * * 1.The exit method of class Runtime has been called and the security * manager has permitted the exit operation to take place. * 2.All threads that are not daemon threads have died, either by * returning from the call to run method or by throwing an exception * that propagates beyond the run method. * */ public class Thread1 implements java.lang.Runnable { // What will be run. private Runnable target; // Whether or not the thread is a daemon thread private boolean daemon = false; private int priority; // The group of this thread private ThreadGroup group; // The context ClassLoader for this thread private ClassLoader contextClassLoader; // Thread ID private long tid; // ThreadLocal values pertaining to this thread. This map is maintained // by the ThreadLocal class. // ThreadLocal.ThreadLocalMap threadLocals = null; /** * Java thread status for tools, * initialized to indicate thread 'not yet started' */ private volatile int threadStatus = 0; /** * Causes this thread to begin execution; the Java Virtual Machine * calls the run method of this thread. * The result is that two threads are running concurrently: the * current thread (which returns from the call to the start method) * and the other thread (which executes its run method). * * It is never legal to start a thread more than once. * In particular, a thread may not be restarted once it has completed * execution. * * @throws IllegalThreadStateException if the thread was already started. * @see #run() */ public synchronized void start() { /** * This method is not invoked for the main method or "system" * group threads created/set up by the VM. Any new functionality * added to this method in the future may have to also be * added to the VM. * * A zero status value corresponds to state "NEW". */ if (threadStatus != 0) { throw new IllegalThreadStateException(); } // start0(); } @Override public void run() { if (target != null) { target.run(); } } // public Thread(Runnable target) { // init(null, target, "Thread-" + nextThreadNum(), 0); // } /** * Initializes a Thread. * * @param g teh Thread group * @param target the object whose run() method gets called * @param name the name of the new Thread * @param stackSize the desired stack size for the new thread, or * zero to indicate that this parameter is to be ignored. * @param accessControlContext the AccessControlContext to inherit, or * AccessController.getContext if null */ private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext accessControlContext) { if (name == null) { throw new NullPointerException("name cannot be null"); } Thread parent = currentThread(); if (g == null) { // ... if (g == null) { g = parent.getThreadGroup(); } } // ... this.group = g; this.daemon = parent.isDaemon(); this.priority = parent.getPriority(); this.target = target; // setPriority(priority); // this.stackSize = stackSize; // tid = nextThreadID(); // if (parent.inheritableThreadLocals != null) { // this.inheritableThreadLocals = // ThreadLocal.createInheritedMap(parent.inheritableThreadLocals); // } } /** * Returns an array of stack trace elements representing the stack dump * of this thread. This method will return a zero-length array if * this thread has not started, has started but has not yet been * scheduled to run by the system, or has terminated. * If the returned array is of non-zero length then the first element * of the array represents the top of the stack, which is the most recent * method invocation in the sequence. The last element of the array * represents the bottom of the stack, which is the least recent method * invocation in the sequence. * * @return an array of StackTraceElement each represents on stack frame. */ public StackTraceElement[] getStateTrace() { return null; } /** * Returns a reference to the currently executing thread object. * * @return the currently executing thread. */ // public static native Thread currentThread(); /** * Causes the currently executing thread to sleep (temporarily cease * execution) for the specified number of milliseconds, subject to * the precision and accuracy of system timers and schedulers. The * thread does not lose ownership of any monitors. * * @param millis the length of time to sleep in milliseconds. * @throws IllegalArgumentException if the value of millis is negative * @throws InterruptedException * if any thread has interrupted the current thread. The * interrupted status of the current thread is cleared * when this exception is thrown. */ public static native void sleep(long millis) throws InterruptedException; // Tests if this thread is alive, a thread is alive if it has // been started and has not yet died. public final native boolean isAlive(); /** * Waits at most millis milliseconds for this thread to * die. A timeout of {@code 0} means to wait forever. * * This implementation uses a loop of {@code this.wait} calls * conditioned on {@code this.isAlive}. As a thread terminates the * {@code this.notifyAll} method is invoked. It is recommended that * applications not use wait, notify, or notifyAll on Thread instance * * @param millis the time to wait in milliseconds * @throws InterruptedException * if any thread has interrupted the current thread. The * interrupted status of the current thread is * cleared when this exception is thrown. */ public final synchronized void join(long millis) throws InterruptedException { // ... if (millis < 0) { throw new IllegalArgumentException("timeout value is negative"); } // My question is: where is (and who calls) the notify() or notifyAll() // when the thread completes, so that it wakes up the calling thread? // Answer: // notifyAll (or its native equivalent) is called in ensure_join in // src/share/vm/runtime/thread.cpp, at line 1526 in the current version, // which is called from JavaThread::exit in the same file. if (millis == 0) { while (isAlive()) { // Causes the current thread to wait until .... // 当前线程是调用 t.join() 线程方法的线程 // 当前线程会在 t 对象的 wait set进行等待 wait(0); } } else { } } /** * A thread state. A thread can be in one of the following states: * NEW: * A thread that has not yet started is in this state. * * RUNNABLE: * A thread executing in the Java virtual machine is in this state. * * BLOCKED: * A thread that is blocked waiting for a monitor lock is in this state. * * WAITING: * A thread that is waiting indefinitely for another thread to * perform a particular action is in this state. * * TIMED_WAITING: * A thread that is waiting for another thread to perform an action * for up to a specified waiting time is in this state. * * TERMINATED: * A thread that has exited is in this state. * * A thread can be in only one state at a given point in time. * These states are virtual machine states which do not reflect * any operating system thread states. * * @see #getState */ public enum State { /** * Thread state for a thread which has not yet started. */ NEW, /** * Thread state for a runnable thread. A thread in the runnable * state is executing in the Java virtual machine but it may * be waiting for other resources from the operating system * such as processor. */ RUNNABLE, /** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * Object.wait(). */ BLOCKED, /** * Thread state for a waiting thread. * A thread is in teh waiting state due to calling one of the * following methods: * Object.wait with no timeout * Thread.join with no timeout * LockSupport.park * * A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called Object.wait() on an * object is waiting for another thread to call Object.notify() * or Object.notifyAll() on that object. A thread that has called * Thread.join() is waiting for a specified thread to terminate. */ WAITING, /** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling on of * the following methods with a specified positive waiting time: * Thread.sleep(); * Object.wait with timeout * Thread.join with timeout * LockSupport#parkNanos * LockSupport#parkUntil */ TIMED_WAITING, /** * Thread state for a terminated thread. * The thread has completed execution. */ TERMINATION; } /** * Returns the state of this thread. * This method is designed for use in monitoring of the system state, * not for synchronization control. * * @return this thread's state. */ public State getState() { return null; // get current thread state // return sun.misc.VM.toThreadState(threadStatue); } }
35.850163
82
0.621933
ec816767e47fa4589975c2440d74edf657170898
1,736
package org.blackbox.bricksole; /** * Class to manage the model of a command parameter */ class CommandParameter { private final String name; private final boolean required; private final String defaultValue; private final Class<?> type; CommandParameter(String name, boolean required, String defaultValue, Class<?> type) { this.name = name; this.required = required; this.defaultValue = defaultValue; this.type = type; } public String getName() { return name; } public boolean isRequired() { return required; } public String getDefaultValue() { return defaultValue; } public Class<?> getType() { return type; } public boolean isNamed() { return name != null; } static CommandParameter of(MethodParameter methodParameter) { CommandParam commandParamAnnotation = methodParameter.getAnnotation(CommandParam.class); Class<?> parameterType = methodParameter.getType(); if (commandParamAnnotation != null) { String parameterName = commandParamAnnotation.value(); boolean required = commandParamAnnotation.required(); String defaultValue = commandParamAnnotation.defaultValue(); if (defaultValue.equals(B.COMMAND_PARAMETER_DEFAULT_VALUE)) { defaultValue = null; } return new CommandParameter(parameterName, required, defaultValue, parameterType); } else { return new CommandParameter(null, true, null, parameterType); } } public boolean hasDefaultValue() { return !B.COMMAND_PARAMETER_DEFAULT_VALUE.equals(this.defaultValue); } }
28.933333
96
0.648618
4bccc8a4c3d379a55cfd5834662a29c339f21ab2
3,277
package org.haobtc.wallet.activities.settings; import android.annotation.SuppressLint; import android.content.Intent; import android.view.View; import android.widget.Switch; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.haobtc.wallet.R; import org.haobtc.wallet.activities.base.BaseActivity; import org.haobtc.wallet.activities.service.CommunicationModeSelector; import org.haobtc.wallet.event.ButtonRequestEvent; import org.haobtc.wallet.event.HandlerEvent; import org.haobtc.wallet.event.SetBluetoothEvent; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import cn.com.heaton.blelibrary.ble.Ble; public class BixinKeyBluetoothSettingActivity extends BaseActivity { public static final String TAG_TRUE = BixinKeyBluetoothSettingActivity.class.getSimpleName(); public static final String TAG_FALSE = "TAG_FALSE_BLUETOOTH_CLOSE"; private String bleName; @BindView(R.id.switchHideBluetooth) Switch switchHideBluetooth; @Override public int getLayoutId() { return R.layout.activity_bixin_key_bluetooth_setting; } @SuppressLint("CommitPrefEdits") @Override public void initView() { ButterKnife.bind(this); EventBus.getDefault().register(this); } @Override public void initData() { bleName = getIntent().getStringExtra("ble_name"); } @Subscribe(threadMode = ThreadMode.MAIN) public void event(SetBluetoothEvent updataHint) { } //Click the confirm button to indicate success @Subscribe(threadMode = ThreadMode.MAIN) public void eventa(ButtonRequestEvent event) { mToast(getString(R.string.confirm_hardware_msg)); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } @OnClick({R.id.img_back, R.id.text_open, R.id.text_close}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.img_back: finish(); break; case R.id.text_open: nModeSelector(true); break; case R.id.text_close: nModeSelector(false); break; } } private void nModeSelector(boolean status) { if (Ble.getInstance().getConnetedDevices().size() != 0) { if (Ble.getInstance().getConnetedDevices().get(0).getBleName().equals(bleName)) { EventBus.getDefault().postSticky(new HandlerEvent()); } } if (status) { Intent intent = new Intent(BixinKeyBluetoothSettingActivity.this, CommunicationModeSelector.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); intent.putExtra("tag", TAG_TRUE); startActivity(intent); } else { Intent intent = new Intent(BixinKeyBluetoothSettingActivity.this, CommunicationModeSelector.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); intent.putExtra("tag", TAG_FALSE); startActivity(intent); } } }
32.445545
111
0.683857
a693a2c8cf6e6f8a9af581ca85a5c9456cc76e6d
262
package tutorial03; /** * * @author ainzone * @version 1.0 */ public class StudentTester { public static void main(String[] args) { Student ourStudent = new Student("Jonathan", "Hinkel", 319401); ourStudent.registerForExam(""); } }
17.466667
72
0.629771
84a70e65843ff13bccc989edb27335ead228d7c4
897
package gov.loc.rdc.app; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableScheduling; /** * Starts the spring-boot application. * Also controls which packages get scanned and what spring beans to add to the context. */ @SpringBootApplication @ComponentScan("gov.loc.rdc") @EnableAutoConfiguration @EnableConfigurationProperties @EnableScheduling public class MainApplication{ public static void main(String[] args) { SpringApplication app = new SpringApplication(MainApplication.class); app.setShowBanner(false); app.run(args); } }
33.222222
88
0.820513
30107b66631b287fbd1fbd516cd8e9654e824b25
1,653
import edu.duke.*; import java.io.*; import java.lang.*; import java.util.*; public class WordFrequencies { private ArrayList<String> myWords; private ArrayList<Integer> myFreqs; public WordFrequencies(){ myWords = new ArrayList<String>(); myFreqs = new ArrayList<Integer>(); } public void findUnique(){ myWords.clear(); myFreqs.clear(); FileResource fr = new FileResource(); for(String word : fr.words()){ word = word.toLowerCase(); int index = myWords.indexOf(word); if(index==-1){ myWords.add(word); myFreqs.add(1); } else{ int value = myFreqs.get(index); myFreqs.set(index,value+1); } } } public void tester(){ findUnique(); //for(int i=0;i<myWords.size();i++){ // System.out.print(myWords.get(i) + " "); // System.out.println(myFreqs.get(i)); //} System.out.println("Unique words found : " + myWords.size()); System.out.println("Highest frequency at Index : " + findIndexOfMax() + " At word : " + myWords.get(findIndexOfMax()) + " with freq : " + myFreqs.get(findIndexOfMax())); } public int findIndexOfMax(){ int maxF = 0; int maxI = -1; int temp = 0; for(int i=0;i<myFreqs.size();i++){ temp = myFreqs.get(i); if(temp>maxF){ maxF = temp; maxI = i; } } return maxI; } }
26.238095
177
0.485178
c8f064303253996d55aa9320dfb38acde92c5487
751
package com.codigodelsur.photoexample.di; import com.codigodelsur.photoexample.di.fragment.builder.DetailFragmentBuilderModule; import com.codigodelsur.photoexample.di.fragment.builder.MainFragmentBuilderModule; import com.codigodelsur.photoexample.ui.detail.DetailActivity; import com.codigodelsur.photoexample.ui.main.MainActivity; import dagger.Module; import dagger.android.ContributesAndroidInjector; /** * Created by valentin on 6/19/17. */ @Module public abstract class ActivityBuilderModule { @ContributesAndroidInjector(modules = MainFragmentBuilderModule.class) abstract MainActivity mainActivity(); @ContributesAndroidInjector(modules = DetailFragmentBuilderModule.class) abstract DetailActivity detailActivity(); }
31.291667
85
0.829561
de3841879626c6db510f19ea91040355b181d25b
298
package app.jg.og.zamong.exception.business; import app.jg.og.zamong.exception.ErrorCode; public class CommentNotFoundException extends BusinessException { public CommentNotFoundException(String message) { super(message); setErrorCode(ErrorCode.COMMENT_NOT_FOUND); } }
21.285714
65
0.758389
0424db0dd03897286c4dea8f0b76806b1c6efea3
3,972
package com.sampleapp.module.musiclist; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import com.sampleapp.R; import com.sampleapp.base.BaseActivity; import com.sampleapp.base.BaseApplication; import com.sampleapp.model.response.ituneresponse.Entry; import com.sampleapp.receivers.ConnectivityReceiver; import com.sampleapp.utils.AppUtils; import com.sampleapp.utils.UtilsModule; import java.util.List; import javax.inject.Inject; import butterknife.BindView; import butterknife.OnClick; public class MusicListActivity extends BaseActivity implements MusicListView, ConnectivityReceiver.ConnectivityReceiverListener { //bind views @BindView(R.id.recycler_view) RecyclerView recyclerView; @BindView(R.id.refresh_button) FloatingActionButton refreshButton; //dependency injections @Inject AppUtils appUtils; @Inject MusicListPresenter musicListPresenter; @Inject MusicAdapter musicAdapter; @Inject LinearLayoutManager linearLayoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /**creating component {@link LoginComponent}for dependency injection*/ DaggerMusicListComponent.builder() .utilsModule(new UtilsModule(this)) .musicListModule(new MusicListModule(this)) .build().inject(this); /**attaching view{@link LoginView} to our presenter*/ musicListPresenter.attachView(this); /** * set up recycler view {@link MusicAdapter} */ setUpRecyclerView(); } /** * recycler view set up */ private void setUpRecyclerView() { recyclerView.setAdapter(musicAdapter); recyclerView.setLayoutManager(linearLayoutManager); } @Override protected void onResume() { super.onResume(); // register connection status listener BaseApplication.getContext().setConnectivityListener(this); //musicListPresenter fetch music play list fetchMusicFromDataSource(); } private void fetchMusicFromDataSource() { if (appUtils.isOnline(recyclerView)) musicListPresenter.fetchMusicList(); else { musicListPresenter.fetchMusicOffline(); } } /** * set layout for this activity */ @Override public int getLayout() { return R.layout.activity_music_list; } /** * set tool bar title * * @return */ @Override protected String getToolbarTitle() { return getString(R.string.music_list); } /** * return intent for this activity */ public static Intent createIntent(Context context) { return new Intent(context, MusicListActivity.class); } /** * if change in internet broad cast received * * @param isConnected */ @Override public void onNetworkConnectionChanged(boolean isConnected) { String message = (isConnected) ? "Good! Connected to Internet" : "Sorry! Not connected to internet"; if (!TextUtils.isEmpty(message)) { appUtils.showSnackBar(refreshButton, message); } refreshButton.setEnabled(isConnected); } /** * on fetch music success * * @param entry */ @Override public void onMusicSuccess(List<Entry> entry) { musicAdapter.updateData(entry); } /** * on title fetched * * @param label */ @Override public void onTitleFetched(String label) { setToolbarTitle(label); } @OnClick(R.id.refresh_button) public void onRefreshClick() { fetchMusicFromDataSource(); } }
25.461538
129
0.670443
40d53148b9d16eafde73aec2a89b16794bb0cfb4
472
package STRING; import java.io.*; class frequencyofallletters { public static void main(String[]args)throws IOException { InputStreamReader ab=new InputStreamReader(System.in); BufferedReader cd=new BufferedReader(ab); String n; int i,j,l,f=0; System.out.println("Enter any string:"); n=cd.readLine(); l=n.length(); for(i=65;i<=90;i++) { for(j=0;j<l;j++) { if(n.charAt(j)==i) { f++; } } if(f>0) { System.out.println((char)i+"\t"+f); } } } }
15.225806
56
0.637712
50ea4a96b1e8fd882959eea71a72d356d01fe747
860
/* This code originated as a project for the COMP 520 class at McGill * University in Winter 2015. Any subsequent COMP 520 student who is * viewing this code must follow the course rules and report any viewing * and/or use of the code. */ package golite; public class GoLiteWeedingException extends RuntimeException { private static final long serialVersionUID = 868259916037491128L; public GoLiteWeedingException() { } public GoLiteWeedingException(String message) { super(message); } public GoLiteWeedingException(Throwable cause) { super(cause); } public GoLiteWeedingException(String message, Throwable cause) { super(message, cause); } public GoLiteWeedingException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
26.875
72
0.77907
ddbafd0cc955c4e1189e136a0a52a64cc1562fa2
4,393
package com.xem.mzbcustomerapp.activity; import android.content.Intent; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.loopj.android.http.RequestParams; import com.xem.mzbcustomerapp.R; import com.xem.mzbcustomerapp.base.BaseActivity; import com.xem.mzbcustomerapp.net.MzbHttpClient; import com.xem.mzbcustomerapp.net.MzbUrlFactory; import com.xem.mzbcustomerapp.net.NetCallBack; import com.xem.mzbcustomerapp.utils.Config; import com.xem.mzbcustomerapp.view.TitleBuilder; import org.json.JSONException; import org.json.JSONObject; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick; /** * Created by xuebing on 15/11/8. */ public class A0_CheckSexActivity extends BaseActivity { @InjectView(R.id.titlebar_iv_left) ImageView back; @InjectView(R.id.titlebar_tv_right) TextView titlebar_tv_right; @InjectView(R.id.boy) ImageView boy; @InjectView(R.id.girl) ImageView girl; @InjectView(R.id.ll_boy) View ll_boy; @InjectView(R.id.ll_girl) View ll_girl; private String strSex; private int flag = -1; private int resultCode = -110; @Override protected void initView() { setContentView(R.layout.a0_checksex_activity); new TitleBuilder(this).setTitleText("选择性别").setLeftImage(R.mipmap.top_view_back).setRightText("保存"); ButterKnife.inject(this); strSex = getIntent().getStringExtra("info"); if (strSex == null){ girl.setVisibility(View.INVISIBLE); boy.setVisibility(View.INVISIBLE); } else if (strSex.equals("F")){ flag = 0; girl.setVisibility(View.VISIBLE); }else { flag = 1; boy.setVisibility(View.VISIBLE); } } @Override protected void initData() { } Intent intents; @OnClick({R.id.titlebar_iv_left,R.id.ll_boy,R.id.ll_girl,R.id.titlebar_tv_right}) public void clickAction(View view){ intents =new Intent(); switch (view.getId()){ case R.id.titlebar_iv_left: Intent intent = new Intent(); intent.putExtra("extra", strSex); setResult(resultCode, intent); finish(); break; case R.id.ll_boy: boy.setVisibility(View.VISIBLE); girl.setVisibility(View.INVISIBLE); strSex = "M"; flag = 1; break; case R.id.ll_girl: girl.setVisibility(View.VISIBLE); boy.setVisibility(View.INVISIBLE); strSex = "F"; flag = 0; break; case R.id.titlebar_tv_right: if (flag == 0){ commitModify("F"); setResult(-110,intents.putExtra("extra","女")); // showToast("女"); }else if (flag == 1){ commitModify("M"); setResult(-110,intents.putExtra("extra","男")); // showToast("男"); } else{ showToast("请选择性别后进行保存"); } break; default: break; } } private void commitModify(final String sex) { showToast("请求调用"); RequestParams params1 = new RequestParams(); params1.put("type", "3"); params1.put("sex", sex); params1.put("uid", Config.getCachedUid(A0_CheckSexActivity.this)); MzbHttpClient.ClientTokenPost(A0_CheckSexActivity.this, MzbUrlFactory.BASE_URL + MzbUrlFactory.minfo, params1, new NetCallBack(this) { @Override public void onMzbSuccess(String result) { try { JSONObject obj = new JSONObject(result); if (obj.getInt("code") == 0) { showToast("修改成功"); setResult(-110, intents.putExtra("extra", sex)); finish(); } } catch (JSONException e) { e.printStackTrace(); } } @Override public void onMzbFailues(Throwable arg0) { showToast("请求失败"); } }); } }
30.506944
142
0.55725