text
stringlengths
10
2.72M
/* * 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 package1; import java.awt.print.PrinterException; /** * * @author ARSHAD */ public class Counter extends javax.swing.JFrame { /** * Creates new form Counter */ public Counter() { initComponents(); } /** * 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(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); name = new javax.swing.JTextField(); watermelon = new javax.swing.JTextField(); apple = new javax.swing.JTextField(); grapes = new javax.swing.JTextField(); banana = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); jLabel8 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); cherry = new javax.swing.JTextField(); strawberry = new javax.swing.JTextField(); mango = new javax.swing.JTextField(); chickoo = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); area = new javax.swing.JTextArea(); generate = new javax.swing.JButton(); print = new javax.swing.JButton(); reset = new javax.swing.JButton(); menu = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N jLabel1.setText("Tasty Fruits And Vegetables"); jLabel2.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel2.setText("Watermelon X"); jLabel3.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Name of Customer :"); jLabel4.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel4.setText("Apple X"); jLabel5.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel5.setText("Grapes X"); jLabel6.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel6.setText("Banana X"); name.setFont(new java.awt.Font("Times New Roman", 0, 18)); // NOI18N watermelon.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N apple.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N grapes.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N banana.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N jLabel7.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel7.setText("Mango X"); jLabel8.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel8.setText("Chickoo X"); jLabel9.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel9.setText("Cherry X"); jLabel10.setFont(new java.awt.Font("Comic Sans MS", 0, 18)); // NOI18N jLabel10.setText("Strawberry X"); cherry.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N strawberry.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N mango.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N chickoo.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N area.setColumns(20); area.setFont(new java.awt.Font("Arial", 0, 18)); // NOI18N area.setRows(5); jScrollPane1.setViewportView(area); generate.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N generate.setText("Generate"); generate.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { generateActionPerformed(evt); } }); print.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N print.setText("Print"); print.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { printActionPerformed(evt); } }); reset.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N reset.setText("Reset"); reset.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { resetActionPerformed(evt); } }); menu.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N menu.setText("Menu"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addGap(354, 354, 354) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 354, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(menu)) .addGroup(layout.createSequentialGroup() .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(watermelon, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 60, Short.MAX_VALUE) .addComponent(banana, javax.swing.GroupLayout.Alignment.LEADING) .addComponent(apple) .addComponent(grapes, javax.swing.GroupLayout.Alignment.LEADING)))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(36, 36, 36) .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(46, 46, 46) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(31, 31, 31)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel10) .addGap(18, 18, 18))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(mango, javax.swing.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE) .addComponent(strawberry) .addComponent(cherry) .addComponent(chickoo)))) .addGap(89, 89, 89) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 488, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(generate, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(reset, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(78, 78, 78) .addComponent(print, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(44, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(menu, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(34, 34, 34) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(name) .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)) .addGap(26, 26, 26) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(apple, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(4, 4, 4)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(chickoo, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(38, 38, 38) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cherry, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(watermelon, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(38, 38, 38))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(banana, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel10, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(strawberry, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(grapes, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(mango, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(generate, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(print, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(reset, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(41, 41, 41)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void generateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateActionPerformed // TODO add your handling code here: int apc,bac,grc,chc,chec,stc,mac,wac; String aps,bas,grs,chs,ches,sts,mas,was; // apple apc=Integer.parseInt(apple.getText()); aps=Integer.toString(apc*10); //area.setText(aps); //System.out.println(apc); //banana bac=Integer.parseInt(banana.getText()); bas=Integer.toString(bac*10); //grapes grc=Integer.parseInt(grapes.getText()); grs=Integer.toString(grc*10); //watermelon wac=Integer.parseInt(watermelon.getText()); was=Integer.toString(wac*10); //chickoo chc=Integer.parseInt(chickoo.getText()); chs=Integer.toString(chc*10); //cherry chec=Integer.parseInt(cherry.getText()); ches=Integer.toString(chec*10); //strawberry stc=Integer.parseInt(strawberry.getText()); sts=Integer.toString(stc*10); //mango mac=Integer.parseInt(mango.getText()); mas=Integer.toString(mac*10); area.setText(" Tasty Fruit Shop \n"); area.setText(area.getText()+" (Invoice)\n\n"); area.setText(area.getText()+"Customer Name : "+name.getText()); area.setText(area.getText()+"\nInvoice No. :2989"); area.setText(area.getText()+"\n\n-----------------------------------------------------------------------------"); area.setText(area.getText()+"\nDescription Qty. Unit Price Amt."); area.setText(area.getText()+"\n-----------------------------------------------------------------------------"); if(apc > 0) area.setText(area.getText()+"\nApples "+apc+" 10 "+aps); if(wac>0) area.setText(area.getText()+"\nWatermelon "+wac+" 10 "+was); if(bac > 0) area.setText(area.getText()+"\nBanana "+bac+" 10 "+bas); if(grc>0) area.setText(area.getText()+"\nGrapes "+grc+" 10 "+grs); if(chc > 0) area.setText(area.getText()+"\nChickoo "+chc+" 10 "+chs); if(chec>0) area.setText(area.getText()+"\nCherry "+chec+" 10 "+ches); if(stc > 0) area.setText(area.getText()+"\nStrawberry "+stc+" 10 "+sts); if(mac>0) area.setText(area.getText()+"\nMango "+mac+" 10 "+mas); }//GEN-LAST:event_generateActionPerformed private void printActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printActionPerformed // TODO add your handling code here: try { area.print(); } catch(PrinterException e) { } }//GEN-LAST:event_printActionPerformed private void resetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetActionPerformed // TODO add your handling code here: //i am new change... name.setText(""); area.setText(""); apple.setText("0"); watermelon.setText("0"); banana.setText("0"); grapes.setText("0"); chickoo.setText("0"); cherry.setText("0"); strawberry.setText("0"); mango.setText("0"); }//GEN-LAST:event_resetActionPerformed /** * @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(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Counter.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Counter.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 Counter().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField apple; private javax.swing.JTextArea area; private javax.swing.JTextField banana; private javax.swing.JTextField cherry; private javax.swing.JTextField chickoo; private javax.swing.JButton generate; private javax.swing.JTextField grapes; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; 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.JScrollPane jScrollPane1; private javax.swing.JTextField mango; private javax.swing.JButton menu; private javax.swing.JTextField name; private javax.swing.JButton print; private javax.swing.JButton reset; private javax.swing.JTextField strawberry; private javax.swing.JTextField watermelon; // End of variables declaration//GEN-END:variables }
package edu.softwarica.MeetingAttendence.Model; public class Modelnotification { private String s_id, s_fname, s_lname, s_email, s_phone, r_id, r_fname, r_lname, r_email, r_phone, e_id, ename, edate, etime, elocation, edesc, eminatt, einvitatten, ethresmin; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } private String status; public String getList_id() { return list_id; } public void setList_id(String list_id) { this.list_id = list_id; } private String list_id; public String getS_id() { return s_id; } public void setS_id(String s_id) { this.s_id = s_id; } public String getS_fname() { return s_fname; } public void setS_fname(String s_fname) { this.s_fname = s_fname; } public String getS_lname() { return s_lname; } public void setS_lname(String s_lname) { this.s_lname = s_lname; } public String getS_email() { return s_email; } public void setS_email(String s_email) { this.s_email = s_email; } public String getS_phone() { return s_phone; } public void setS_phone(String s_phone) { this.s_phone = s_phone; } public String getR_id() { return r_id; } public void setR_id(String r_id) { this.r_id = r_id; } public String getR_fname() { return r_fname; } public void setR_fname(String r_fname) { this.r_fname = r_fname; } public String getR_lname() { return r_lname; } public void setR_lname(String r_lname) { this.r_lname = r_lname; } public String getR_email() { return r_email; } public void setR_email(String r_email) { this.r_email = r_email; } public String getR_phone() { return r_phone; } public void setR_phone(String r_phone) { this.r_phone = r_phone; } public String getE_id() { return e_id; } public void setE_id(String e_id) { this.e_id = e_id; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getEdate() { return edate; } public void setEdate(String edate) { this.edate = edate; } public String getEtime() { return etime; } public void setEtime(String etime) { this.etime = etime; } public String getElocation() { return elocation; } public void setElocation(String elocation) { this.elocation = elocation; } public String getEdesc() { return edesc; } public void setEdesc(String edesc) { this.edesc = edesc; } public String getEminatt() { return eminatt; } public void setEminatt(String eminatt) { this.eminatt = eminatt; } public String getEinvitatten() { return einvitatten; } public void setEinvitatten(String einvitatten) { this.einvitatten = einvitatten; } public String getEthresmin() { return ethresmin; } public void setEthresmin(String ethresmin) { this.ethresmin = ethresmin; } }
package ro.siit; public class Counter extends Thread{ private int step; private int limit; public Counter(int step, int limit){ this.step = step; this.limit = limit; } @Override public void run() { for(int i = 0; i< limit; i = i + step){ System.out.println("" + i + Thread.currentThread()); } } }
package com.amazon.opendistro.elasticsearch.performanceanalyzer.rca.util; import com.amazon.opendistro.elasticsearch.performanceanalyzer.reader.ClusterDetailsEventProcessor; import com.amazon.opendistro.elasticsearch.performanceanalyzer.reader.ClusterDetailsEventProcessorTestHelper; import com.google.common.collect.Lists; import java.util.Collections; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class ClusterUtilsTest { private static final String HOST = "127.0.0.1"; private static final String HOST2 = "127.0.0.2"; private static final ClusterDetailsEventProcessor.NodeDetails EMPTY_DETAILS = ClusterDetailsEventProcessorTestHelper.newNodeDetails("", "", false); @Before public void setup() { ClusterDetailsEventProcessor.setNodesDetails(Collections.singletonList(EMPTY_DETAILS)); } @Test public void testGetCurrentHostAddress() { Assert.assertEquals(ClusterUtils.EMPTY_STRING, ClusterUtils.getCurrentNodeHostAddress()); ClusterDetailsEventProcessor.setNodesDetails(Collections.singletonList( ClusterDetailsEventProcessorTestHelper.newNodeDetails(null, HOST, false) )); Assert.assertEquals(HOST, ClusterUtils.getCurrentNodeHostAddress()); } @Test public void testGetAllPeerHostAddresses() { // method should behave when fed an empty list of peers Assert.assertEquals(Collections.emptyList(), ClusterUtils.getAllPeerHostAddresses()); // method should not include the current node in the list of peers ClusterDetailsEventProcessor.setNodesDetails(Lists.newArrayList( ClusterDetailsEventProcessorTestHelper.newNodeDetails(null, HOST, false) )); Assert.assertEquals(Collections.emptyList(), ClusterUtils.getAllPeerHostAddresses()); // method should return the appropriate peers when peers exist ClusterDetailsEventProcessor.setNodesDetails(Lists.newArrayList( ClusterDetailsEventProcessorTestHelper.newNodeDetails(null, HOST, false), ClusterDetailsEventProcessorTestHelper.newNodeDetails(null, HOST2, false) )); Assert.assertEquals(Collections.singletonList(HOST2), ClusterUtils.getAllPeerHostAddresses()); } @Test public void testIsHostAddressInCluster() { // Explicitly reset ClusterDetailsEventProcessor. Test fails on mac otherwise. ClusterDetailsEventProcessor.setNodesDetails(Collections.singletonList(EMPTY_DETAILS)); // method should return false when there are no peers Assert.assertFalse(ClusterUtils.isHostAddressInCluster(HOST)); // method should properly recognize which hosts are peers and which aren't ClusterDetailsEventProcessor.setNodesDetails(Lists.newArrayList( ClusterDetailsEventProcessorTestHelper.newNodeDetails(null, HOST, false) )); Assert.assertTrue(ClusterUtils.isHostAddressInCluster(HOST)); Assert.assertFalse(ClusterUtils.isHostAddressInCluster(HOST2)); } }
import base.TestBase; import com.codeborne.selenide.testng.BrowserPerTest; import com.codeborne.selenide.testng.ScreenShooter; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Listeners; import org.testng.annotations.Test; import pages.HeaderPage; import ru.yandex.qatools.allure.annotations.Features; import ru.yandex.qatools.allure.annotations.Stories; @Listeners({ScreenShooter.class, BrowserPerTest.class}) public class HomeOnlinerTest extends TestBase { @BeforeMethod @Override public void setup() { super.setup(); } @Features("Home page") @Stories("Verify ") @Test() public void checkLinksOpened() { } }
import java.util.Scanner; public class BMICalculator { public static void main( String[] args ) { Scanner keyboard = new Scanner(System.in); double m, kg, bmi, f, i, lbs, inches; System.out.print( "Your height (feet only): " ); f = keyboard.nextDouble(); System.out.print( "Your height (inches): " ); i = keyboard.nextDouble(); System.out.print( "Your weight in pounds: " ); lbs = keyboard.nextDouble(); inches = (f*12) + i; m = inches*0.0254; kg = lbs*0.453592; bmi = kg / (m*m); System.out.println( "Your BMI is " + bmi ); } }
package main; import java.awt.Color; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.Image; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.net.MalformedURLException; import java.net.URL; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Executors; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.BoxLayout; import javax.swing.JLabel; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import java.awt.FlowLayout; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.Component; import javax.swing.SwingConstants; public class Inw extends JPanel { String fname; String lname; String fbname; int LP_full; int LP_current; int MP_full; int MP_current; int maxDeck; String fb_id; ImageIcon profile; //BufferedImage image; int user_ID; public int[] all_IC; public int[] deck; private JLabel picLabel; private JLabel nameLabel; private JLabel LP; private JLabel MP; /**@deprecated * @param fname * @param lname * @param LP * @param MP * @param maxDeck * @param fb_id * @param user_ID * @param image * @param fbname */ public Inw(String fname, String lname, int LP, int MP, int maxDeck, String fb_id, int user_ID, BufferedImage image, String fbname) { this.fname = fname; this.lname = lname; this.LP_full = LP; this.MP_full = MP; LP_current = LP_full; MP_current = MP_full; this.maxDeck = maxDeck; this.fb_id = fb_id; this.user_ID = user_ID; // this.image = image; this.fbname = fbname; // initGUI(); } public static void main(String[] args) { // TESTING : getting all cards from user; // CardData.saveAllCardsToLocal(); JFrame frame = new JFrame(); frame.setSize(700, 700); frame.setVisible(true); frame.getContentPane().setLayout(new GridLayout(4, 5)); Inw a = new Inw( "{\"cv_uid\":\"517\",\"fb_id\":\"100000038984537\",\"firstname_en\":\"Assanee\",\"lastname_en\":\"Sukatham\",\"full_lp\":\"40\",\"full_mp\":\"5\",\"max_deck_size\":\"20\"}"); Card c = new Card(1, true, a); frame.getContentPane().add(a); System.out.println(a.useMP(3)); JButton j = new JButton("ADD"); frame.getContentPane().add(j); } public Inw(String fname, String lname, int LP, int MP, int maxDeck, String fb_id, int user_ID) { this.fname = fname; this.lname = lname; this.LP_full = LP; this.MP_full = MP; LP_current = LP_full; MP_current = MP_full; this.maxDeck = maxDeck; this.fb_id = fb_id; this.user_ID = user_ID; initGUI(); } /** * create Inw with String representing the individual Inw JSON data from * http://128.199.235.83/icw/?q=icw/service/opponent Example String value: * "{\"cv_uid\":\"517\",\"fb_id\":\"100000038984537\",\"firstname_en\":\"Assanee\",\"lastname_en\":\"Sukatham\",\"full_lp\":\"40\",\"full_mp\":\"5\",\"max_deck_size\":\"20\"}" * * @param JSONString */ public Inw(String JSONString) { JsonObject j = (JsonObject) new JsonParser().parse(JSONString); this.fb_id = j.get("fb_id").getAsString(); this.user_ID = j.get("cv_uid").getAsInt(); this.fname = j.get("firstname_en").getAsString(); this.lname = j.get("lastname_en").getAsString(); this.LP_full = j.get("full_lp").getAsInt(); this.MP_full = j.get("full_mp").getAsInt(); this.maxDeck = j.get("max_deck_size").getAsInt(); LP_current = LP_full; MP_current = MP_full; initGUI(); // System.out.println("create inw from JSONString successful"); } /** * get Inw data from only JsonObject from * http://128.199.235.83/icw/?q=icw/service/opponent * * @param j * - Individual JsonObject extracted from the "data" JsonObject * @wbp.parser.constructor * */ public Inw(JsonObject j) { this.fb_id = j.get("fb_id").getAsString(); this.user_ID = j.get("cv_uid").getAsInt(); this.fname = j.get("firstname_en").getAsString(); this.lname = j.get("lastname_en").getAsString(); this.LP_full = j.get("full_lp").getAsInt(); this.MP_full = j.get("full_mp").getAsInt(); this.maxDeck = j.get("max_deck_size").getAsInt(); LP_current = LP_full; MP_current = MP_full; initGUI(); } private void initGUI() { try { // image = ImageIO.read(new // URL("https://graph.facebook.com/"+fb_id+"/picture")); profile = new ImageIcon(ImageIO.read(new URL( "https://graph.facebook.com/" + fb_id + "/picture?width=200&height=200"))); } catch (IOException e) { e.printStackTrace(); } setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); picLabel = new JLabel(profile); picLabel.setForeground(new Color(0, 0, 0)); picLabel.setAlignmentX(Component.CENTER_ALIGNMENT); // picLabel.setText(fname + " " + lname + " LP: " + LP_current + " MP: " // + MP_current); add(picLabel); nameLabel = new JLabel(fname+" "+lname); nameLabel.setHorizontalAlignment(SwingConstants.CENTER); nameLabel.setAlignmentX(Component.CENTER_ALIGNMENT); add(nameLabel); LP = new JLabel("LP: "+LP_current); LP.setHorizontalAlignment(SwingConstants.CENTER); LP.setAlignmentX(Component.CENTER_ALIGNMENT); add(LP); MP = new JLabel("MP: "+MP_current); MP.setHorizontalAlignment(SwingConstants.CENTER); MP.setAlignmentX(Component.CENTER_ALIGNMENT); add(MP); } /** * @return An array of all opponent from * http://128.199.235.83/icw/?q=icw/service/opponent */ public static Inw[] getOpponent() { JsonArray opponent; while (true) { Gson gs; InputStream is; String url = "http://128.199.235.83/icw/?q=icw/service/opponent"; // INTERT // YOUR // ID // HERE JsonObject job = null; try { is = new URL(url).openStream(); gs = new Gson(); job = gs.fromJson(new InputStreamReader(is), JsonObject.class); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { System.err.print("can't connect, retrying"); continue; } opponent = new Gson().fromJson(job.get("data"), JsonArray.class); break; } Inw[] all = new Inw[opponent.size()]; int count = 0; for (JsonElement j : opponent) { all[count] = new Inw(j.getAsJsonObject()); count++; } return all; } public void getAllIC() { } public String toString() { return "[FIRSTNAME: " + fname + ", LASTNAME: " + lname + ", LP: " + LP_full + ", MP: " + MP_full + ", MAXDECK: " + ",IMAGE: " + profile.toString() + "]"; } public int getID() { return user_ID; } public String getName() { return fname; } /* public static String getAll() { return fname + lname + "MP" + "LP_full" + "MP_full" + "maxDeck" + fb_id + "user_ID"; } */ /** * Check if the character has enough MP to perform action, if yes then this * method will automatically decrease the MP of character by that amount * * @param mp_cost * - the MP cost of the SA or Spell * @return whether or not the character have enough MP to cover the MP cost */ public boolean useMP(int mp_cost) { if (MP_current >= mp_cost) { MP_current = MP_current - mp_cost; // System.out.println("MP used: "+mp_cost+" MP left"+MP_current); updateGUI(); return true; } else return false; } public void updateGUI() { LP.setText("LP: "+LP_current); MP.setText("MP: "+MP_current); validate(); } /** * Fetch this Inw's deck data from the server * * @return true if there is deck AND more than 10 cards in the deck */ public boolean addDeck() { Gson gs; InputStream is; String url = "http://128.199.235.83/icw/?q=icw/service/get_deck&user=" + user_ID; // INTERT YOUR ID HERE JsonObject job = null; while (true) { try { is = new URL(url).openStream(); gs = new Gson(); job = gs.fromJson(new InputStreamReader(is), JsonObject.class); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { System.err.println("Cannot connect, trying again..."); continue; } // Type listType = new TypeToken<List<Integer>>(){}.getType(); System.out.println(job); if (job.get("data").isJsonNull()) { System.err.println("User hasn't save his/her deck yet!"); return false; } JsonArray ja = job.get("data").getAsJsonArray(); if (ja.size() < 10) return false; deck = new int[ja.size()]; int count = 0; for (JsonElement je : ja) { deck[count] = je.getAsInt(); count++; } break; } return true; } public boolean attack(int DMG) { if (DMG < 0) { effectColor(Color.GREEN); } else effectColor(Color.RED); this.LP_current -= DMG; updateGUI(); System.out.println("Inw received "+DMG+ " damages LP is now: "+LP_current); if(DMG>=0)Battlefield.notify.append("Inw received "+DMG+ " damages. LP is now: "+LP_current+"\n"); else Battlefield.notify.append("Inw received "+(-DMG)+ " health. LP is now: "+LP_current+"\n"); return LP_current<=0; } public void restoreMP() { MP_current = MP_full; updateGUI(); } public void effectColor(final Color c) { // Executors.newSingleThreadExecutor().execute // SwingUtilities.invokeLater Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); int alpha = 0; Graphics gr = Inw.this.getGraphics(); if (gr == null) return; alpha = 255; while (alpha > 0) { gr.setColor(new Color(r, g, b, alpha)); gr.fillRect(0, 0, getWidth(), getHeight()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } alpha -= 26; // repaint(); } // repaint(); } }); } }
package com.example.demo.sendmail.domain.model.validate; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; @Constraint(validatedBy = RequestTypeValidator.class) @Target({ ElementType.METHOD, ElementType.FIELD }) @Documented @Retention(RetentionPolicy.RUNTIME) public @interface SendMailType { String message() default "RequestType is invalid."; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
package com.webcloud.define; import com.webcloud.R; /** * 四种模板风格。 * * @author bangyue * @version [版本号, 2014-1-16] * @see [相关类/方法] * @since [产品/模块版本] */ public class ModelStyle { public static final String MODELSTYLE = "modelstyle"; public static final String MODEL_METRO = "metro"; public static final String MODEL_GRIDVIEW = "gridview"; public static final String MODEL_TAB = "tab"; public static final String MODEL_SLIDEMENU = "slidemenu"; public static int theme; public static int[] GRIDVIEW_BG_ID = new int[]{R.drawable.g1,R.drawable.g2,R.drawable.g3,R.drawable.g4,R.drawable.g5,R.drawable.g6,R.drawable.g7,R.drawable.g8,R.drawable.g9}; }
package rt; import javax.vecmath.Tuple3f; import javax.vecmath.Vector3f; /** * Axis aligned finite 3D BoundingBox * * @author Florian */ public class BoundingBox { float minx; float maxx; float miny; float maxy; float minz; float maxz; /** * Construct BoundingBox from minimal and maximal axis values (boundaries on axes). * Upper and lower values are automatically swapped if lower > upper. Therefore inputs with lower > upper and upper > lower are equally valid. * * @param minx lower boundary on x-axis * @param maxx upper boundary on x-axis * @param miny lower boundary on y-axis * @param maxy upper boundary on y-axis * @param minz lower boundary on z-axis * @param maxz upper boundary on z-axis */ public BoundingBox(float minx, float maxx, float miny, float maxy, float minz, float maxz) { if(minx < maxx) { this.minx = minx; this.maxx = maxx; }else { this.minx = maxx; this.maxx = minx; } if(miny < maxy) { this.miny = miny; this.maxy = maxy; }else { this.miny = maxy; this.maxy = miny; } if(minz < maxz) { this.minz = minz; this.maxz = maxz; }else { this.minz = maxz; this.maxz = minz; } } /** * Construct BoundingBox from its central vector and its uniform size a * (height = width = depth = 2*a) * p inside BoundingBox <=> maxnorm(p - center) < a * * @param center central vector * @param a distance from bounds to central vector */ public BoundingBox(Vector3f center, float a) { minx = center.x - a; maxx = center.x + a; miny = center.y - a; maxy = center.y + a; minz = center.z - a; maxz = center.z + a; } /** * Construct BoundingBox from central vector and its height, width and depth. * * @param center central vector * @param w width (x-axis aligned) * @param h height (y-axis aligned) * @param d depth (z-axis aligned) */ public BoundingBox(Tuple3f center, float w, float h, float d) { minx = center.x - w/2.0f; maxx = center.x + w/2.0f; miny = center.y - h/2.0f; maxy = center.y + h/2.0f; minz = center.z - d/2.0f; maxz = center.z + d/2.0f; } /** * Construct BoundingBox from two diagonally opposite corner vectors of the BoundnigBox * * @param a first corner vector * @param b second corner vector */ public BoundingBox(Tuple3f a, Tuple3f b) { minx = Math.min(a.x, b.x); maxx = Math.max(a.x, b.x); miny = Math.min(a.y, b.y); maxy = Math.max(a.y, b.y); minz = Math.min(a.z, b.z); maxz = Math.max(a.z, b.z); } /** * Create identical copy of BoundingBox b * * @param b BoundingBox to be copied */ public BoundingBox(BoundingBox b) { minx = b.minx; maxx = b.maxx; miny = b.miny; maxy = b.maxy; minz = b.minz; maxz = b.maxz; } /** * Extend this BoundingBox, so that it contains the BoundingBox b too. * * @param b BoundingBox to be included * @return this BoundingBox(extended) or null if extension is not possible (e.g. b = null) */ public BoundingBox combinationWith(BoundingBox b) { if(b == null) { return null; } minx = Math.min(minx, b.minx); maxx = Math.max(maxx, b.maxx); miny = Math.min(miny, b.miny); maxy = Math.max(maxy, b.maxy); minz = Math.min(minz, b.minz); maxz = Math.max(maxz, b.maxz); return this; } /** * Intersect this BoundingBox with another, resulting in a smaller BoundingBox that is inside of both * * @param b BoundingBox to be intersected with * @return this BoundingBox(intersection) or null if intersection is empty */ public BoundingBox intersectionWith(BoundingBox b) { if(!intersect(b)) { return null; } minx = Math.max(minx, b.minx); maxx = Math.min(maxx, b.maxx); miny = Math.max(miny, b.miny); maxy = Math.min(maxy, b.maxy); minz = Math.max(minz, b.minz); maxz = Math.min(maxz, b.maxz); return this; } /** * Test if this BoundingBox intersects with other BoundingBox b * * @param b BoundingBox to be intersected * @return true if the boxes intersect */ public boolean intersect(BoundingBox b) { if(b == null) { return false; } return ((minx < b.maxx && b.minx < maxx)&&(miny < b.maxy && b.miny < maxy)&&(minz < b.maxz && b.minz < maxz)); } /** * fast intersection test of the BoundingBox and a {@link Ray} * * @param r Ray to be intersected with * @return parameter of intersection point (>0) or -1 if no intersection */ public float intersect(Ray r) { float n1 = (minx - r.origin.x)/r.direction.x; float n2 = (maxx - r.origin.x)/r.direction.x; if(n1 > n2) { float temp = n1; n1 = n2; n2 = temp; } float n3 = (miny - r.origin.y)/r.direction.y; float n4 = (maxy - r.origin.y)/r.direction.y; if(n3 > n4) { float temp = n3; n3 = n4; n4 = temp; } n1 = Math.max(n1, n3); n2 = Math.min(n2, n4); n3 = (minz - r.origin.z)/r.direction.z; n4 = (maxz - r.origin.z)/r.direction.z; if(n3 > n4) { float temp = n3; n3 = n4; n4 = temp; } n1 = Math.max(n1, n3); n2 = Math.min(n2, n4); if(n1 > n2) { return Float.NEGATIVE_INFINITY; // no intersection } if(n1 > 0) // intersection { return n1; } return 0; // ray begins inside } public float getMinx() { return minx; } public float getMaxx() { return maxx; } public float getMiny() { return miny; } public float getMaxy() { return maxy; } public float getMinz() { return minz; } public float getMaxz() { return maxz; } }
package ga.islandcrawl.form; import java.util.Random; import ga.islandcrawl.draw.Bush; import ga.islandcrawl.draw.Oval; import ga.islandcrawl.draw.Shape; import ga.islandcrawl.draw.Triangle; import ga.islandcrawl.other.M; /** * Created by Ga on 7/10/2015. */ public class BushTree extends Form { private Random rand; public float size, branchWidth; public int petals; public int depth; public float[] color; public float[] colorBase; public boolean tall; public float[] branchSize; Shape base; public Shape[] branch; Bush[] leaf; public BushTree(String seed) { super(); rand = new Random(Integer.parseInt(seed)); create(rand); } public void removeBranch(){ Shape[] t = new Shape[branch.length-1]; float[] t2 = new float[branch.length-1]; organs.remove(branch[branch.length-1]); for (int i=0;i<t.length;i++){ t[i] = branch[i]; t2[i] = branchSize[i]; } branch = t; branchSize = t2; } public void create(Random rnd){ leaf = new Bush[3]; size = .35f+(rnd.nextFloat()*.15f); petals = rnd.nextInt(14)+4; depth = rnd.nextInt(6)+6; tall = rnd.nextInt(2) != 0; branch = new Shape[rnd.nextInt(5)]; branchSize = new float[branch.length]; branchWidth = (rnd.nextFloat()*.04f)+.02f; for (int i=0;i<branch.length;i++){ branchSize[i] = (rnd.nextFloat()*.25f)+.1f; } color = new float[]{ rnd.nextFloat()*.8f, (rnd.nextFloat()*.7f)+.25f, rnd.nextFloat()*.4f, (rnd.nextFloat()*.35f)+.6f }; colorBase = new float[]{ rnd.nextFloat()*.6f+.3f, (rnd.nextFloat()*.5f)+.2f, rnd.nextFloat()*.4f, 1 }; init(); } public void init(){ organs.add(base = new Oval(size / 5, size / 5, new float[]{.5f, .4f, .1f, 1})); for (int i=0;i<branch.length;i++) { organs.add(branch[i] = new Triangle(branchSize[i],-branchWidth,branchWidth, new float[]{.5f, .4f, .1f, 1})); branch[i].offsetR.x = branchSize[i]/2; branch[i].rotate(M.rand(0,359)); } organs.add(leaf[0] = new Bush(size, 1, petals, depth, new float[]{color[0], color[1], color[2], Math.max(0, color[3] - .2f)})); organs.add(leaf[1] = new Bush(size-.1f,1,petals,depth,new float[]{color[0]+.02f,color[1]+.02f,color[2]+.02f,Math.max(0, color[3]-.1f)})); if (tall) organs.add(leaf[2] = new Bush(size - .2f, 1, petals, depth, new float[]{color[0] + .05f, color[1] + .05f, color[2] + .05f, Math.max(0, color[3])})); for (int i = 0; i < (tall ? 3 : 2); i++){ leaf[i].rotate(15 * i); } } }
package com.data.rhis2; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.database.Cursor; import android.graphics.Color; import android.location.Location; import android.os.Bundle; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Spinner; import android.widget.TableLayout; import android.widget.TextView; import android.widget.TimePicker; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import Common.Connection; import Common.Global; /** * Created by Nisan on 8/9/2016. */ public class FpaWorkPlaningViewFPINotAproved extends Activity { Calendar calendar; boolean netwoekAvailable = false; Location currentLocation; double currentLatitude, currentLongitude; Location currentLocationNet; double currentLatitudeNet, currentLongitudeNet; //Disabled Back/Home key //-------------------------------------------------------------------------------------------------- @Override public boolean onKeyDown(int iKeyCode, KeyEvent event) { if (iKeyCode == KeyEvent.KEYCODE_BACK || iKeyCode == KeyEvent.KEYCODE_HOME) { return false; } else { return true; } } //Top menu //-------------------------------------------------------------------------------------------------- public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mnuclose, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { AlertDialog.Builder adb = new AlertDialog.Builder(FpaWorkPlaningViewFPINotAproved.this); switch (item.getItemId()) { case R.id.menuClose: adb.setTitle("Close"); adb.setMessage("আপনি কি এই ফর্ম থেকে বের হতে চান?"); adb.setNegativeButton("না", null); adb.setPositiveButton("হ্যাঁ", new AlertDialog.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); adb.show(); return true; } return false; } String VariableID; private int hour; private int minute; private int mDay; private int mMonth; private int mYear; static final int DATE_DIALOG = 1; static final int TIME_DIALOG = 2; public static String[] namesOfDays = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"}; Connection C; Global g; SimpleAdapter dataAdapter; ArrayList<String> FPAValue = new ArrayList<String>(); ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>(); private String TableName; private String TableNameDetail; //public static String workplanId1; LinearLayout secS10; LinearLayout secSlNo; TextView VlblSlNo; LinearLayout secFPIPMonth; TextView VlblFPIPMonth; Spinner spnFPIPMonth; TextView lblHS10; LinearLayout secReq; TextView VlblReqName; // TextView txtReqName; Spinner spnfpaCode; LinearLayout secReqToCode; TextView VlblReqToCode; TextView txtFpiWarea; EditText txtRemarks; LinearLayout secfpaVill; TextView VlblfpaVill; TextView txtfpaVill; LinearLayout secRemarks; LinearLayout secListRow1; Spinner spnVillage1; Button cmdSync; Button cmdDownload; Button cmdApproved; Button cmdNotApproved; Button cmdRequest; String StartTime; String DeviceNo; ListView list; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { setContentView(R.layout.fpaworkplaningviewnotaproved); C = new Connection(this); g = Global.getInstance(); StartTime = g.CurrentTime24(); list = (ListView) findViewById(R.id.lstData); TableName = "workPlanMaster"; TableNameDetail = "workPlanDetail"; secListRow1 = (LinearLayout) findViewById(R.id.secListRow1); secRemarks = (LinearLayout) findViewById(R.id.secRemarks); lblHS10 = (TextView) findViewById(R.id.lblHS10); secS10 = (LinearLayout) findViewById(R.id.secS10); secSlNo = (LinearLayout) findViewById(R.id.secSlNo); VlblSlNo = (TextView) findViewById(R.id.VlblSlNo); lblHS10.setText("পরিবার কল্যাণ সহকারীর মাসিক অগ্রিম কর্মসূচী অননুমোদিত"); secRemarks.setVisibility(View.GONE); txtRemarks = (EditText) findViewById(R.id.txtRemarks); cmdSync = (Button) findViewById(R.id.cmdSync); cmdDownload = (Button) findViewById(R.id.cmdDownload); cmdApproved = (Button) findViewById(R.id.cmdApproved); cmdNotApproved = (Button) findViewById(R.id.cmdNotApproved); cmdRequest = (Button) findViewById(R.id.cmdRequest); secFPIPMonth = (LinearLayout) findViewById(R.id.secFPIPMonth); VlblFPIPMonth = (TextView) findViewById(R.id.VlblFPIPMonth); spnFPIPMonth = (Spinner) findViewById(R.id.spnFPIPMonth); // spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT strftime('%Y', date('now')) ||','||mName||':-'||substr('0' ||id, -2, 2) as ym from month where id <=(SELECT strftime('%m','now')+1) order by id Desc")); //spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT '99-- সিলেক্ট মাস-' AS ym Union SELECT substr('0' ||id, -2, 2)||'-'||mName||','||strftime('%Y', date('now')) as ym from month where id <=(SELECT strftime('%m','now')+1) order by ym Desc")); String Month=C.ReturnSingleValue("select strftime( '%m', 'now' ) as m"); if(Month.equals("12")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT '99-- সিলেক্ট মাস-' AS ym\n" + " \n" + "UNION SELECT ( CASE WHEN id=strftime( '%m', 'now' ) then '01-January,'||cast(strftime( '%Y', date( 'now' ) )+1 as int) else '' END ) AS ym FROM month where id=12\n" + " Union\n" + "\n" + "\n" + "SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || strftime( '%Y', date( 'now' ) ) AS ym\n" + " FROM month\n" + " WHERE id<>1 and id<>2 and id<>3 and id<>4 and id<>5 and id<>6 and id <=( \n" + " SELECT strftime( '%m', 'now' ) + 1 \n" + " ) \n" + " \n" + " ORDER BY ym DESC")); } else if(Month.equals("11")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT substr('0' ||id, -2, 2)||'-'||mName||','||strftime('%Y', date('now')) as ym from month where id<>1 and id<>2 and id<>3 and id<>4 and id<>5 and id <=(SELECT strftime('%m','now')+1) order by id Desc")); } else if(Month.equals("10")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT substr('0' ||id, -2, 2)||'-'||mName||','||strftime('%Y', date('now')) as ym from month where id<>1 and id<>2 and id<>3 and id<>4 and id <=(SELECT strftime('%m','now')+1) order by id Desc")); } else if(Month.equals("09")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT substr('0' ||id, -2, 2)||'-'||mName||','||strftime('%Y', date('now')) as ym from month where id<>1 and id<>2 and id<>3 and id <=(SELECT strftime('%m','now')+1) order by id Desc")); } else if(Month.equals("08")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT substr('0' ||id, -2, 2)||'-'||mName||','||strftime('%Y', date('now')) as ym from month where id<>1 and id<>2 and id <=(SELECT strftime('%m','now')+1) order by id Desc")); } else if(Month.equals("07")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT substr('0' ||id, -2, 2)||'-'||mName||','||strftime('%Y', date('now')) as ym from month where id<>1 and id <=(SELECT strftime('%m','now')+1) order by id Desc")); } else if(Month.equals("06")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT substr('0' ||id, -2, 2)||'-'||mName||','||strftime('%Y', date('now')) as ym from month where id <=(SELECT strftime('%m','now')+1) order by id Desc")); } else if(Month.equals("05")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT '99-- সিলেক্ট মাস-' AS ym\n" + " \n" + " Union SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || cast(strftime( '%Y', date( 'now' ) )-1 as int) AS ym FROM month WHERE id >=11\n" + " Union\n" + "\n" + "\n" + "SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || strftime( '%Y', date( 'now' ) ) AS ym\n" + " FROM month\n" + " WHERE id <=( \n" + " SELECT strftime( '%m', 'now' ) + 1 \n" + " ) \n" + " \n" + " ORDER BY ym DESC")); } else if(Month.equals("04")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT '99-- সিলেক্ট মাস-' AS ym\n" + " \n" + " Union SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || cast(strftime( '%Y', date( 'now' ) )-1 as int) AS ym FROM month WHERE id >=10\n" + " Union\n" + "\n" + "\n" + "SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || strftime( '%Y', date( 'now' ) ) AS ym\n" + " FROM month\n" + " WHERE id <=( \n" + " SELECT strftime( '%m', 'now' ) + 1 \n" + " ) \n" + " \n" + " ORDER BY ym DESC")); } else if(Month.equals("03")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT '99-- সিলেক্ট মাস-' AS ym\n" + " \n" + "Union SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || cast(strftime( '%Y', date( 'now' ) )-1 as int) AS ym FROM month WHERE id >=9\n" + " Union\n" + "\n" + "\n" + "SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || strftime( '%Y', date( 'now' ) ) AS ym\n" + " FROM month\n" + " WHERE id <=( \n" + " SELECT strftime( '%m', 'now' ) + 1 \n" + " ) \n" + " \n" + " ORDER BY ym DESC")); } else if(Month.equals("02")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT '99-- সিলেক্ট মাস-' AS ym\n" + " \n" + " Union SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || cast(strftime( '%Y', date( 'now' ) )-1 as int) AS ym FROM month WHERE id >=8\n" + " Union\n" + "\n" + "\n" + "SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || strftime( '%Y', date( 'now' ) ) AS ym\n" + " FROM month\n" + " WHERE id <=( \n" + " SELECT strftime( '%m', 'now' ) + 1 \n" + " ) \n" + " \n" + " ORDER BY ym DESC")); } else if(Month.equals("01")) { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT '99-- সিলেক্ট মাস-' AS ym\n" + " \n" + "Union SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || cast(strftime( '%Y', date( 'now' ) )-1 as int) AS ym FROM month WHERE id >=7\n" + " Union\n" + "\n" + "\n" + "SELECT substr( '0' || id, -2, 2 ) || '-' || mName || ',' || strftime( '%Y', date( 'now' ) ) AS ym\n" + " FROM month\n" + " WHERE id <=( \n" + " SELECT strftime( '%m', 'now' ) + 1 \n" + " ) \n" + " \n" + " ORDER BY ym DESC")); } else { spnFPIPMonth.setAdapter(C.getArrayAdapterMultiline("SELECT substr('0' ||id, -2, 2)||'-'||mName||','||strftime('%Y', date('now')) as ym from month where id <=(SELECT strftime('%m','now')+1) order by id Desc")); } secReq = (LinearLayout) findViewById(R.id.secReq); VlblReqName = (TextView) findViewById(R.id.VlblReqName); spnfpaCode = (Spinner) findViewById(R.id.spnfpaCode); secfpaVill = (LinearLayout) findViewById(R.id.secfpaVill); VlblfpaVill = (TextView) findViewById(R.id.VlblfpaVill); txtfpaVill = (TextView) findViewById(R.id.txtfpaVill); // spnfpaVill=(Spinner) findViewById(R.id.spnfpaVill); // spnfpaCode.setAdapter(C.getArrayAdapterMultiline("Select ProvCode||'-'||ProvName from ProviderDB where ProvType ='3'")); spnfpaCode.setAdapter(C.getArrayAdapterMultiline("Select substr('0' ||ProvCode, -6, 6)||'-'||ProvName from ProviderDB where ProvType ='3'")); txtFpiWarea = (TextView) findViewById(R.id.txtFpiWarea); spnFPIPMonth.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { buttonStatus(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); spnfpaCode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { buttonStatus(); } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); // txtFpiWarea.setText(g.getFWAUnit()); DisplaySearch(true); txtFpiWarea.setText(ProvArea("3", Global.Left(spnfpaCode.getSelectedItem().toString(), 6))); secReqToCode = (LinearLayout) findViewById(R.id.secReqToCode); VlblReqToCode = (TextView) findViewById(R.id.VlblReqToCode); DataSearch(Global.Right(spnFPIPMonth.getSelectedItem().toString(), 4) + "-" + Global.Left(spnFPIPMonth.getSelectedItem().toString(), 2), Global.Left(spnfpaCode.getSelectedItem().toString(), 6)); secListRow1.setVisibility(View.GONE); cmdSync.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //Check for Internet connectivity //******************************************************************************* boolean netwoekAvailable = false; if (Connection.haveNetworkConnection(FpaWorkPlaningViewFPINotAproved.this)) { netwoekAvailable = true; // UploadFWA(); final ProgressDialog progDailog = ProgressDialog.show( FpaWorkPlaningViewFPINotAproved.this, "", "অপেক্ষা করুন ...", true); new Thread() { public void run() { UploadFWA(); progDailog.dismiss(); runOnUiThread(new Runnable() { @Override public void run() { buttonStatus(); } }); } }.start(); } else { netwoekAvailable = false; Connection.MessageBox(FpaWorkPlaningViewFPINotAproved.this, "Internet connection is not available."); // return true; } } }); } catch (Exception e) { Connection.MessageBox(FpaWorkPlaningViewFPINotAproved.this, e.getMessage()); return; } } private void buttonStatus() { String val = Global.Left(spnfpaCode.getSelectedItem().toString(), 6); if (val.length() >= 0) { txtFpiWarea.setText(ProvArea("3", Global.Left(spnfpaCode.getSelectedItem().toString(), 6))); txtFpiWarea.setEnabled(false); txtfpaVill.setText(ProvVill(Global.Left(spnfpaCode.getSelectedItem().toString(), 6))); DataSearch(Global.Right(spnFPIPMonth.getSelectedItem().toString(), 4) + "-" + Global.Left(spnFPIPMonth.getSelectedItem().toString(), 2), Global.Left(spnfpaCode.getSelectedItem().toString(), 6)); if (val.equals("99")) { cmdSync.setVisibility(View.GONE); secListRow1.setVisibility(View.GONE); secRemarks.setVisibility(View.GONE); } else if (!C.Existence("Select * FROM workPlanMaster A INNER JOIN workPlanDetail B ON A.workPlanId = B.workPlanId WHERE A.status='3' and B.providerId= '" + Global.Left(spnfpaCode.getSelectedItem().toString(), 6) + "' AND substr( B.workPlanDate, 1, 7 )='" + Global.Right(spnFPIPMonth.getSelectedItem().toString(), 4) + "-" + Global.Left(spnFPIPMonth.getSelectedItem().toString(), 2) + "'")) { cmdSync.setVisibility(View.GONE); secListRow1.setVisibility(View.GONE); secRemarks.setVisibility(View.GONE); } else if (C.Existence("Select * FROM workPlanMaster A INNER JOIN workPlanDetail B ON A.workPlanId = B.workPlanId WHERE A.status='3' and B.providerId= '" + Global.Left(spnfpaCode.getSelectedItem().toString(), 6) + "' AND substr( B.workPlanDate, 1, 7 )='" + Global.Right(spnFPIPMonth.getSelectedItem().toString(), 4) + "-" + Global.Left(spnFPIPMonth.getSelectedItem().toString(), 2) + "'")) { cmdSync.setVisibility(View.VISIBLE); secListRow1.setVisibility(View.VISIBLE); secRemarks.setVisibility(View.GONE); } } } private void UploadFWA() { String TableName = ""; String VariableList = ""; // message = "Uploading workPlanMaster"; // jumpTime += 1; // progressHandler.sendMessage(progressHandler.obtainMessage()); TableName = "workPlanMaster"; VariableList = "workPlanId,workAreaId,providerId,month,status,systemEntryDate,modifyDate,upload"; C.UploadJSON(TableName, VariableList, "workPlanId, providerId, month"); // message = "Uploading workPlanDetail"; // jumpTime += 1; // progressHandler.sendMessage(progressHandler.obtainMessage()); TableName = "workPlanDetail"; VariableList = "workPlanId,item,workPlanDate,unitNo,village,elcoFrom,elcoTo,leaveType,providerId,systemEntryDate,modifyDate,otherDec,remarks,upload,status"; C.UploadJSON(TableName, VariableList, "workPlanId, item, workPlanDate, providerId"); // DeleteChangeUPTables(); } private String ProvArea(String ProvType, String ProvCode) { String SQL = ""; if (ProvType.equals("2")) SQL = "select distinct ward from ProviderArea WHERE Cast(provCode AS INT) = '" + ProvCode + "'"; //SQL="select distinct p.ward||' সাব ব্লক :'||p.Block||'-'||u.BNameBan from ProviderArea p,HABlock u WHERE u.BCode=p.block and p.provCode= '"+ ProvCode +"'"; else if (ProvType.equals("3")) //SQL = "select distinct fwaunit from ProviderArea WHERE provCode = '"+ ProvCode +"'"; SQL = "select distinct p.fwaunit||'-'||u.UNameBan from ProviderArea p,FWAUnit u where u.UCode=p.fwaunit and Cast(p.provCode AS INT) ='" + ProvCode + "'"; Cursor cur = C.ReadData(SQL); String retValue = ""; cur.moveToFirst(); while (!cur.isAfterLast()) { retValue = retValue.length() > 0 ? retValue + ", " + cur.getString(0) : cur.getString(0); cur.moveToNext(); } cur.close(); return retValue; } private String ProvVill(String ProvCode) { String SQL = ""; // SQL="select MOUZAID||VILLAGEID||'-'||VILLAGENAME as VILLAGENAME from Village where mouzaid||VILLAGEID in (Select mouzaid||VILLAGEID from ProviderArea where ProvCode ='"+ ProvCode +"'"; SQL = " select MOUZAID||VILLAGEID||'-'||VILLAGENAME as VILLAGENAME from Village where mouzaid||VILLAGEID in (Select mouzaid||VILLAGEID from ProviderArea where Cast(ProvCode AS INT)='" + ProvCode + "')"; Cursor cur = C.ReadData(SQL); String retValue = ""; cur.moveToFirst(); while (!cur.isAfterLast()) { retValue = retValue.length() > 0 ? retValue + ", " + cur.getString(0) : cur.getString(0); cur.moveToNext(); } cur.close(); return retValue; } private void DisplaySearch(boolean willdisplaysearch) { getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); ((ImageButton) findViewById(R.id.btnMinus)).setVisibility(View.GONE); ((ImageButton) findViewById(R.id.btnPlus)).setVisibility(View.VISIBLE); ((LinearLayout) findViewById(R.id.seclblSearchGroup)).setVisibility(View.GONE); ((ImageButton) findViewById(R.id.btnPlus)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { ((LinearLayout) findViewById(R.id.seclblSearchGroup)).setVisibility(View.VISIBLE); ((ImageButton) findViewById(R.id.btnPlus)).setVisibility(View.GONE); ((ImageButton) findViewById(R.id.btnMinus)).setVisibility(View.VISIBLE); } }); ((ImageButton) findViewById(R.id.btnMinus)).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { ((LinearLayout) findViewById(R.id.seclblSearchGroup)).setVisibility(View.GONE); ((ImageButton) findViewById(R.id.btnMinus)).setVisibility(View.GONE); ((ImageButton) findViewById(R.id.btnPlus)).setVisibility(View.VISIBLE); } }); final Boolean displayheader = true; } private void DataSearch(String month, String ProvCode) { try { list = (ListView) findViewById(R.id.lstData); list.setAdapter(null); Cursor cur = null; if (month.length() > 0) { cur = C.ReadData("SELECT A.status AS status,ifnull(B.status, '' ) AS dstatus,ifnull(A.modifyDate, '' ) AS modifyDate,ifnull(B.upload, '' ) AS upload,\n" + " B.workPlanDate AS workPlanDate,\n" + " group_concat(\n" + " ( CASE\n" + " WHEN CAST ( C.itemcode AS int ) = 1 THEN C.itemdes || ',-ইউনিট:' ||B.unitNo ||'-'||(Select UNameBan from FWAUnit where UCode in (SELECT unitNo FROM workPlanDetail where unitNo = B.unitNo and workPlanDate=B.workPlanDate )\n" + " \n" + ")|| ',গ্রাম:' ||( \n" + " SELECT VILLAGENAME\n" + " FROM Village\n" + " WHERE MOUZAID IN ( \n" + " SELECT substr(village, 1, 3 )\n" + " FROM workPlanDetail where providerId= B.providerId and unitNo= B.unitNo and MOUZAID=substr(B.village, 1, 3 ) and VILLAGEID=substr(B.village, 4, 5 ) and workPlanDate=B.workPlanDate\n" + " ) \n" + " \n" + " ) \n" + " || ' ,দম্পতি নম্বর:(' || B.elcoFrom || '-' || B.elcoTo || ')' \n" + " WHEN CAST ( C.itemcode AS int ) = 16 THEN C.itemdes || ',-ইউনিট:' || B.unitNo ||'-'||(Select UNameBan from FWAUnit where UCode in (SELECT unitNo FROM workPlanDetail where unitNo = B.unitNo and workPlanDate=B.workPlanDate )\n" + " \n" + ")|| ',গ্রাম:' ||( \n" + " SELECT VILLAGENAME\n" + " FROM Village\n" + " WHERE MOUZAID IN ( \n" + " SELECT substr(village, 1, 3 )\n" + " FROM workPlanDetail where providerId= B.providerId and unitNo= B.unitNo and MOUZAID=substr(B.village, 1, 3 ) and VILLAGEID=substr(B.village, 4, 5 ) and workPlanDate=B.workPlanDate\n" + " ) \n" + " \n" + " ) \n" + " || ' ,দম্পতি নম্বর:(' || B.elcoFrom || '-' || B.elcoTo || ')' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 1 THEN C.itemdes || ':বাৎসরিক' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 2 THEN C.itemdes || ':অসুস্থতা জনিত' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 3 THEN C.itemdes || ':মাতৃত্বকালীন' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 4 THEN C.itemdes || ':পিতৃত্ব কালীন ছুটি' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 5 THEN C.itemdes || ':নৈমিত্তিক ছুটি' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 6 THEN C.itemdes || ':শ্রান্তি ও বিনোদন' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 7 THEN C.itemdes || ':ঐচ্ছিক ছুটি' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 8 THEN C.itemdes || ':সরকারী ছুটি' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 9 THEN C.itemdes || ':অন্যান্য' \n" + " ELSE ifnull( C.itemdes, '' ) \n" + " END )) AS itemdes\n" + " FROM workPlanMaster A\n" + " INNER JOIN workPlanDetail B\n" + " ON A.workPlanId = B.workPlanId and B.providerId=A.providerId and A.providerId=B.providerId and A.month=substr( B.workPlanDate, 1, 7 )\n" + " INNER JOIN fpaItem C\n" + " ON B.item = C.itemcode\n" + " WHERE B.providerId= '" + ProvCode + "' And C.type = '1' And A.status='3' And B.status='2'\n" + " AND\n" + " substr( B.workPlanDate, 1, 7 )='" + month + "' group by B.workPlanDate,B.status"); } else { cur = C.ReadData("SELECT A.status AS status,ifnull(B.status, '' ) AS dstatus,ifnull(A.modifyDate, '' ) AS modifyDate,ifnull(B.upload, '' ) AS upload,\n" + " B.workPlanDate AS workPlanDate,\n" + " group_concat(\n" + " ( CASE\n" + " WHEN CAST ( C.itemcode AS int ) = 1 THEN C.itemdes || ',-ইউনিট:' || B.unitNo ||'-'||(Select UNameBan from FWAUnit where UCode in (SELECT unitNo FROM workPlanDetail where unitNo = B.unitNo and workPlanDate=B.workPlanDate )\n" + " \n" + ") || ',গ্রাম:' ||( \n" + " SELECT VILLAGENAME\n" + " FROM Village\n" + " WHERE MOUZAID IN ( \n" + " SELECT substr(village, 1, 3 )\n" + " FROM workPlanDetail where providerId= B.providerId and unitNo= B.unitNo and MOUZAID=substr(B.village, 1, 3 ) and VILLAGEID=substr(B.village, 4, 5 ) and workPlanDate=B.workPlanDate\n" + " ) \n" + " \n" + " ) \n" + " || ' ,দম্পতি নম্বর:(' || B.elcoFrom || '-' || B.elcoTo || ')' \n" + " WHEN CAST ( C.itemcode AS int ) = 16 THEN C.itemdes || ',-ইউনিট:' || B.unitNo ||'-'||(Select UNameBan from FWAUnit where UCode in (SELECT unitNo FROM workPlanDetail where unitNo = B.unitNo and workPlanDate=B.workPlanDate )\n" + " \n" + ")|| ',গ্রাম:' ||( \n" + " SELECT VILLAGENAME\n" + " FROM Village\n" + " WHERE MOUZAID IN ( \n" + " SELECT substr(village, 1, 3 )\n" + " FROM workPlanDetail where providerId= B.providerId and unitNo= B.unitNo and MOUZAID=substr(B.village, 1, 3 ) and VILLAGEID=substr(B.village, 4, 5 ) and workPlanDate=B.workPlanDate\n" + " ) \n" + " \n" + " ) \n" + " || ' ,দম্পতি নম্বর:(' || B.elcoFrom || '-' || B.elcoTo || ')' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 1 THEN C.itemdes || ':বাৎসরিক' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 2 THEN C.itemdes || ':অসুস্থতা জনিত' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 3 THEN C.itemdes || ':মাতৃত্বকালীন' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 4 THEN C.itemdes || ':পিতৃত্ব কালীন ছুটি' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 5 THEN C.itemdes || ':নৈমিত্তিক ছুটি' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 6 THEN C.itemdes || ':শ্রান্তি ও বিনোদন' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 7 THEN C.itemdes || ':ঐচ্ছিক ছুটি' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 8 THEN C.itemdes || ':সরকারী ছুটি' \n" + " WHEN CAST ( C.itemcode AS int ) = 9 \n" + " AND\n" + " B.leaveType = 9 THEN C.itemdes || ':অন্যান্য' \n" + " ELSE ifnull( C.itemdes, '' ) \n" + " END )) AS itemdes\n" + " FROM workPlanMaster A\n" + " INNER JOIN workPlanDetail B\n" + " ON A.workPlanId = B.workPlanId and B.providerId=A.providerId and A.providerId=B.providerId and A.month=substr( B.workPlanDate, 1, 7 )\n" + " INNER JOIN fpaItem C\n" + " ON B.item = C.itemcode\n" + " WHERE B.providerId='" + ProvCode + "' And C.type = '1' And A.status='3' And B.status='2' \n" + " AND\n" + " substr( B.workPlanDate, 1, 7 )='" + month + "' group by B.workPlanDate,B.status"); } cur.moveToFirst(); dataList.clear(); while (!cur.isAfterLast()) { HashMap<String, String> map = new HashMap<String, String>(); //w list = (ListView)findViewById(R.id.lstData); map.put("workPlanDate", cur.getString(cur.getColumnIndex("workPlanDate"))); map.put("itemdes", cur.getString(cur.getColumnIndex("itemdes"))); map.put("Status", cur.getString(cur.getColumnIndex("status"))); map.put("Dstatus", cur.getString(cur.getColumnIndex("dstatus"))); map.put("ModifyDate", cur.getString(cur.getColumnIndex("modifyDate"))); map.put("Upload", cur.getString(cur.getColumnIndex("upload"))); dataList.add(map); dataAdapter = new SimpleAdapter(FpaWorkPlaningViewFPINotAproved.this, dataList, R.layout.fpaworkplanrowview, new String[]{"edit"}, new int[]{R.id.cmdB1}); list.setAdapter(new DataListAdapter(this)); cur.moveToNext(); } cur.close(); } catch (Exception e) { Connection.MessageBox(FpaWorkPlaningViewFPINotAproved.this, e.getMessage()); return; } } public class DataListAdapter extends BaseAdapter { private Context context; public DataListAdapter(Context c) { context = c; } public int getCount() { return dataAdapter.getCount(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = inflater.inflate(R.layout.fpaworkplanrowview, null); } Button cmdB1 = (Button) convertView.findViewById(R.id.cmdB1); final TableLayout memtab = (TableLayout) convertView.findViewById(R.id.memtab); final TextView workPlanDate = (TextView) convertView.findViewById(R.id.workPlanDate); final TextView itemdes = (TextView) convertView.findViewById(R.id.itemdes); final TextView status = (TextView) convertView.findViewById(R.id.status); final HashMap<String, String> o = (HashMap<String, String>) dataAdapter.getItem(position); workPlanDate.setText(Global.DateConvertDMY(o.get("workPlanDate"))); itemdes.setText(o.get("itemdes")); if (o.get("Upload").equals("1")) { cmdSync.setText("Submitted"); cmdSync.setBackgroundColor(Color.parseColor("#99cc33")); } else if (o.get("Upload").equals("2")) { cmdSync.setText("Submit"); cmdSync.setTextColor(Color.BLACK); cmdSync.setBackgroundColor(Color.parseColor("#C2E0EC")); } if (o.get("Dstatus").equalsIgnoreCase("2")) { status.setVisibility(View.VISIBLE); memtab.setBackgroundColor(Color.YELLOW); status.setText("FWA অগ্রিম কর্মসূচী পরিবর্তন করতে হবে"); } else { status.setText(""); memtab.setBackgroundColor(Color.WHITE); } return convertView; } } protected Dialog onCreateDialog(int id) { final Calendar c = Calendar.getInstance(); hour = c.get(Calendar.HOUR_OF_DAY); minute = c.get(Calendar.MINUTE); Integer Y = g.mYear; Integer M = g.mMonth; Integer D = g.mDay; switch (id) { case DATE_DIALOG: return new DatePickerDialog(this, mDateSetListener, Y, M - 1, 1); case TIME_DIALOG: return new TimePickerDialog(this, timePickerListener, hour, minute, false); } return null; } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear + 1; mDay = dayOfMonth; EditText dtpDate; /* dtpDate = (EditText)findViewById(R.id.dtpAgDT); if (VariableID.equals("btnAgDT")) { dtpDate = (EditText)findViewById(R.id.dtpAgDT); dtpDate.setText(new StringBuilder() .append(Global.Right("00" + mMonth,2)).append("/") .append(mYear)); } if (VariableID.equals("btnItemDT")) { dtpDate = (EditText)findViewById(R.id.dtpItemDT); dtpDate.setText(new StringBuilder() .append(Global.Right("00"+mDay,2)).append("/") .append(Global.Right("00"+mMonth,2)).append("/") .append(mYear)); } */ } }; private TimePickerDialog.OnTimeSetListener timePickerListener = new TimePickerDialog.OnTimeSetListener() { public void onTimeSet(TimePicker view, int selectedHour, int selectedMinute) { hour = selectedHour; minute = selectedMinute; EditText tpTime; } }; }
package E2EAzubuTest; import com.codeborne.selenide.Configuration; import com.codeborne.selenide.Screenshots; import com.google.common.io.Files; import org.junit.After; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.chrome.ChromeDriver; import ru.yandex.qatools.allure.annotations.Attachment; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selenide.*; import static org.junit.Assert.assertEquals; /** * Created by oryabinskiy on 12/4/2015. */ public class StageMainFeaturesTest extends BasicMethods { @BeforeClass public static void setup(){ System.setProperty("webdriver.chrome.driver", "C://Program Files//Google//Chrome//Application//chromedriver.exe"); Configuration.browser = "chrome"; } @After public void tearDown() throws IOException { screenshot(); } @Attachment(type = "image/png") public byte[] screenshot() throws IOException { File screenshot = Screenshots.getScreenShotAsFile(); return Files.toByteArray(screenshot); } @Test public void incorrectLogin() throws IOException { smartOpen(); login("incorrect", "some pass"); $(".toast-error div").shouldBe(visible).should(have(exactText("login was not successful. please try again."))); } @Test public void testLogin() throws IOException { smartOpen(); readDataFromFile("Stage_acc.csv"); login(getUsername("Broadcaster"), getPassword("Broadcaster")); successConfirmation.shouldBe(visible); assertLoginSuccess(); } @Test public void testIsStreamAppearOnHomePage() throws IOException { if($(".home-video-list li").is(visible)){ } else { screenshot(); } } @Test public void testCreatingAndDeletingGearModule() throws IOException { openMenuItem("My Channel"); //Briks are not appears without refresh refresh(); while(module.is(visible)){ deleteModule(); sleep(10000); refresh(); } module.shouldBe(not(visible)); openMenuItem("create a Module"); selectModuleType("gear"); $("#brickTitle").setValue("Test Title"); $("#itemName").setValue("Test name"); $("#itemURL").setValue("http://google.com"); $("#itemCategory").setValue("Test category"); $(".button-main").click(); successConfirmation.shouldBe(visible); openMenuItem("My Channel"); for(int i=0; i<7; i++) { if (module.is(visible)) { screenshot(); break; } else { sleep(5000); refresh(); } } deleteModule(); module.is(not(visible)); screenshot(); sleep(30000); refresh(); module.is(not(visible)); } /* @Test public void testRegistration() throws IOException { generateNewEmailAddress(); String emailAddress = $("#fe_text").shouldBe(visible).getAttribute("value"); writeEmailToFile(emailAddress); smartOpen(); $(".sign-up").click(); $("#signUpEmail").setValue(emailAddress).pressEnter(); successConfirmation.shouldBe(visible); open("https://10minutemail.net/"); $$("#maillist td").find(exactText("Confirm your AzubuTV registration")).shouldBe(visible).click(); $("#tabs-1").shouldBe(visible).should(have(text("new account creation on Azubu.tv"))); $("#tabs-1 a").click(); $("#form-registration-user").shouldBe(visible); $(".form-control[type=text]").setValue("name"); $(".form-control[name=password_1]").setValue("123321"); $(".form-control[name=password_2]").setValue("123321"); $("#license-checkbox").click(); sleep(10000); }*/ }
package me.neznamy.tab.yamlassist; import java.util.List; import org.yaml.snakeyaml.error.YAMLException; public abstract class SyntaxError { protected YAMLException exception; protected List<String> fileLines; public SyntaxError(YAMLException exception, List<String> fileLines) { this.exception = exception; this.fileLines = fileLines; } public abstract boolean isType(); public abstract String getSuggestion(); }
/* * 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 model.entity; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * * @author Sasha */ public class User extends Person { /** user account */ private BigDecimal account; /** list of user's orders */ private List<Order> orders; /** * Constructor * @param firstName user first name * @param lastName user last name * @param email user email * @param password users' password */ public User(String firstName, String lastName, String email, String password) { super(firstName, lastName, email, password); } /** * Get user account * @return */ public BigDecimal getAccount() { return account; } /** * Set user account * @param account user account */ public void setAccount(BigDecimal account) { this.account = account; } /** * Set all user's orders * @param orders */ public void setOrders(List<Order> orders) { this.orders = orders; } /** * Get orders * @return list of orders */ public List<Order> getOrders() { return orders; } /** * Add order to the user's order list * @param order */ public void addOrder(Order order) { if (orders == null) { orders = new ArrayList<>(); } orders.add(order); } /** * Remove order from user's order list by id * @param orderId id of order might be removed */ public void removeOrderById(int orderId) { if (orders != null) { for (Order order : orders) { if (order.id == orderId) { orders.remove(order); break; } } } } }
package com.goodhealth.algorithm.Genericity; /** * @ClassName Pear * @Description TODO * @Author WDH * @Date 2019/8/15 19:12 * @Version 1.0 **/ public class Pear extends Fruits { @Override public void function() { System.out.println("生津止渴,润肺止咳"); } }
package moderate; /* Sample code to read in test cases:*/ import java.io.*; import java.util.*; import java.lang.*; public class MToLast { public static void main (String[] args) throws IOException { File file = new File(args[0]); BufferedReader buffer = new BufferedReader(new FileReader(file)); String line; while ((line = buffer.readLine()) != null) { line = line.trim(); String[] str = line.split("\\s+"); int n = Integer.parseInt(str[str.length-1]); n++; if(n>str.length || n<1){ continue; } String res =""; for(int i=0; i<=(str.length - n); i++){ res = str[i]; } System.out.println(res); } } }
package com.example.provider.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** * @author 86151 */ @RestController public class ProviderController { @GetMapping(value = "/echo") public String echo(@RequestParam("name") String name) { return "Hello Nacos Discovery " + name; } }
import java.util.HashSet; import java.util.Set; /** * Created by vlado on 10/12/2017. */ public class AdventNode { private AdventNode _parent; private int _weight; private String _name; private Set<AdventNode> _children; public AdventNode(String name, int weight) { _name = name; _weight = weight; _parent = null; _children = new HashSet<AdventNode>(); } public AdventNode getParent() { return _parent; } public void setParent(AdventNode parent) { _parent = parent; } public String getName() { return _name; } public Set<AdventNode> getChildren() { return _children; } public void addChild(AdventNode child){ _children.add(child); } public int getTreeWeight() { int totalWeight = _weight; for (AdventNode child : _children) { totalWeight += child.getTreeWeight(); } return totalWeight; } public int getNodeWeight() { return _weight; } @Override public String toString() { return "AdventNode{" + ", _weight=" + _weight + ", _name='" + _name + '\'' + ", TreeWeight=" + this.getTreeWeight() + '}'; } }
package com.factory.dominik.factorynewsreader.ui.article.list; import com.factory.dominik.factorynewsreader.data.model.ArticlesModel; import java.util.List; public interface ArticleListView { void showArticles(List<ArticlesModel> articles); void cacheArticles(List<ArticlesModel> articles); void showArticlesFetchError(String message); }
package com.semantyca.officeframe.modules.reference.dao; import com.semantyca.officeframe.modules.reference.model.Position; import javax.ejb.Stateless; @Stateless public class PositionDAO extends ReferenceDAO<Position> { }
package leetcode; import java.util.ArrayList; import java.util.List; /** * @author kangkang lou */ public class Main_166 { public static String fractionToDecimal(int numerator0, int denominator0) { StringBuilder sb = new StringBuilder(); if ((numerator0 < 0 && denominator0 > 0) || (numerator0 > 0 && denominator0 < 0)) { sb.append("-"); } long numerator = Math.abs((long)numerator0); long denominator = Math.abs((long)denominator0); sb.append(numerator / denominator); if (numerator % denominator == 0) { return sb.toString(); } else { sb.append("."); numerator %= denominator; StringBuilder temp = new StringBuilder(); boolean flag = false; List<Long> list = new ArrayList<>(); while (numerator != 0) { if (list.contains(numerator)) { flag = true; break; } list.add(numerator); long a = numerator * 10; long b = numerator; while (a < denominator) { temp.append("0"); a *= 10; b *= 10; list.add(b); } if (a % denominator == 0) { temp.append(a / denominator); break; } else { temp.append(a / denominator); numerator = a % denominator; } } if (flag) { int pos = list.indexOf(numerator); String s = temp.toString(); for (int i = 0; i < s.length(); i++) { if (i == pos) { sb.append("("); } sb.append(s.charAt(i)); } sb.append(")"); } else { sb.append(temp.toString()); } } return sb.toString(); } public static void main(String[] args) { System.out.println(fractionToDecimal(-1, -2147483648)); } }
package backjoon.tree; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; class Point{ int end; int weight; public Point(int end, int weight){ this.end = end; this.weight = weight; } } public class Backjoon1967 { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static final int INF = 10_000 * 100; static List<Point> list[]; static int dist[]; static int n; public static void main(String[] args) throws IOException { n = Integer.parseInt(br.readLine()); list = new ArrayList[n + 1]; for(int i = 0; i <= n ; i++){ list[i] = new ArrayList<>(); } for(int i = 2; i <= n; i++){ StringTokenizer st = new StringTokenizer(br.readLine()); int parent = Integer.parseInt(st.nextToken()); int child = Integer.parseInt(st.nextToken()); int weight = Integer.parseInt(st.nextToken()); list[parent].add(new Point(child, weight)); list[child].add(new Point(parent, weight)); } bfs(1); int farestIdx = 1; for(int i = 2; i <= n; i++) farestIdx = dist[farestIdx] > dist[i] ? farestIdx : i; bfs(farestIdx); int farestLength = 0; for(int i = 1; i <= n; i++) farestLength = farestLength > dist[i] ? farestLength : dist[i]; System.out.println(farestLength); } public static void bfs(int start){ Queue<Point> queue = new LinkedList<>(); dist = new int[n + 1]; Arrays.fill(dist, INF); queue.add(new Point(start, 0)); dist[start] = 0; while (!queue.isEmpty()){ Point curPoint = queue.poll(); for(Point p : list[curPoint.end]){ if(dist[p.end] == INF){ dist[p.end] = curPoint.weight + p.weight; queue.add(new Point(p.end, dist[p.end])); } } } } }
package com.udemy.oauth2.udemyoauth2.controller; import com.udemy.oauth2.udemyoauth2.model.Task; import com.udemy.oauth2.udemyoauth2.repository.TaskRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.security.Principal; import java.util.List; @RestController public class TaskController { @Autowired private TaskRepository taskRepository; @PostMapping(value = "/getTasks", produces= MediaType.APPLICATION_JSON_VALUE) public List<Task> getTasksForUser(Principal principal) { return taskRepository.findByHolderName(principal.getName()); } @PostMapping("/insertTask") public ResponseEntity<Void> addTaskForUser(Principal principal, String task) { Task t = new Task(principal.getName(), task); taskRepository.save(t); return new ResponseEntity<Void>(HttpStatus.CREATED); } }
package io.hessian.rpc.core; /** * Created by manbu on 7/2/16. */ public class SerializeException extends RuntimeException { public SerializeException(String message, Exception exception) { super(message, exception); } }
// Sun Certified Java Programmer // Chapter 7, P583 // Generics and Collections class Cat { }
package com.sunteam.library.db; import java.util.ArrayList; import com.sunteam.library.entity.DownloadResourceEntity; import com.sunteam.library.utils.DatabaseConstants; import com.sunteam.library.utils.LibraryConstant; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; public class DownloadResourceDBDao { private LibraryDBHelper mLibraryDBHelper = null; public DownloadResourceDBDao( Context context, String name, CursorFactory factory, int version ) { mLibraryDBHelper = new LibraryDBHelper( context, name, factory, version ); } public DownloadResourceDBDao( Context context, String name ) { mLibraryDBHelper = new LibraryDBHelper( context, name, null, DatabaseConstants.DATABASE_VERSION ); } public DownloadResourceDBDao( Context context ) { mLibraryDBHelper = new LibraryDBHelper( context, DatabaseConstants.LIBRARY_DATABASE_NAME, null, DatabaseConstants.DATABASE_VERSION ); } public void insert( DownloadResourceEntity entity ) { if( null == entity ) { return; } SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); String sql = "insert into " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " (" + DatabaseConstants.DOWNLOAD_RESOURCE_CHAPTER_COUNT + "," + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + "," + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + "," + DatabaseConstants.DOWNLOAD_RESOURCE_TITLE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_DBCODE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_SYSID + "," + DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER + "," + DatabaseConstants.DOWNLOAD_RESOURCE_CATEGORYCODE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_FULLNAME + ") values (?,?,?,?,?,?,?,?,?,?)"; db.execSQL( sql, new Object[]{entity.chapterCount,entity.resType,entity.status,entity.userName,entity.title,entity.dbCode,entity.sysId,entity.identifier,entity.categoryCode,entity.categoryFullName}); db.close(); } //顺序插入 public void insert( ArrayList<DownloadResourceEntity> list ) { if( ( null == list ) || ( list.size() == 0 ) ) { return; } SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); int size = list.size(); for( int i = 0; i < size; i++ ) { DownloadResourceEntity entity = list.get(i); String sql = "insert into " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " (" + DatabaseConstants.DOWNLOAD_RESOURCE_CHAPTER_COUNT + "," + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + "," + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + "," + DatabaseConstants.DOWNLOAD_RESOURCE_TITLE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_DBCODE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_SYSID + "," + DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER + "," + DatabaseConstants.DOWNLOAD_RESOURCE_CATEGORYCODE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_FULLNAME + ") values (?,?,?,?,?,?,?,?,?,?)"; db.execSQL( sql, new Object[]{entity.chapterCount,entity.resType,entity.status,entity.userName,entity.title,entity.dbCode,entity.sysId,entity.identifier,entity.categoryCode,entity.categoryFullName}); } db.close(); } //倒序插入 public void insertDescending( ArrayList<DownloadResourceEntity> list ) { if( ( null == list ) || ( list.size() == 0 ) ) { return; } SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); int size = list.size(); for( int i = size-1; i >= 0; i-- ) { DownloadResourceEntity entity = list.get(i); String sql = "insert into " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " (" + DatabaseConstants.DOWNLOAD_RESOURCE_CHAPTER_COUNT + "," + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + "," + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + "," + DatabaseConstants.DOWNLOAD_RESOURCE_TITLE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_DBCODE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_SYSID + "," + DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER + "," + DatabaseConstants.DOWNLOAD_RESOURCE_CATEGORYCODE + "," + DatabaseConstants.DOWNLOAD_RESOURCE_FULLNAME + ") values (?,?,?,?,?,?,?,?,?,?)"; db.execSQL( sql, new Object[]{entity.chapterCount,entity.resType,entity.status,entity.userName,entity.title,entity.dbCode,entity.sysId,entity.identifier,entity.categoryCode,entity.categoryFullName}); } db.close(); } //清除整个表数据 public void clearTable() { String sql1 = "DELETE FROM " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME +";"; String sql2= "update sqlite_sequence set seq=0 where name='" + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + "'"; SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); db.execSQL(sql1); db.execSQL(sql2); db.close(); } //查找所有数据条数 public long getCount() { SQLiteDatabase db = mLibraryDBHelper.getReadableDatabase(); if( null == db ) { return 0; } Cursor cursor = db.rawQuery("select count(*) from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME, null); if( null == cursor ) { return 0; } cursor.moveToFirst(); long count = cursor.getLong(0); if (!cursor.isClosed()) { cursor.close(); } db.close(); return count; } //查找数据 public DownloadResourceEntity find( String userName, int resType, String bookId ) { SQLiteDatabase db = mLibraryDBHelper.getReadableDatabase(); Cursor cursor = null; if( LibraryConstant.LIBRARY_DATATYPE_EBOOK == resType ) { cursor = db.rawQuery("select * from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER + " = ?", new String[]{userName, resType+"", bookId}); } else { cursor = db.rawQuery("select * from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_SYSID + " = ?", new String[]{userName, resType+"", bookId}); } if( null == cursor ) { db.close(); return null; } DownloadResourceEntity entity = null; while(cursor.moveToNext()) { entity = new DownloadResourceEntity(); entity._id = cursor.getInt(cursor.getColumnIndex("_id")); entity.chapterCount = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_CHAPTER_COUNT)); entity.resType = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE)); entity.status = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_STATUS)); entity.userName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME)); entity.title = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_TITLE)); entity.dbCode = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_DBCODE)); entity.sysId = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_SYSID)); entity.identifier = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER)); entity.categoryCode = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_CATEGORYCODE)); entity.categoryFullName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_FULLNAME)); break; } if (!cursor.isClosed()) { cursor.close(); } db.close(); return entity; } //查找数据 public DownloadResourceEntity find( String userName, DownloadResourceEntity dre ) { SQLiteDatabase db = mLibraryDBHelper.getReadableDatabase(); Cursor cursor = null; if( LibraryConstant.LIBRARY_DATATYPE_EBOOK == dre.resType ) { cursor = db.rawQuery("select * from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER + " = ?", new String[]{userName, dre.resType+"", dre.identifier}); } else { cursor = db.rawQuery("select * from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_SYSID + " = ?", new String[]{userName, dre.resType+"", dre.sysId}); } if( null == cursor ) { db.close(); return null; } DownloadResourceEntity entity = null; while(cursor.moveToNext()) { entity = new DownloadResourceEntity(); entity._id = cursor.getInt(cursor.getColumnIndex("_id")); entity.chapterCount = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_CHAPTER_COUNT)); entity.resType = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE)); entity.status = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_STATUS)); entity.userName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME)); entity.title = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_TITLE)); entity.dbCode = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_DBCODE)); entity.sysId = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_SYSID)); entity.identifier = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER)); entity.categoryCode = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_CATEGORYCODE)); entity.categoryFullName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_FULLNAME)); break; } if (!cursor.isClosed()) { cursor.close(); } db.close(); return entity; } //查找所有已完成数据 public ArrayList<DownloadResourceEntity> findAllCompleted( String userName ) { SQLiteDatabase db = mLibraryDBHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + " = ?", new String[]{userName, "2"}); if( null == cursor ) { db.close(); return null; } ArrayList<DownloadResourceEntity> list = new ArrayList<DownloadResourceEntity>(); while(cursor.moveToNext()) { DownloadResourceEntity entity = new DownloadResourceEntity(); entity._id = cursor.getInt(cursor.getColumnIndex("_id")); entity.chapterCount = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_CHAPTER_COUNT)); entity.resType = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE)); entity.status = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_STATUS)); entity.userName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME)); entity.title = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_TITLE)); entity.dbCode = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_DBCODE)); entity.sysId = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_SYSID)); entity.identifier = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER)); entity.categoryCode = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_CATEGORYCODE)); entity.categoryFullName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_FULLNAME)); list.add(0,entity); //逆序插入 } if (!cursor.isClosed()) { cursor.close(); } db.close(); return list; } //查找所有未完成数据 public ArrayList<DownloadResourceEntity> findAllUnCompleted( String userName ) { SQLiteDatabase db = mLibraryDBHelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select * from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + " != ?", new String[]{userName, "2"}); if( null == cursor ) { db.close(); return null; } ArrayList<DownloadResourceEntity> list = new ArrayList<DownloadResourceEntity>(); while(cursor.moveToNext()) { DownloadResourceEntity entity = new DownloadResourceEntity(); entity._id = cursor.getInt(cursor.getColumnIndex("_id")); entity.chapterCount = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_CHAPTER_COUNT)); entity.resType = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE)); entity.status = cursor.getInt(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_STATUS)); entity.userName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME)); entity.title = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_TITLE)); entity.dbCode = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_DBCODE)); entity.sysId = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_SYSID)); entity.identifier = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER)); entity.categoryCode = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_CATEGORYCODE)); entity.categoryFullName = cursor.getString(cursor.getColumnIndex(DatabaseConstants.DOWNLOAD_RESOURCE_FULLNAME)); list.add(entity); } if (!cursor.isClosed()) { cursor.close(); } db.close(); return list; } //删除数据 public void delete( String userName, int resType, String bookId ) { SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); if( LibraryConstant.LIBRARY_DATATYPE_EBOOK == resType ) { db.execSQL("delete from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER + " = ?", new String[]{userName, resType+"", bookId}); } else { db.execSQL("delete from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_SYSID + " = ?", new String[]{userName, resType+"", bookId}); } db.close(); } //删除数据 public void delete( DownloadResourceEntity entity ) { SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); if( LibraryConstant.LIBRARY_DATATYPE_EBOOK == entity.resType ) { db.execSQL("delete from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_IDENTIFIER + " = ?", new String[]{entity.userName, entity.resType+"", entity.identifier}); } else { db.execSQL("delete from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_RESTYPE + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_SYSID + " = ?", new String[]{entity.userName, entity.resType+"", entity.sysId}); } db.close(); } //删除所有已完成数据 public void deleteAllCompleted( String username ) { SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); db.execSQL("delete from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + " = ?", new String[]{username, "2"}); db.close(); } //删除所有未完成数据 public void deleteAllUnCompleted( String username ) { SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); db.execSQL("delete from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " where " + DatabaseConstants.DOWNLOAD_RESOURCE_USERNAME + " = ? and " + DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + " != ?", new String[]{username, "2"}); db.close(); } //删除所有的数据 public void deleteAll() { SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); db.execSQL("delete from " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME, null); db.close(); } //更新状态 public void update( int status, int recorcdId ) { SQLiteDatabase db = mLibraryDBHelper.getWritableDatabase(); db.execSQL("update " + DatabaseConstants.DOWNLOAD_RESOURCE_TABLE_NAME + " set "+ DatabaseConstants.DOWNLOAD_RESOURCE_STATUS + "=? where " + "_id" + " = ?", new String[]{status+"", recorcdId+""}); db.close(); } //关闭数据库 public void closeDb() { if (mLibraryDBHelper != null) { mLibraryDBHelper.close(); } } }
package com.cg.hcs.service; import java.time.LocalDateTime; import com.cg.hcs.dao.IUserDAO; import com.cg.hcs.dao.UserDAOImpl; import com.cg.hcs.entity.DiagnosticCenter; import com.cg.hcs.entity.Test; import com.cg.hcs.entity.Users; public class UserServiceImpl implements IUserService{ IUserDAO userDaoInterface = new UserDAOImpl(); public String makeAppointment(Users user, DiagnosticCenter test, String datetime) { return userDaoInterface.makeAppointment(user, test, datetime); } public String register(Users user) { return userDaoInterface.register(user); } public String getRoleCode(String userId) { // TODO Auto-generated method stub return userDaoInterface.getRoleCode(userId); } public boolean validateUser(String userId, String password) { // TODO Auto-generated method stub return userDaoInterface.validateUser(userId, password); } }
package com.jovanmillenno.e_forecasting; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class HasilActivity extends AppCompatActivity { TextView namabarang,hasil; Button ulang, keluar; Intent pindah; String nama, satuan; String hasilakhirstring; int hasilakhirint; double hasilakhir; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hasil); Intent intent = getIntent(); nama = intent.getStringExtra("nama"); satuan = intent.getStringExtra("satuan"); hasilakhir = intent.getDoubleExtra("hasil",hasilakhir); namabarang = findViewById(R.id.namabarang); hasil = findViewById(R.id.hasil); namabarang.setText(nama); hasilakhirint = (int) hasilakhir; hasilakhirstring = String.valueOf(hasilakhirint); hasil.setText(hasilakhirstring+" "+satuan); ulang = findViewById(R.id.btn1); ulang.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { pindah = new Intent(HasilActivity.this, HomeActivity.class); startActivity(pindah); //saat pindah, activity yg sekarang langsung ditutup //agar saat menekan tombol kembali tidak bolak-balik finish(); } }); keluar = findViewById(R.id.btn2); keluar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { moveTaskToBack(true); } }); } @Override public void onBackPressed() { new AlertDialog.Builder(this) .setIcon(R.mipmap.ic_launcher) .setTitle(R.string.app_name) .setMessage("Kamu yakin ingin keluar?") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }) .show(); } }
package com.example.aleksej.budget; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.lang.String; import android.widget.TextView; import android.widget.Toast; import org.w3c.dom.Text; import java.security.acl.LastOwnerException; import java.util.InputMismatchException; public class secondScreen extends AppCompatActivity { final Context c = this; String s; double d; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second_screen); Button addButton = (Button) findViewById(R.id.addButton); addButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { LayoutInflater layoutInflaterAndriod = LayoutInflater.from(c); View v = layoutInflaterAndriod.inflate(R.layout.user_input_dialog_box, null); AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(c); alertDialogBuilderUserInput.setView(v); final EditText inputName = (EditText) v.findViewById(R.id.name); final EditText inputNumber = (EditText) v.findViewById(R.id.amount); alertDialogBuilderUserInput.setCancelable(false); alertDialogBuilderUserInput.setPositiveButton("Create", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { try { s = inputName.getText().toString(); d = Double.parseDouble(inputNumber.getText().toString()); TextView textView = (TextView) findViewById(R.id.test); textView.setText(s); } catch (NumberFormatException q) { Toast.makeText(secondScreen.this, "Please Enter A Number in the Enter Amount", Toast.LENGTH_LONG).show(); } System.out.println(s); System.out.println(d); } }); alertDialogBuilderUserInput.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialogAndroid = alertDialogBuilderUserInput.create(); alertDialogAndroid.show(); } }); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package herramientas; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; /** * * @author Administrador */ public class insertaOperclientes { private static Connection conexion = null; private static String sRutaPropiedades = "/data/informes/generaOperacionesbsch/propiedades/generaOperacionesbsch.properties"; private static Utilidades.Propiedades propiedades = null; public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, Exception { //insertaOperclientes(); //insertaCatastro(); //insertaSeguimiento(); numera(); System.gc(); } public static void numera() { String sconsulta = ""; java.sql.ResultSet rs = null; Objetos.unidades.Elementos oelementos = new Objetos.unidades.Elementos(); int contador = 0; rs = null; try { File fPropiedades = new File(sRutaPropiedades); propiedades = new Utilidades.Propiedades(fPropiedades.getAbsolutePath()); conexion = Utilidades.Conexion.getConnection(propiedades.getValueProperty("IfxConexion"),propiedades.getValueProperty("IfxLogin"),propiedades.getValueProperty("IfxPass")); conexion.setAutoCommit(false); sconsulta = "SELECT id_elmto FROM elementos where numexp = '1553 0308 160008 V2'"; rs = Utilidades.Conexion.select(sconsulta,conexion); while (rs.next()) { contador ++; if (oelementos.load(rs.getInt("id_elmto"), conexion)) { oelementos.id_agrupa = contador; if (oelementos.update(conexion) == 1) { conexion.commit(); } else conexion.rollback(); oelementos.clear(); } } rs.close(); rs = null; } catch (Exception e) { } finally { try { conexion.close(); } catch (Exception e) { } } } /* public static void insertaOperclientes() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException { File fPropiedades = new File(sRutaPropiedades); propiedades = new Utilidades.Propiedades(fPropiedades.getAbsolutePath()); conexion = Utilidades.Conexion.getConnection(propiedades.getValueProperty("IfxConexion"),propiedades.getValueProperty("IfxLogin"),propiedades.getValueProperty("IfxPass")); conexion.setAutoCommit(false); String cliente = "255"; String expediente = "1550 0902 142956"; String referencia = "0000009383"; String tipoObjeto = "01"; //04 para promociones 01 para expediente Tablas.operclientes operservihabitat = new Tablas.operclientes(cliente); String seq = Funciones.Fcomunes.obtenerSecuencia(conexion,cliente); operservihabitat.setIdmensaje(seq); operservihabitat.setNumexp(expediente); operservihabitat.setReferencia(referencia.trim()); operservihabitat.setTipoperacion("REC"); operservihabitat.setTipomensaje("STA"); operservihabitat.setControl(tipoObjeto); operservihabitat.setPostventa("1"); operservihabitat.setFchenvio(); operservihabitat.setHoraenvio(); operservihabitat.setEstado("101"); //confirmado sta operservihabitat.insertaOperacion(conexion); boolean estadoOK = operservihabitat.EstadoOK(); if (estadoOK) conexion.commit(); else conexion.rollback(); conexion.close(); }//insertaOperclientes public static void insertaCatastro() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, Exception { File fPropiedades = new File(sRutaPropiedades); propiedades = new Utilidades.Propiedades(fPropiedades.getAbsolutePath()); conexion = Utilidades.Conexion.getConnection(propiedades.getValueProperty("IfxConexion"),propiedades.getValueProperty("IfxLogin"),propiedades.getValueProperty("IfxPass")); conexion.setAutoCommit(false); int cuantos = 121; //numero total de registros a insertar Objetos.Catastro oCatastro = new Objetos.Catastro(); oCatastro.numexp = "1550 0827 140957"; oCatastro.tipoinm = "ERC"; for (int i=6; i<=cuantos; i++) { oCatastro.numero = i; if (oCatastro.insert(conexion) == 1) conexion.commit(); else conexion.rollback(); } conexion.close(); }//insertaOperclientes */ public static void insertaSeguimiento() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, Exception { File fPropiedades = new File(sRutaPropiedades); propiedades = new Utilidades.Propiedades(fPropiedades.getAbsolutePath()); //conexion = Utilidades.Conexion.getConnection(propiedades.getValueProperty("IfxConexion"),propiedades.getValueProperty("IfxLogin"),propiedades.getValueProperty("IfxPass")); conexion = Utilidades.Conexion.getConnection(propiedades.getValueProperty("IfxConexion")); conexion.setAutoCommit(false); String expediente = "xxx3456"; Objetos.Refer oRefer = new Objetos.Refer(); oRefer.numexp = expediente; try { if (oRefer.insert(conexion) == 1) System.out.println("INSERTARIA 1"); else System.out.println("INSERTARIA 0"); } catch (Exception e) { System.out.println(e.toString()); } /* boolean estadoOK = false; Objetos.v2.Seguimiento oSeguim = new Objetos.v2.Seguimiento(); if (oSeguim.load2(expediente, conexion)) { oSeguim.numexp = "548.VLT110297700753459"; oSeguim.tipoinm = "VUS"; if (oSeguim.insert(conexion) == 1) conexion.commit(); else conexion.rollback(); } */ conexion.close(); }//insertaOperclientes /* public static void insertaCatastro() throws FileNotFoundException, IOException, ClassNotFoundException, SQLException, Exception { File fPropiedades = new File(sRutaPropiedades); propiedades = new Utilidades.Propiedades(fPropiedades.getAbsolutePath()); conexion = Utilidades.Conexion.getConnection(propiedades.getValueProperty("IfxConexion"),propiedades.getValueProperty("IfxLogin"),propiedades.getValueProperty("IfxPass")); conexion.setAutoCommit(false); int cuantos = 121; //numero total de registros a insertar Objetos.Catastro oCatastro = new Objetos.Catastro(); oCatastro.numexp = "1550 0827 140957"; oCatastro.tipoinm = "ERC"; for (int i=6; i<=cuantos; i++) { oCatastro.numero = i; if (oCatastro.insert(conexion) == 1) conexion.commit(); else conexion.rollback(); } conexion.close(); }//insertaOperclientes * */ }
package com.gmail.khanhit100896.foody.like; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.view.ContextThemeWrapper; import android.support.v7.widget.CardView; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.gmail.khanhit100896.foody.R; import com.gmail.khanhit100896.foody.config.Config; import com.gmail.khanhit100896.foody.food.Food; import com.gmail.khanhit100896.foody.main.GeocodingLocation; import com.gmail.khanhit100896.foody.main.MapActivity; import com.gmail.khanhit100896.foody.main.Point; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class FoodRecyclerViewAdapter extends RecyclerView.Adapter<FoodRecyclerViewAdapter.FoodViewHolder> { /* * Khai báo biến cần thiết */ private Context context; private List<Food> foodList; private List<Food> foodListFull; private String getURL = Config.getConfig().getPathUpdateFood(); /* */ /* * Hàm Constructor */ public FoodRecyclerViewAdapter(Context context, List<Food> foodList) { this.context = context; this.foodList = foodList; this.foodListFull = new ArrayList<>(); this.foodListFull.addAll(this.foodList); } @NonNull @Override public FoodViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view; view = LayoutInflater.from(context).inflate(R.layout.cardview_item_food_like,parent,false); view.startAnimation(AnimationUtils.loadAnimation(context,R.anim.anim_recycler_view)); return new FoodViewHolder(view); } @Override public void onBindViewHolder(@NonNull final FoodViewHolder holder, final int position) { // Gán giá trị cho thuộc tính tên và hình món ăn holder.txt_name_food.setText(this.foodList.get(position).getFood_name()); if(this.foodList.get(position).getFood_price().equals("")){ holder.txt_price_food.setText("Đang cập nhật"); }else{ holder.txt_price_food.setText(this.foodList.get(position).getFood_price()); } Picasso.get().load(Config.getConfig().getPathLoadImgFood() .concat(this.foodList.get(position).getImg_address())) .into(holder.img_food); /* * Bắt sự kiện khi nhấp vào cardview để xem chi tiết món ăn */ holder.cardview_food.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,FoodLikeDetailsActivity.class); intent.putExtra("ID",foodList.get(position).getId()); intent.putExtra("FoodCode",foodList.get(position).getFood_code()); intent.putExtra("FoodName",foodList.get(position).getFood_name()); intent.putExtra("FoodImage",foodList.get(position).getImg_address()); intent.putExtra("FoodAddress",foodList.get(position).getFood_address()); intent.putExtra("FoodPrice",foodList.get(position).getFood_price()); intent.putExtra("FoodKind",foodList.get(position).getKind_code()); foodList.get(position).setAction_like(0); intent.putExtra("ActionLike",foodList.get(position).getAction_like()); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } }); /* */ /* * Bắt sự kiện cho Popup Menu cardview */ holder.iv_menu_food.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Context wrapper = new ContextThemeWrapper(context, R.style.MyPopupMenu); PopupMenu popupMenu = new PopupMenu(wrapper,holder.iv_menu_food); popupMenu.inflate(R.menu.menu_food_like); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { // Bắt sự kiện khi nhấp vào cardview để xem chi tiết món ăn case R.id.action_details: Intent intent0 = new Intent(context,FoodLikeDetailsActivity.class); intent0.putExtra("ID",foodList.get(position).getId()); intent0.putExtra("class",FoodLikeDetailsActivity.class.getSimpleName()); intent0.putExtra("FoodName",foodList.get(position).getFood_name()); intent0.putExtra("FoodImage",foodList.get(position).getImg_address()); intent0.putExtra("FoodAddress",foodList.get(position).getFood_address()); intent0.putExtra("FoodPrice",foodList.get(position).getFood_price()); intent0.putExtra("FoodKind",foodList.get(position).getKind_code()); foodList.get(position).setAction_like(0); intent0.putExtra("ActionLike",foodList.get(position).getAction_like()); intent0.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent0); break; // Bát sự kiện chuyển đến MapActivity case R.id.action_map: Point point = new Point(GeocodingLocation.getLatitude(foodList.get(position).getFood_address(),context) ,GeocodingLocation.getLongitude(foodList.get(position).getFood_address(),context)); Intent intent2 = new Intent(context,MapActivity.class); String className = com.gmail.khanhit100896.foody.food.FoodRecyclerViewAdapter.class.getSimpleName(); intent2.putExtra("context",className); intent2.putExtra("name",foodList.get(position).getFood_name()); intent2.putExtra("image",foodList.get(position).getImg_address()); intent2.putExtra("address",foodList.get(position).getFood_address()); intent2.putExtra("latitude",String.valueOf(point.getLatitude())); intent2.putExtra("longitude",String.valueOf(point.getLongitude())); intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent2); break; case R.id.action_dislike: RequestQueue requestQueue = Volley.newRequestQueue(context); StringRequest stringRequest = new StringRequest(Request.Method.POST, getURL, new Response.Listener<String>() { @Override public void onResponse(String response) { if(response.trim().equals("success")){ Toast toast = Toast.makeText(context,"Đã xóa " + foodList.get(position).getFood_name() + " khỏi danh sách yêu thích.",Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER,0,0); toast.show(); }else{ Toast toast = Toast.makeText(context,"Lỗi. Vui lòng kiểm tra lại.",Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER,0,0); toast.show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } } ){ @Override protected Map<String, String> getParams(){ foodList.get(position).setAction_like(0); Map<String, String> params = new HashMap<>(); params.put("id", String.valueOf(foodList.get(position).getId())); params.put("actionLike", String.valueOf(foodList.get(position).getAction_like())); return params; } }; requestQueue.add(stringRequest); return true; default: break; } return false; } }); popupMenu.show(); } }); /* */ } @Override public int getItemCount() { return foodList.size(); } /* * Class holder - ánh xạ các thuộc tính */ static class FoodViewHolder extends RecyclerView.ViewHolder{ ImageView img_food, iv_menu_food; TextView txt_name_food; TextView txt_price_food; CardView cardview_food; FoodViewHolder(View itemView) { super(itemView); img_food = itemView.findViewById(R.id.img_food); iv_menu_food = itemView.findViewById(R.id.iv_menu_food); txt_name_food = itemView.findViewById(R.id.txt_name_food); txt_price_food = itemView.findViewById(R.id.txt_price_food); cardview_food = itemView.findViewById(R.id.cardview_food_like); } } }
package com.byterefinery.rmbench.dialogs; import org.eclipse.core.resources.IFile; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.dialogs.WizardNewFileCreationPage; import org.eclipse.ui.ide.IDE; import com.byterefinery.rmbench.RMBenchPlugin; import com.byterefinery.rmbench.util.ImageConstants; /** * a wizard for creating a RMBench new model file */ public class NewModelWizard extends Wizard implements INewWizard { public static final String WIZARD_ID = "com.byterefinery.rmbench.wizards.NewModelWizard"; private WizardNewFileCreationPage modelFilePage; private NewModelWizardPage1 modelPropertiesPage; private IStructuredSelection selection; public NewModelWizard() { super(); setDefaultPageImageDescriptor(RMBenchPlugin.getImageDescriptor(ImageConstants.MODEL_WIZARD)); setNeedsProgressMonitor(true); } public void addPages() { modelPropertiesPage = new NewModelWizardPage1(); addPage(modelPropertiesPage); modelFilePage = new NewModelWizardPage2(selection); addPage(modelFilePage); } public void init(IWorkbench workbench, IStructuredSelection selection) { this.selection = selection; } public boolean performFinish() { IFile result = modelFilePage.createNewFile(); try { IDE.openEditor( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), result); } catch (PartInitException e) { RMBenchPlugin.logError(e); } return result != null; } }
package com.hyty.tree.treejiegou.service; import com.hyty.tree.treejiegou.entity.BusinessModule; import com.hyty.tree.treejiegou.entity.Personnel; import com.hyty.tree.treejiegou.entity.RoleJurisdiction; import java.util.List; /** * Created by Whk on 2019/3/29. * 角色与权限对应关系Service */ public interface RoleJurisdictionService { /** * 新增/修改 角色权限 */ RoleJurisdiction saveRoleJurisdiction(RoleJurisdiction roleJurisdiction) throws Exception; /** * 新增/修改 角色权限关联企业员工_头体对应关系 * * @param personnel * @return * @throws Exception */ Personnel savePersonnel(Personnel personnel) throws Exception; /* *//** * 新增/修改 角色权限与业务模块_头体对应关系 * * @param module * @return *//* BusinessModule savebusinessModule(BusinessModule module) throws Exception;*/ /** * 查询所有 角色权限 * * @return */ List<RoleJurisdiction> selectAll() throws Exception; /** * 根据Id 查询角色权限 * * @param id * @return */ RoleJurisdiction selectRoleJurisdiction(String id) throws Exception; /** * 根据id 查询角色权限与系统角色对应关系 * * @param id * @return */ List<Personnel> selectPersonnel(String id) throws Exception; /** * 根据id 查询角色权限关联业务功能_头体对应关系 * * @param id * @return */ List<BusinessModule> selectBusinessModule(String id) throws Exception; /** * 根据Id 删除角色权限 * * @param id * @return */ boolean deleteRoleJurisdiction(String id) throws Exception; /** * 根据Id 删除角色权限关联企业员工_头体对应关系 * * @param id * @return */ boolean deletePersonnel(String id) throws Exception; /** * 根据Id 删除角色权限与业务功能_头体对应关系 * * @param id * @return * @throws Exception */ boolean deleteModule(String id) throws Exception; }
package com.timebank.controllers; import java.util.Set; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.timebank.data.ActivityDAO; import com.timebank.data.AddressDAO; import com.timebank.data.ServiceDAO; import entities.ServiceOffer; import entities.ServiceOfferActivity; import entities.ServiceOfferDestination; import entities.ServiceOfferOrigin; import entities.ServiceOfferSchedule; import entities.ServiceOfferTx; import entities.ServiceRequest; import entities.ServiceRequestActivity; import entities.ServiceRequestDestination; import entities.ServiceRequestOrigin; import entities.ServiceRequestTimeWindow; import entities.ServiceRequestTx; @RestController public class ServiceControllerImpl implements ServiceControllerInterface { @Autowired ServiceDAO serviceDAO; @Autowired ActivityDAO activityDAO; @Autowired AddressDAO addressDAO; @Override @RequestMapping(path = "/so/create/{timebankId}", method = RequestMethod.POST) public ServiceOffer createServiceOffer(HttpSession session, HttpServletResponse res, @PathVariable int timebankId, @RequestBody String offerJson) { return null; } @Override @RequestMapping(path = "/so/{offerId}/schedule", method = RequestMethod.POST) public ServiceOfferSchedule createServiceOfferSchedule(HttpSession session, HttpServletResponse res, int offerId, String scheduleJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/origin", method = RequestMethod.POST) public ServiceOfferOrigin createServiceOfferOrigin(HttpSession session, HttpServletResponse res, int offerId, int addressId, String originJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/destination", method = RequestMethod.POST) public ServiceOfferDestination createServiceOfferDestination(HttpSession session, HttpServletResponse res, int offerId, int addressId, String destinationJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/tx", method = RequestMethod.POST) public ServiceOfferTx createServiceOfferTx(HttpSession session, HttpServletResponse res, int offerId, String txJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/activity", method = RequestMethod.POST) public ServiceOfferActivity createServiceOfferActivity(HttpSession session, HttpServletResponse res, int offerId, String activityJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/create/{timebankId}", method = RequestMethod.POST) public ServiceRequest createServiceRequest(HttpSession session, HttpServletResponse res, @PathVariable int timebankId, String requestJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/window", method = RequestMethod.POST) public ServiceRequestTimeWindow createServiceRequestTimeWindow(HttpSession session, HttpServletResponse res, int requestId, String windowJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/origin", method = RequestMethod.POST) public ServiceRequestOrigin createServiceRequestOrigin(HttpSession session, HttpServletResponse res, int requestId, int addressId, String originJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/destination", method = RequestMethod.POST) public ServiceRequestDestination createServiceRequestDestination(HttpSession session, HttpServletResponse res, int requestId, int addressId, String destinationJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/tx", method = RequestMethod.POST) public ServiceRequestTx createServiceRequestTx(HttpSession session, HttpServletResponse res, int requestId, String txJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/activity", method = RequestMethod.POST) public ServiceRequestActivity createServiceRequestActivity(HttpSession session, HttpServletResponse res, int requestId, String activityJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}", method = RequestMethod.GET) public ServiceOffer showServiceOffer(HttpSession session, HttpServletResponse res, int offerId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/schedule", method = RequestMethod.GET) public ServiceOfferSchedule showServiceOfferSchedule(HttpSession session, HttpServletResponse res, int offerId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/origin/{originId}", method = RequestMethod.GET) public ServiceOfferOrigin showServiceOfferOrigin(HttpSession session, HttpServletResponse res, int offerId, int originId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/destination/{destinationId}", method = RequestMethod.GET) public ServiceOfferDestination showServiceOfferDestination(HttpSession session, HttpServletResponse res, int offerId, int destinationId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/activity/{activityId}", method = RequestMethod.GET) public ServiceOfferActivity showServiceOfferActivity(HttpSession session, HttpServletResponse res, int offerId, int activityId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}", method = RequestMethod.GET) public ServiceRequest showServiceRequest(HttpSession session, HttpServletResponse res, int requestId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/window/{windowId}", method = RequestMethod.GET) public ServiceRequestTimeWindow showServiceRequestTimeWindow(HttpSession session, HttpServletResponse res, int requestId, int windowId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/origin/{originId}", method = RequestMethod.GET) public ServiceRequestOrigin showServiceRequestOrigin(HttpSession session, HttpServletResponse res, int requestId, int originId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/destination/{destinationId}", method = RequestMethod.GET) public ServiceRequestDestination showServiceRequestDestination(HttpSession session, HttpServletResponse res, int requestId, int destinationId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/activity/{activityId}", method = RequestMethod.GET) public ServiceRequestActivity showServiceRequestActivity(HttpSession session, HttpServletResponse res, int requestId, int activityId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/origin", method = RequestMethod.GET) public Set<ServiceOfferOrigin> getAllServiceOfferOrigins(HttpSession session, HttpServletResponse res, int offerId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/destination", method = RequestMethod.GET) public Set<ServiceOfferDestination> getAllServiceOfferDestinations(HttpSession session, HttpServletResponse res, int offerId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/activity", method = RequestMethod.GET) public Set<ServiceOfferActivity> getAllServiceOfferActivity(HttpSession session, HttpServletResponse res, int offerId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/window", method = RequestMethod.GET) public Set<ServiceRequestTimeWindow> getAllServiceRequestTimeWindows(HttpSession session, HttpServletResponse res, int requestId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/origin", method = RequestMethod.GET) public Set<ServiceRequestOrigin> getAllServiceRequestOrigins(HttpSession session, HttpServletResponse res, int requestId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/destination", method = RequestMethod.GET) public Set<ServiceRequestDestination> getAllServiceRequestDestinations(HttpSession session, HttpServletResponse res, int requestId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/activity", method = RequestMethod.GET) public Set<ServiceRequestActivity> getAllServiceRequestActivity(HttpSession session, HttpServletResponse res, int requestId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/user/{userId}", method = RequestMethod.GET) public Set<ServiceOffer> getServiceOffersByUser(HttpSession session, HttpServletResponse res, int userId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/user/{userId}", method = RequestMethod.GET) public Set<ServiceRequest> getServiceRequestsByUser(HttpSession session, HttpServletResponse res, int userId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/timebank/{timebankId}", method = RequestMethod.GET) public Set<ServiceOffer> getServiceOffersByTimebank(HttpSession session, HttpServletResponse res, int timebankId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/timebank/{timebankId}", method = RequestMethod.GET) public Set<ServiceRequest> getServiceRequestsByTimebank(HttpSession session, HttpServletResponse res, int timebankId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/global", method = RequestMethod.GET) public Set<ServiceOffer> getGlobalServiceOffers(HttpSession session, HttpServletResponse res) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/global", method = RequestMethod.GET) public Set<ServiceRequest> getGlobalServiceRequests(HttpSession session, HttpServletResponse res) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}", method = RequestMethod.PUT) public ServiceOffer updateServiceOffer(HttpSession session, HttpServletResponse res, int offerId, String offerJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/schedule/{scheduleId}", method = RequestMethod.PUT) public ServiceOfferSchedule updateServiceOfferSchedule(HttpSession session, HttpServletResponse res, int offerId, String scheduleJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/origin/{originId}", method = RequestMethod.PUT) public ServiceOfferOrigin updateServiceOfferOrigin(HttpSession session, HttpServletResponse res, int offerId, int addressId, String originJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/destination/{destinationId}", method = RequestMethod.PUT) public ServiceOfferDestination updateServiceOfferDestination(HttpSession session, HttpServletResponse res, int offerId, int addressId, String destinationJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/activity/{activityId}", method = RequestMethod.PUT) public ServiceOfferActivity updateServiceOfferActivity(HttpSession session, HttpServletResponse res, int offerId, int activityId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/providerAccept", method = RequestMethod.GET) public ServiceOfferTx serviceOfferProviderAccept(HttpSession session, HttpServletResponse res, int offerId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/providerReject", method = RequestMethod.GET) public ServiceOfferTx serviceOfferProviderReject(HttpSession session, HttpServletResponse res, int offerId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/recipientComplete", method = RequestMethod.GET) public ServiceOfferTx serviceOfferRecipientComplete(HttpSession session, HttpServletResponse res, int offerId, String txJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/providerComplete", method = RequestMethod.GET) public ServiceOfferTx serviceOfferProviderComplete(HttpSession session, HttpServletResponse res, int offerId, String txJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}", method = RequestMethod.PUT) public ServiceRequest updateServiceRequest(HttpSession session, HttpServletResponse res, int requestId, String requestJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/window/{windowId}", method = RequestMethod.PUT) public ServiceRequestTimeWindow updateServiceRequestTimeWindow(HttpSession session, HttpServletResponse res, int requestId, String windowJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/origin/{originId}", method = RequestMethod.PUT) public ServiceRequestOrigin updateServiceRequestOrigin(HttpSession session, HttpServletResponse res, int requestId, int addressId, String originJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/destination/{destinationId}", method = RequestMethod.PUT) public ServiceRequestDestination updateServiceRequestDestination(HttpSession session, HttpServletResponse res, int requestId, int addressId, String destinationJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/activity/{activityId}", method = RequestMethod.PUT) public ServiceRequestActivity updateServiceRequestActivity(HttpSession session, HttpServletResponse res, int requestId, int activityId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/recipientAccept", method = RequestMethod.GET) public ServiceRequestTx serviceRequestRecipientAccept(HttpSession session, HttpServletResponse res, int requestId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/recipientReject", method = RequestMethod.GET) public ServiceRequestTx serviceRequestRecipientReject(HttpSession session, HttpServletResponse res, int requestId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/recipientComplete", method = RequestMethod.GET) public ServiceRequestTx serviceRequestRecipientComplete(HttpSession session, HttpServletResponse res, int requestId, String txJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/providerComplete", method = RequestMethod.GET) public ServiceRequestTx serviceRequestProviderComplete(HttpSession session, HttpServletResponse res, int requestId, String txJson) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/so/{offerId}/deactivate", method = RequestMethod.GET) public Boolean deactivateServiceOffer(HttpSession session, HttpServletResponse res, int offerId) { // TODO Auto-generated method stub return null; } @Override @RequestMapping(path = "/sr/{requestId}/deactivate", method = RequestMethod.GET) public Boolean deactivateServiceRequest(HttpSession session, HttpServletResponse res, int requestId) { // TODO Auto-generated method stub return null; } }
package com.gmail.at.telchuev.leitnerboxlite; import android.app.backup.BackupHelper; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; public class Utility { // DATA RETRIEVAL public static ArrayList<String> getNonEmptyBoxes(){ ArrayList<String> result = new ArrayList<>(); SQLiteDatabase db = new DBHelper().getWritableDatabase(); String query = "SELECT DISTINCT " + DBHelper.COL_BOX_NMB + " FROM " + DBHelper.TABLE_NAME_MAIN + " ORDER BY " + DBHelper.COL_BOX_NMB + DBHelper.ASC; Cursor c = db.rawQuery(query, null); if(c.moveToFirst()){ do{ result.add(c.getString(c.getColumnIndex(DBHelper.COL_BOX_NMB))); }while (c.moveToNext()); } c.close(); db.close(); return result; } public static ArrayList<Entry> getBoxVocabulary(String boxNmb){ return getVocabulary(DBHelper.COL_BOX_NMB + " = " + boxNmb); } public static int getTotalWordsCount(){ int result = 0; SQLiteDatabase db = new DBHelper().getWritableDatabase(); String query = "SELECT COUNT(" + DBHelper.COL_ID + ")" + " AS " + DBHelper.COL_ID + " FROM " + DBHelper.TABLE_NAME_MAIN; Cursor c = db.rawQuery(query, null); if(c.moveToFirst()){ result = c.getInt(c.getColumnIndex(DBHelper.COL_ID)); } c.close(); db.close(); return result; } public static ArrayList<Entry> getLowestBoxVocabulary(){ ArrayList<Entry> result = new ArrayList<>(); SQLiteDatabase db = new DBHelper().getWritableDatabase(); String query = "SELECT MIN(" + DBHelper.COL_BOX_NMB + ") AS " + DBHelper.COL_BOX_NMB + " FROM " + DBHelper.TABLE_NAME_MAIN; Cursor c = db.rawQuery(query, null); if(!c.moveToFirst()){ return result; } String boxNmb = c.getString(c.getColumnIndex(DBHelper.COL_BOX_NMB)); c.close(); db.close(); return getVocabulary(DBHelper.COL_BOX_NMB + " = " + boxNmb); } public static ArrayList<Entry> getVocabulary(String selection){ ArrayList<Entry> result = new ArrayList<>(); SQLiteDatabase db = new DBHelper().getWritableDatabase(); String query = "SELECT * FROM " + DBHelper.TABLE_NAME_MAIN + (selection == null ? "" : " WHERE " + selection) + " ORDER BY " + DBHelper.COL_WORD + DBHelper.ASC; Cursor c = db.rawQuery(query, null); if(c.moveToFirst()){ do{ result.add(new Entry(c)); }while (c.moveToNext()); } c.close(); db.close(); return result; } public static ArrayList<String> getSpinnerData(){ ArrayList<String> boxes = new ArrayList<>(); for(int i = Entry.BOX_NMB_MIN; i <= Entry.BOX_NMB_MAX; i++){ boxes.add(""+i); } return boxes; } // DATA MANIPULATION public static void insertData(ContentValues cv){ SQLiteDatabase db = new DBHelper().getWritableDatabase(); db.insert(DBHelper.TABLE_NAME_MAIN, DBHelper.COL_NULL, cv); db.close(); } public static void updateData(ContentValues cv, String selection, String[] selectionArgs){ SQLiteDatabase db = new DBHelper().getWritableDatabase(); db.update(DBHelper.TABLE_NAME_MAIN, cv, selection, selectionArgs); db.close(); } public static void deleteData(String selection, String[] selectionArgs){ SQLiteDatabase db = new DBHelper().getWritableDatabase(); db.delete(DBHelper.TABLE_NAME_MAIN, selection, selectionArgs); db.close(); } public static void deleteAll(){ SQLiteDatabase db = new DBHelper().getWritableDatabase(); db.delete(DBHelper.TABLE_NAME_MAIN, null, null); db.close(); } public static void importFile(){ //READ WORDS FROM FILE BufferedReader reader = null; boolean isWord = true; ArrayList<Word> newWords = new ArrayList<>(); try { reader = new BufferedReader(new InputStreamReader(MyApp.getAppContext().getAssets().open("Goethe B1.txt"))); String line; Word w = null; String s = ""; while ((line = reader.readLine()) != null) { if(line.isEmpty()) { s = s.substring(0, s.length()-1); if(isWord) { w = new Word(); newWords.add(w); w.word = s; }else { w.example = s; } s = ""; isWord = !isWord; }else { s = s + line + "\n"; } } } catch (IOException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } // GET EXISTING WORDS ArrayList<String> existingWords = new ArrayList<>(); SQLiteDatabase db = new DBHelper().getWritableDatabase(); String query = "SELECT " + DBHelper.COL_WORD + " FROM " + DBHelper.TABLE_NAME_MAIN; Cursor c = db.rawQuery(query, null); if(c.moveToFirst()){ do{ existingWords.add(c.getString(c.getColumnIndex(DBHelper.COL_WORD))); }while (c.moveToNext()); } c.close(); db.close(); // ADD TO DB NON-EXISTING WORDS for(Word w: newWords){ if(!existingWords.contains(w.word)){ Entry e = new Entry(); e.setWord(w.word); e.setExample(w.example); e.toDB(); Log.d(MyApp.TAG, "Added: " + e.getWord()); } } } // HELPERS public static class Word { public String word; public String example; } public static boolean empty(String s){ return s == null || s.isEmpty(); } }
package com.example.springdemo.Controller; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @company 宏图 * @User Kodak * @create 2019-02-20 -21:04 */ @RestController public class hellcontroller { @RequestMapping("/hello") public String hello(){ return "springboot2.0"; } }
package com.gcipriano.katas.salestaxes.model.product.catalog; import java.util.ArrayList; import java.util.List; public class InMemoryExemptedProductCatalog implements ExemptedProductCatalog { private List<String> exemptedProducts = new ArrayList<>(); public InMemoryExemptedProductCatalog(List<String> exemptedProducts) { this.exemptedProducts = exemptedProducts; } @Override public boolean isExempted(String description) { return exemptedProducts.contains(description); } }
package com.qihoo.finance.chronus.core.task; import com.qihoo.finance.chronus.metadata.api.common.PageResult; import com.qihoo.finance.chronus.metadata.api.task.entity.TaskEntity; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** * Created by xiongpu on 2018/11/5. */ public interface TaskService { TaskEntity selectTaskInfoByTaskName(String taskName); PageResult<TaskEntity> selectListByPage(TaskEntity taskEntity, List<String> dealSysCodes); List<TaskEntity> selectTaskInfoByCluster(String cluster); /** * 获取所有任务,不区分集群 * * @return */ List<TaskEntity> selectAllTaskInfo(); Map<String, TaskEntity> selectTaskInfoByTaskNames(Collection<String> taskNameSet); Set<String> existTaskByTag(String tagName); void update(TaskEntity taskEntity); void insert(TaskEntity taskEntity); void delete(String taskName); TaskEntity selectById(String id); void start(String taskName); void stop(String taskName); List<TaskEntity> selectTaskInfoBySysCode(String dealSysCode); }
package com.linkedbook.dao; import com.linkedbook.dto.area.selectArea.SelectAreaOutput; import com.linkedbook.entity.AreaDB; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface AreaRepository extends JpaRepository<AreaDB, Integer> { @Query("select new com.linkedbook.dto.area.selectArea.SelectAreaOutput(a.id, a.dongmyeonri, concat(a.sido, ' ', a.sigungu, ' ', a.dongmyeonri))" + " from AreaDB a where concat(a.sido, ' ', a.sigungu, ' ', a.dongmyeonri) like %?1%") Page<SelectAreaOutput> findByArea(String search, Pageable pageable); }
package StreamAPI; import java.util.ArrayList; import java.util.Collections; import java.util.stream.Stream; public class Exer { public static void main(String[] args) { ArrayList<String> one = new ArrayList<String>(); ArrayList<String> two = new ArrayList<String>(); Collections.addAll(one, "迪丽热巴","宋远桥","苏星河","石破天","石中玉","老子","庄子","洪七公"); Collections.addAll(two, "古力娜扎","张无忌","赵丽颖","张三丰","尼古拉斯","张天爱","张二狗"); //1.第一个队伍只要名字为3个字的成员姓名;存储到一个新集合中。 Stream<String> s1 = one.stream() .filter(s->s.length() == 3) //2.第一个队伍筛选之后只要前3个人;存储到一个新集合中。 .limit(3); //3.第二个队伍只要姓张的成员姓名;存储到一个新集合中。 Stream<String> s2 = two.stream() .filter(s->s.startsWith("张")) //4. 第二个队伍筛选之后不要前2个人;存储到一个新集合中。 .skip(2); //5. 将两个队伍合并为一个队伍;存储到一个新集合中。 Stream.concat(s1, s2) //6. 根据姓名创建 Person 对象;存储到一个新集合中。 .map(name->new Person(name)) //7. 打印整个队伍的Person对象信息。 .forEach(t->System.out.println(t)); } } class Person{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public Person(String name) { super(); this.name = name; } public Person() { super(); } @Override public String toString() { return "Person [name=" + name + "]"; } }
package com.tencent.mm.plugin.mmsight.ui; import com.tencent.mm.plugin.mmsight.model.j; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; class SightCaptureUI$1 implements Runnable { final /* synthetic */ long jEc; final /* synthetic */ SightCaptureUI lqr; SightCaptureUI$1(SightCaptureUI sightCaptureUI, long j) { this.lqr = sightCaptureUI; this.jEc = j; } public final void run() { x.i("MicroMsg.SightCaptureUI", "connect cost %sms", new Object[]{Long.valueOf(bi.bI(this.jEc))}); j.c(SightCaptureUI.a(this.lqr).lem); SightCaptureUI.b(this.lqr); } }
package SebastianMiklaszewski.Excercises.Core.Model; import SebastianMiklaszewski.Excercises.Core.Exception.NotEnoughMoneyException; import SebastianMiklaszewski.Excercises.Core.Factory.WalletFactoryInterface; import SebastianMiklaszewski.Excercises.Core.ValueObject.MoneyValue; import SebastianMiklaszewski.Excercises.Infrastructure.Entity.Wallet; import SebastianMiklaszewski.Excercises.Infrastructure.Factory.WalletFactory; public class WithdrawMoneyFromWallet { private final WalletFactoryInterface walletFactory; private Wallet wallet; public WithdrawMoneyFromWallet() throws NotEnoughMoneyException { this.walletFactory = new WalletFactory(); this.initWallet(); } public void withdrawMoneyFromWallet(MoneyValue toWithdraw) throws NotEnoughMoneyException { this.wallet.withdraw(toWithdraw); } private void initWallet() throws NotEnoughMoneyException { this.wallet = this.walletFactory.createWalletWithFiveUsd(); } }
package com.beiyelin.projectportal.service.impl; import com.beiyelin.account.bean.AccountQuery; import com.beiyelin.account.entity.Account; import com.beiyelin.account.entity.EmbeddableAccount; import com.beiyelin.common.bean.JwtUser; import com.beiyelin.common.reqbody.PageReq; import com.beiyelin.common.resbody.PageResp; import com.beiyelin.common.utils.StrUtils; import com.beiyelin.commonsql.jpa.BaseDomainCRUDServiceImpl; import com.beiyelin.commonsql.jpa.PageImpl; import com.beiyelin.commonsql.utils.QueryUtils; import com.beiyelin.organization.bean.OrganizationQuery; import com.beiyelin.organization.entity.Organization; import com.beiyelin.person.bean.PersonQuery; import com.beiyelin.person.entity.Person; import com.beiyelin.projectportal.bean.BorrowMoneyQualificationPoolQuery; import com.beiyelin.projectportal.bean.ProjectAuthQuery; import com.beiyelin.projectportal.constant.ProjectAuthConstant; import com.beiyelin.projectportal.entity.BorrowMoneyQualificationPool; import com.beiyelin.projectportal.entity.EmbeddableProject; import com.beiyelin.projectportal.entity.ProjectAuth; import com.beiyelin.projectportal.repository.BorrowMoneyQualificationPoolRepository; import com.beiyelin.projectportal.repository.ProjectAuthRepository; import com.beiyelin.projectportal.service.ProjectAuthService; import com.google.common.base.Joiner; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.jpa.domain.Specification; import org.springframework.security.access.method.P; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.beiyelin.common.constant.MessageCaption.MESSAGE_PARAM_IS_NULL; import static com.beiyelin.common.utils.CheckUtils.notEmpty; import static com.beiyelin.common.utils.CheckUtils.notNull; import static com.beiyelin.projectportal.constant.ProjectAuthConstant.ALL_ALLOW; import static java.lang.String.format; /** * @Description: * @Author: newmann * @Date: Created in 22:35 2018-02-11 */ @Service("projectAuthService") @Slf4j public class ProjectAuthServiceImpl extends BaseDomainCRUDServiceImpl<ProjectAuth> implements ProjectAuthService { private ProjectAuthRepository projectAuthRepository; @Autowired public void setProjectAuthRepository(ProjectAuthRepository repository) { super.setSuperRepository(repository); this.projectAuthRepository = repository; } /** * 实体管理对象 */ @PersistenceContext private EntityManager em; @Override public PageResp<ProjectAuth> fetchByQuery(ProjectAuthQuery query, PageReq pageReq) { notNull(query,MESSAGE_PARAM_IS_NULL); notNull(pageReq,MESSAGE_PARAM_IS_NULL); log.info(format("开始查询,查询条件:%s,分页条件:%s",query.toString(),pageReq.toString())); JwtUser currentUser = getSessionUser(); StringBuilder countSelectSql = new StringBuilder(); countSelectSql.append("select count(*) from ProjectAuth a, Project pj,Account at "); // + // "where a.id = pa.project.projectId and " + // " (pa.account.accountId = %s or pa.account.accountId = %s) ", // ProjectAuthConstant.ALL_ALLOW,currentUser.getId())); int firstIndex = (pageReq.getPage()-1)* pageReq.getPageSize(); StringBuilder selectSql = new StringBuilder(); selectSql.append(" select a from ProjectAuth a, Project pj, Account at "); // "where a.id = pa.project.projectId and " + // " (pa.account.accountId = %s or pa.account.accountId = %s) ", // ProjectAuthConstant.ALL_ALLOW,currentUser.getId())); Map<String,Object> params = new HashMap<>(); StringBuilder whereSql = new StringBuilder(); /** * 符合条件: * 1、项目是自己创建的 * 2、该项目是允许所有人开放的 * * 是自己创建的不一定可见,因为: * 一个项目开始对自己可见,在引入一批其他用胡后,没有这个项目的可见权限了,这时候原来自己引入的其他用户记录也是不可见的。 */ whereSql.append(format(" where (a.projectId = pj.id) and (a.accountId = at.id) " + " ((a.accountId = '%s') " + " or (pj.createAction.createId = '%s')) ", ALL_ALLOW,currentUser.getId(),currentUser.getId())); if (!StrUtils.isBlank(query.getProjectCode())){ whereSql.append(" and (pj.projectCode like :projectCode) "); params.put("projectCode",StrUtils.genQueryLikeContent(query.getProjectCode())); } if (!StrUtils.isBlank(query.getProjectName())){ whereSql.append(" and (pj.projectName like :projectName) "); params.put("projectName",StrUtils.genQueryLikeContent(query.getProjectName())); } if (!StrUtils.isBlank(query.getAccountCode())){ whereSql.append(" and (at.accountCode like :accountCode) "); params.put("accountCode",StrUtils.genQueryLikeContent(query.getAccountCode())); } if (!StrUtils.isBlank(query.getAccountName())){ whereSql.append(" and (at.accountName like :accountName) "); params.put("accountName",StrUtils.genQueryLikeContent(query.getAccountName())); } if (query.getModifyDateBegin()>0) { whereSql.append(" and (a.modifyAction.modifyDateTime >= :modifyDateBegin) "); params.put("modifyDateBegin",query.getModifyDateBegin()); } if (query.getModifyDateEnd()>0) { whereSql.append(" and (a.modifyAction.modifyDateTime <= :modifyDateEnd) "); params.put("modifyDateEnd",query.getModifyDateEnd()); } String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString(); Query countQuery = this.em.createQuery(countSql,Long.class); QueryUtils.setParameters(countQuery,params); Long count = (Long) countQuery.getSingleResult(); String resultSQL = new StringBuilder().append(selectSql).append(whereSql).toString(); Query resultQuery = this.em.createQuery(resultSQL,ProjectAuth.class); QueryUtils.setParameters(resultQuery,params); resultQuery.setFirstResult(firstIndex); resultQuery.setMaxResults(pageReq.getPageSize()); List<ProjectAuth> resultList = resultQuery.getResultList(); Page<ProjectAuth> resultPage = new PageImpl<ProjectAuth>(resultList, pageReq.toPageable(), count); log.info("Query result:" + resultPage.getContent().toString()); log.info(format("查询结束。条数为:%d",resultPage.getTotalElements())); return new PageResp<>(resultPage); // Specification<ProjectAuth> querySpec = new Specification<ProjectAuth>(){ // @Override // public Predicate toPredicate(Root<ProjectAuth> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) { // List<Predicate> predicates = new ArrayList<>(); // // // //代码 // if (!StrUtils.isEmpty(query.getProjectCode())){ // predicates.add(criteriaBuilder.like(root.get("project").get("porjectCode"),"%" + query.getProjectCode()+"%")); // } // //名称 // if (!StrUtils.isEmpty(query.getProjectName())){ // predicates.add(criteriaBuilder.equal(root.get("project").get("projectName"), query.getProjectName())); // } // // if (!StrUtils.isEmpty(query.getAccountCode())){ // predicates.add(criteriaBuilder.like(root.get("account").get("accountCode"),"%" + query.getAccountCode()+"%")); // } // //名称 // if (!StrUtils.isEmpty(query.getAccountName())){ // predicates.add(criteriaBuilder.equal(root.get("account").get("accountName"), query.getAccountName())); // } // // // if (query.getModifyDateBegin()>0) { // predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("modifyAction").get("modifyDateTime"),query.getModifyDateBegin())); // // } // if (query.getModifyDateEnd()>0) { // predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("modifyAction").get("modifyDateTime"),query.getModifyDateEnd())); // // } // // return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()])); // } // }; // Page<ProjectAuth> findEntity = projectAuthRepository.findAll(querySpec,pageReq.toPageable()); // log.info(format("查询结束。条数为:%d",findEntity.getTotalElements())); // return new PageResp<>(findEntity); } @Override public List<ProjectAuth> batchAdd(List<ProjectAuth> pools) { notNull(pools,MESSAGE_PARAM_IS_NULL); log.info(format("开始批量添加,待添加条数:%d ",pools.size())); List<ProjectAuth> result = new ArrayList<>(); pools.stream().forEach(item->{result.add(super.create(item));}); return result; } @Override public PageResp<Account> findAccountAvailablePools(String projectId, AccountQuery accountQuery, PageReq pageReq) { notEmpty(projectId,MESSAGE_PARAM_IS_NULL); notNull(accountQuery,MESSAGE_PARAM_IS_NULL); notNull(pageReq,MESSAGE_PARAM_IS_NULL); log.info(format("开始查询可用账户,projectId:%s, 查询条件:%s,分页条件:%s",projectId, accountQuery.toString(),pageReq.toString())); int firstIndex = (pageReq.getPage()-1)* pageReq.getPageSize(); StringBuilder countSelectSql = new StringBuilder(); countSelectSql.append("select count(*) from Account a "); StringBuilder selectSql = new StringBuilder(); selectSql.append("from Account a " ); Map<String,Object> params = new HashMap<>(); StringBuilder whereSql = new StringBuilder(); whereSql.append(format(" where (a.id not in (select accountId from ProjectAuth where projectId = '%s')) ",projectId)); if (!StrUtils.isBlank(accountQuery.getUsername())){ whereSql.append(" and a.username like :code "); params.put("code",StrUtils.genQueryLikeContent(accountQuery.getUsername())); } if (!StrUtils.isBlank(accountQuery.getFullName())){ whereSql.append(" and a.fullName like :fullName "); params.put("name",StrUtils.genQueryLikeContent(accountQuery.getFullName())); } if (!StrUtils.isBlank(accountQuery.getNickname())){ whereSql.append(" and a.nickName like :nickName "); params.put("simpleName",StrUtils.genQueryLikeContent(accountQuery.getNickname())); } if (accountQuery.getModifyDateBegin()>0) { whereSql.append(" and a.modifyAction.modifyDateTime >= :modifyDateBegin "); params.put("modifyDateBegin",accountQuery.getModifyDateBegin()); } if (accountQuery.getModifyDateEnd()>0) { whereSql.append(" and a.modifyAction.modifyDateTime <= :modifyDateEnd "); params.put("modifyDateEnd",accountQuery.getModifyDateEnd()); } if (!accountQuery.getStatus().isEmpty()){ whereSql.append(" and a.status in (:status) "); params.put("status",accountQuery.getStatus()); } String countSql = new StringBuilder().append(countSelectSql).append(whereSql).toString(); Query countQuery = this.em.createQuery(countSql,Long.class); QueryUtils.setParameters(countQuery,params); Long count = (Long) countQuery.getSingleResult(); String resultSQL = new StringBuilder().append(selectSql).append(whereSql).toString(); Query resultQuery = this.em.createQuery(resultSQL,Account.class); QueryUtils.setParameters(resultQuery,params); resultQuery.setFirstResult(firstIndex); resultQuery.setMaxResults(pageReq.getPageSize()); List<Account> resultList = resultQuery.getResultList(); Page<Account> resultPage = new PageImpl<Account>(resultList, pageReq.toPageable(), count); log.info(format("查询结束。条数为:%d",resultPage.getTotalElements())); return new PageResp<>(resultPage); } @Override public List<Account> fetchAccountsByProjectId(String projectId) { notEmpty(projectId,MESSAGE_PARAM_IS_NULL); log.info(format("开始查询项目对应的账户,projectId:%s。 ",projectId)); List<Account> resultList = projectAuthRepository.fetchAccountsByProjectId(projectId); log.info(format("查询结束。条数为:%d",resultList.size())); return resultList; } @Override public boolean checkAllowAllByProjectId(String projectId) { notEmpty(projectId,MESSAGE_PARAM_IS_NULL); log.info(format("开始查询项目是否开放可见性权限,projectId:%s。 ",projectId)); ProjectAuth item = projectAuthRepository.fetchAllowAllByProjectId(projectId); boolean result; if (item == null) { result = false; }else{ result =item.getAccountId().equals(ALL_ALLOW); } if (result) { log.info(format("查询结束,项目%s 开放了可见性权限。",projectId)); }else { log.info(format("查询结束,项目%s 没有开放了可见性权限。",projectId)); } return result; } @Override @Transactional public boolean deleteByProjectIdAndAccountId(String projectId, String accountId) { notEmpty(projectId,MESSAGE_PARAM_IS_NULL); notEmpty(accountId,MESSAGE_PARAM_IS_NULL); log.info(format("开始删除对应记录,projectId:%s,accountId:%s。 ",projectId, accountId)); Long result = projectAuthRepository.deleteAllByProjectIdAndAccountId(projectId,accountId); log.info(format("正确删除 %d 条记录。", result)); //不管删除多少条,只要正确执行,就返回为true; return true; } @Override @Transactional public ProjectAuth enableAllowAll(String projectId) { notEmpty(projectId,MESSAGE_PARAM_IS_NULL); log.info(format("开始设置项目对所有人开放,projectId:%s。 ",projectId)); ProjectAuth entity = new ProjectAuth(); entity.setProjectId( projectId); entity.setAccountId(ProjectAuthConstant.ALL_ALLOW); // EmbeddableProject ep = new EmbeddableProject(); // ep.setProjectId(projectId); // entity.setProject(ep); // // EmbeddableAccount ea = new EmbeddableAccount(); // ea.setAccountId(ProjectAuthConstant.ALL_ALLOW); // entity.setAccount(ea); ProjectAuth result = super.create(entity); log.info(format("设置项目对所有人开放成功,projectId:%s。 ",projectId)); return result; } @Override @Transactional public boolean disableAllowAll(String projectId) { notEmpty(projectId,MESSAGE_PARAM_IS_NULL); log.info(format("开始取消项目对所有人开放,projectId:%s。 ",projectId)); Long result = projectAuthRepository.deleteAllByProjectIdAndAccountId(projectId,ProjectAuthConstant.ALL_ALLOW); log.info(format("取消项目对所有人开放成功,projectId:%s。 ",projectId)); return true; } }
import java.util.Scanner; import java.math.BigInteger; // at // least // I've // got // some // comments public class Mission1_noRun { public static void main(String[] args) { System.out.println("let's divide by zero!" + 1/0); } }
package acs; import static org.assertj.core.api.Assertions.assertThat; import java.util.Date; import java.util.HashMap; import javax.annotation.PostConstruct; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.web.client.RestTemplate; import acs.boundary.ActionBoundary; import acs.boundary.ElementBoundary; import acs.boundary.UserBoundary; import acs.boundary.boundaryUtils.Element; import acs.boundary.boundaryUtils.ElementId; import acs.boundary.boundaryUtils.InvokedBy; import acs.boundary.boundaryUtils.Location; import acs.boundary.boundaryUtils.NewUserDetails; import acs.boundary.boundaryUtils.UserId; import acs.data.UserRole; @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) public class ActionTests { private int port; private String url; private String userEmail; private String domain; private String adminEmail; private String managerEmail; private RestTemplate restTemplate; @LocalServerPort public void setPort(int port) { this.port = port; } @Value("${spring.application.name:2020b.daniel.zusev}") public void setProjectName(String projectName) { this.domain = projectName; this.userEmail = "player@" + this.domain + ".com"; this.adminEmail = "admin@" + this.domain + ".com"; this.managerEmail = "manager@" + this.domain + ".com"; } @PostConstruct public void init() { this.url = "http://localhost:" + this.port + "/acs"; this.restTemplate = new RestTemplate(); // Create Admin NewUserDetails admin = new NewUserDetails(); admin.setAvatar(":)"); admin.setRole(UserRole.ADMIN); admin.setEmail(this.adminEmail); admin.setUsername("admin"); this.restTemplate.postForObject(this.url + "/users", admin, UserBoundary.class); // Create Manager NewUserDetails manager = new NewUserDetails(); manager.setAvatar(":)"); manager.setRole(UserRole.MANAGER); manager.setEmail(this.managerEmail); manager.setUsername("manager"); this.restTemplate.postForObject(this.url + "/users", manager, UserBoundary.class); // Create User NewUserDetails user = new NewUserDetails(); user.setAvatar(":)"); user.setRole(UserRole.PLAYER); user.setEmail(this.userEmail); user.setUsername("daniel"); this.restTemplate.postForObject(this.url + "/users", user, UserBoundary.class); } @BeforeEach public void setup() { } @AfterEach public void teardown() { this.restTemplate .delete(this.url + "/admin/actions/{domain}/{email}",domain,adminEmail); this.restTemplate .delete(this.url + "/admin/elements/{domain}/{email}",domain,adminEmail); this.restTemplate .delete(this.url + "/admin/users/{domain}/{email}", this.domain, this.adminEmail); } @Test public void testInvokeNewActionAndValidateTheDatabaseContainsASingleAction(){ ElementBoundary elementBoundary = new ElementBoundary(null, "regular", true, "dugma", new Date(), null, new Location(25.3, 13.2), new HashMap<String,Object>()); elementBoundary = this.restTemplate.postForObject(this.url + "/elements/{managerDomain}/{managerEmail}" , elementBoundary, ElementBoundary.class, this.domain, this.managerEmail); ActionBoundary action = new ActionBoundary(); action.setElement(new Element(new ElementId(this.domain,elementBoundary.getElementId().getId()))); action.setType("get_info_garden"); action.setInvokedBy(new InvokedBy(new UserId(this.domain, this.userEmail))); action.setActionAttributes(new HashMap<String, Object>()); this.restTemplate.postForObject(this.url + "/actions",action,Object.class); ActionBoundary[] actions = this.restTemplate.getForObject(this.url + "/admin/actions/{domain}/{email}", ActionBoundary[].class,this.domain,this.adminEmail); assertThat(actions).hasSize(1); } @Test public void testGetAllActionsAndValidateTheDatabaseIsEmpty() { ActionBoundary[] actions = this.restTemplate.getForObject(this.url + "/admin/actions/{domain}/{email}", ActionBoundary[].class,domain,adminEmail); assertThat(actions).isEmpty(); } }
import java.awt.Color; import java.awt.Graphics; import javax.swing.Timer; public class Ball { public int x = 220, y = 100; public int xspeed = 4; public int yspeed = 3; public int width = 20, height = 20; public int mapwidth = 600, mapheight = 600; public void render(Graphics g) { // System.out.println("Ball render"); g.setColor(Color.RED); g.fillOval(x, y, width, height); } public void update() { this.x += this.xspeed; this.y += this.yspeed; // System.out.println("[" + x + "," + y + "]"); } public void edges(){ if(y > mapheight){ yspeed *= -1; } if(y < 0){ yspeed *= -1; } if(x > mapwidth + 10){ xspeed *= -1; } if(x < 0){ xspeed *= -1; } } }
package oriorihuela; import static org.junit.Assert.*; import org.junit.Test; public class CollatzTest { @Test public void collatzTest() { assertEquals("3->10->5->16->8->4->2->1", Collatz.collatz(3)); assertEquals("4->2->1", Collatz.collatz(4)); assertEquals("2->1", Collatz.collatz(2)); } }
package com.lin.redis; /** * * 用户登录或者退出状态直接保存在redis里 * <p>ClassName: UserRedis.java<p> * <p>Description<p> * @author linzj * @createTime 2016年4月1日 下午4:19:08 */ public interface UserRedis { /** * 添加或者更新redis中的用户 * @param account */ public void addOrUpdate(String account); /** * 根据用户id获取用户对象 * @param account * @return */ public boolean loadUser(String account); /** * 根据id删除redis中的用户 * @param account */ public void deleteUserById(String account); }
package org.openfuxml.renderer.word; import org.openfuxml.content.ofx.Document; import org.openfuxml.factory.ConfigurationProviderFacotry; import org.openfuxml.interfaces.configuration.ConfigurationProvider; import org.openfuxml.media.cross.NoOpCrossMediaManager; import org.openfuxml.renderer.word.structure.WordDocumentRenderer; import org.openfuxml.util.configuration.settings.OfxDefaultSettingsManager; import net.sf.exlp.util.xml.JaxbUtil; public class TestWordDocumentRenderer extends AbstractTestWordRenderer{ public static void main(String[] args) throws Exception{ int lvl = 0; TestWordDocumentRenderer twdr = new TestWordDocumentRenderer(); OfxDefaultSettingsManager dsm = new OfxDefaultSettingsManager(); NoOpCrossMediaManager cmm = new NoOpCrossMediaManager(); ConfigurationProvider cp = ConfigurationProviderFacotry.build(cmm, dsm); WordDocumentRenderer wdr = new WordDocumentRenderer(cp, lvl); Document d = twdr.buildDocument(); // XML Ausgabe // JaxbUtil.info(d); wdr.renderer(wdr.getDocument(), d); wdr.writeDocument(wdr.getDocument()); } }
package com.mysql.cj.exceptions; public class DataReadException extends CJException { private static final long serialVersionUID = 1684265521187171525L; public DataReadException(Exception cause) { super(cause); setSQLState("S1009"); } public DataReadException(String msg) { super(msg); setSQLState("S1009"); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\exceptions\DataReadException.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.cs4125.bookingapp.services; import com.cs4125.bookingapp.model.entities.Booking; import com.cs4125.bookingapp.model.entities.Route; import org.springframework.stereotype.Service; import java.util.List; @Service public interface BookingService { String searchBooking(int id); List<String> searchAllBookings(int userid); String addBooking(Route r, Booking b, String discountCode); String updateTransaction(Booking b); String cancelBooking(Booking b); }
package com.tencent.mm.plugin.exdevice.ui; import com.tencent.mm.plugin.exdevice.ui.ExdeviceDeviceProfileUI.4.1; class ExdeviceDeviceProfileUI$4$1$1 implements Runnable { final /* synthetic */ 1 iCR; ExdeviceDeviceProfileUI$4$1$1(1 1) { this.iCR = 1; } public final void run() { this.iCR.hmi.dismiss(); } }
package edu.nyu.cs.aeoi.twitterapi; import org.apache.log4j.Logger; import twitter4j.Query; import twitter4j.QueryResult; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; /** * Demo using twitter4j.properties with maven to get recent tweets * */ public class DemoTestGetTweets { private static Logger log = Logger.getLogger(DemoTestGetTweets.class .getName()); public static void main(String[] args) throws TwitterException { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query("software engineer salary"); QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { log.info("@" + status.getUser().getScreenName() + ":" + status.getText()); } } }
package br.com.caelum.financas.teste; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import br.com.caelum.financas.modelo.Conta; import br.com.caelum.financas.modelo.Movimentacao; import br.com.caelum.financas.modelo.TipoMovimentacao; import br.com.caelum.financas.util.JPAUtil; public class TeteJPQL { public static void main(String[] args) { EntityManager entityManager = new JPAUtil().getEntityManager(); entityManager.getTransaction().begin(); Conta conta = new Conta(2); TypedQuery<Movimentacao> query = entityManager.createQuery("SELECT m FROM Movimentacao m WHERE m.conta = :pConta AND m.tipo = :pTipo order by m.valor desc", Movimentacao.class); query.setParameter("pConta", conta); query.setParameter("pTipo", TipoMovimentacao.SAIDA); List<Movimentacao> lista = query.getResultList(); for (Movimentacao movimentacao : lista) { System.out.println(movimentacao); } entityManager.getTransaction().commit(); entityManager.close(); } }
package kphai.noobswe.com.firebaselab.activity; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.CardView; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import kphai.noobswe.com.firebaselab.R; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class LoginActivity extends AppCompatActivity { private EditText edtEmail; private EditText edtPassword; private Button btnLogin; private ProgressBar mProgressBar; private CardView cardView; private FirebaseAuth auth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); auth = FirebaseAuth.getInstance(); if (auth.getCurrentUser() != null) { startActivity(new Intent(LoginActivity.this, MainActivity.class)); finish(); } setContentView(R.layout.activity_login); bindView(); initializes(); } private void bindView() { cardView = (CardView) findViewById(R.id.cardView); edtEmail = (EditText) findViewById(R.id.edtEmail); edtPassword = (EditText) findViewById(R.id.edtPassword); btnLogin = (Button) findViewById(R.id.btnLogin); mProgressBar = (ProgressBar) findViewById(R.id.progressBar); mProgressBar.setVisibility(View.GONE); } private void initializes() { auth = FirebaseAuth.getInstance(); btnLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doLogin(); } }); } private void doLogin() { String strEmail = edtEmail.getText().toString().trim(); final String strPassword = edtPassword.getText().toString().trim(); if (TextUtils.isEmpty(strEmail)) { Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_LONG).show(); return; } if (TextUtils.isEmpty(strPassword)) { Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_LONG).show(); return; } cardView.setVisibility(View.GONE); mProgressBar.setVisibility(View.VISIBLE); //authenticate user auth.signInWithEmailAndPassword(strEmail, strPassword).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { mProgressBar.setVisibility(View.GONE); if (!task.isSuccessful()) { cardView.setVisibility(View.VISIBLE); // there was an error if (strPassword.length() < 6) { Toast.makeText(LoginActivity.this, "Password < 6", Toast.LENGTH_LONG).show(); } else { Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_LONG).show(); } } else { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); finish(); } } }); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } }//end of LoginActivity
package com.axis.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.axis.coolcat.R; import com.axis.util.Constant; /** * @author lq 2013-6-1 lq2625304@gmail.com */ public class FrameLocalMusicFragment extends Fragment { private final String TAG = this.getClass().getName(); private final Fragment fragment = new TrackBrowserFragment(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.frame_for_nested_fragment, container, false); return rootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle args = new Bundle(); args.putInt(Constant.PARENT, Constant.START_FROM_LOCAL_MUSIC); fragment.setArguments(args); // Log.i(TAG , "我执行了一遍"); getChildFragmentManager() .beginTransaction() .add(R.id.frame_for_nested_fragment, fragment) .commit(); } /** * Called when the hidden state (as returned by {@link #isHidden()} of * the fragment has changed. Fragments start out not hidden; this will * be called whenever the fragment changes state from that. * * @param hidden True if the fragment is now hidden, false if it is not * visible. */ @Override public void onHiddenChanged(boolean hidden) { // Log.i(TAG, "================我执行了"); if(hidden) { // Log.i(TAG, "================我隐藏了"); getChildFragmentManager().beginTransaction().hide(fragment).commit(); }else { // Log.i(TAG, "================我现身了"); getChildFragmentManager().beginTransaction().show(fragment).commit(); } super.onHiddenChanged(hidden); } @Override public void onSaveInstanceState(Bundle outState) { } }
package br.vianna.aula.appteatro.domain.entities; import br.vianna.aula.appteatro.domain.entities.abstracts.Ingresso; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; @Entity @Table(name = "ingresso_teatro") @PrimaryKeyJoinColumn(name="pk_ingresso_teatro",referencedColumnName = "id") public class IngressoTeatro extends Ingresso implements Serializable { private String setor; @Column(length = 10) private String codigoCadeira; public IngressoTeatro() { } public String getSetor() { return setor; } public void setSetor(String setor) { this.setor = setor; } public String getCodigoCadeira() { return codigoCadeira; } public void setCodigoCadeira(String codigoCadeira) { this.codigoCadeira = codigoCadeira; } }
/** @author Chazwarp923 */ package tech.chazwarp923.unifieditems.block; public enum HarvestLevel { WOOD(0), STONE(1), IRON(2), DIAMOND(3); final int level; HarvestLevel(int level) { this.level = level; } }
package Usta.sistemas; import java.util.Scanner; public class Main { public static void main(String[] args) { /*AUTHOR: Angel Manuel Correa Rivera DATE: 19 March, 2020 DESCRIPTION: This software calculate the volume of a cylinder */ Scanner keyboard = new Scanner(System.in); double height, radius, volume; System.out.println("This software calculate the volume of a cylinder in cm, please, input the height(cm): "); height = keyboard.nextDouble(); System.out.println("Please enter the radius(cm): "); radius = keyboard.nextDouble(); volume = 3.1416* Math.pow(radius, 2)* height; System.out.println("The volume of the cylinder is (cm): " + volume); } }
import java.util.Scanner; public class Example2_19 //compute area of a triangle { public static void main(String[] args) { //Create a scanner object Scanner input = new Scanner(System.in); //Prompt the user to enter three points System.out.print(" Enter three points for a triangle : "); double x1 = input.nextDouble(); double y1 = input.nextDouble(); double x2 = input.nextDouble(); double y2 = input.nextDouble(); double x3 = input.nextDouble(); double y3 = input.nextDouble(); // compute the sides of triangle double side1 = Math.pow(Math.pow(x2-x1,2)+ Math.pow(y2-y1,2) , 0.5); double side2 = Math.pow(Math.pow(x3-x2,2)+ Math.pow(y3-y2,2) ,0.5); double side3 = Math.pow(Math.pow(x1-x3,2)+ Math.pow(y1-y3,2),0.5); double s = (side1 + side2 + side3)/2; // compute area of the triangle double area = Math.pow(s* (s-side1)*( s-side2)*(s-side3),0.5); //Display result System.out.println(" The area of triangle is " +area); } }
package com.revature.accessmods; public class Driver2 { // we'll set fields of this class equal to the value of a Drive1 object Driver1 d1 = new Driver1(); int y = d1.publicField; // int x = d1.privateField; int z = d1.protectedField; int w = d1.defaultField; }
/******************************************************************************* * Copyright (c) 2014 Liviu Ionescu. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Liviu Ionescu - initial implementation. *******************************************************************************/ package ilg.gnuarmeclipse.packs.cmsis; /** * Static class used to support the PDSC parsing. */ public class PdscUtils { /** * Validate the schema version. * * @param schemaVersion * a string with the xml attribute of the <package> element. * @return true if the value is valid. */ public static boolean isSchemaValid(String schemaVersion) { if ("1.0".equals(schemaVersion) || "1.1".equals(schemaVersion) || "1.2".equals(schemaVersion) || "1.3".equals(schemaVersion)) { return true; } else { return false; } } /** * Convert a Windows path into a POSIX path. * * @param spath * the string representing the Windows path. * @return the corresponding POSIX path. */ public static String updatePosixSeparators(String spath) { return spath.replace('\\', '/'); } }
package uk.co.samwho.modopticon.modules; import java.time.Clock; import dagger.Module; import dagger.Provides; @Module public final class ClockModule { @Provides static Clock provideClock() { return Clock.systemUTC(); } }
package unalcol.io; import java.io.IOException; import java.lang.reflect.Method; public class ReadWrapper extends Read<Object> { /** * Creates a clone wrapped method for objects */ protected String method_name = "clone"; protected Method method = null; public ReadWrapper(Class<?> type) { try { method = type.getMethod(method_name); } catch (Exception e) { e.printStackTrace(); } } public boolean available() { return method != null; } @Override public Object read(ShortTermMemoryReader reader) throws IOException { try { return method.invoke(reader); } catch (Exception e) { throw new IOException(e.getMessage()); } } }
package agents.anac.y2012.MetaAgent.agents.WinnerAgent; import java.util.HashMap; import java.util.Vector; public class Loop<T> { // this class is helpful for creating all possible offers in the domain private Loop<T> _nextLoop; private Vector<T> _vec; private HashMap<Integer, Integer> _indexMap; public Loop(Vector<T> vec, HashMap<Integer, Integer> indexMap){ _vec = vec; _indexMap = indexMap; _nextLoop = null; } public Loop(Vector<T> vec, HashMap<Integer, Integer> indexMap, Loop<T> next){ this(vec, indexMap); _nextLoop = next; } public Loop<T> setNext(Vector<T> vec) { _nextLoop = new Loop<T>(vec, _indexMap); return _nextLoop; } public void iteration(HashMap<Integer,T> outerLoop, int index,Vector<HashMap<Integer,T>> cartesianProd, int limit){ for(T o : _vec) { if(cartesianProd.size() >= limit) { break; } HashMap<Integer,T> innerMap = new HashMap<Integer,T>(); innerMap.putAll(outerLoop); innerMap.put(_indexMap.get(index), o); if(_nextLoop != null) { _nextLoop.iteration(innerMap, index+1, cartesianProd, limit); } else { cartesianProd.add(innerMap); } } } }
package com.example.camera360.main; import java.util.ArrayList; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import com.example.camera360.provider.HotImages; import com.example.camera360.provider.LatestImages; import com.example.camera360.provider.PhotoImages; public class MainFragmentPagerAdapter extends FragmentPagerAdapter { private ArrayList<Fragment> fragmentsList; public HotImages hotImages = null; public LatestImages latestImages = null; public PhotoImages photoImages = null; public MainFragmentPagerAdapter(FragmentManager fm) { super(fm); } public MainFragmentPagerAdapter(FragmentManager fm, ArrayList<Fragment> fragments) { super(fm); this.fragmentsList = fragments; } @Override public int getCount() { return fragmentsList.size(); } @Override public Fragment getItem(int arg0) { Fragment fragment = fragmentsList.get(arg0); switch(arg0){ case 0: new HotImages(fragment); break; case 1: new LatestImages(fragment); break; case 2: new PhotoImages(fragment); break; } return fragment; } @Override public int getItemPosition(Object object) { return super.getItemPosition(object); } }
package net.packet.handlers; import io.netty.buffer.ByteBuf; import maplestory.npc.MTSButtonNpcConversation; import net.Proxy; import net.handler.HandlePacketResult; import net.handler.MaplePacketHandler; import net.packet.server.MapleNpcPacket; import net.packet.server.MapleReAllowActionPacket; public class OpenMTSHandler implements MaplePacketHandler { @Override public void onSendToServer(Proxy proxy, ByteBuf buf, HandlePacketResult result) { result.setCancelled(true); proxy.getMaplestory().startNpcConversation(new MTSButtonNpcConversation(proxy, 2080005)); proxy.getClient().sendPacket(new MapleReAllowActionPacket()); } @Override public void onSendToClient(Proxy proxy, ByteBuf buf, HandlePacketResult result) { } }
package com.cnk.travelogix.suppliers.acco.service.test; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.cnk.travelogix.suppliers.acco.data.AvailRequestSegment; import com.cnk.travelogix.suppliers.acco.data.Criterion; import com.cnk.travelogix.suppliers.acco.data.DateTimeSpanType; import com.cnk.travelogix.suppliers.acco.data.GetDetailsReadRequest; import com.cnk.travelogix.suppliers.acco.data.GetDetailsRequestWrapper; import com.cnk.travelogix.suppliers.acco.data.GetDetailsResponseWrapper; import com.cnk.travelogix.suppliers.acco.data.GuestCount; import com.cnk.travelogix.suppliers.acco.data.GuestCountType; import com.cnk.travelogix.suppliers.acco.data.HotelAvailRQ; import com.cnk.travelogix.suppliers.acco.data.HotelRef; import com.cnk.travelogix.suppliers.acco.data.HotelSearchCriteria; import com.cnk.travelogix.suppliers.acco.data.RoomStayCandidate; import com.cnk.travelogix.suppliers.acco.service.SupplierAccoService; import com.cnk.travelogix.suppliers.common.data.Credential; import com.cnk.travelogix.suppliers.common.data.Credentials; import com.cnk.travelogix.suppliers.common.data.OperationURL; import com.cnk.travelogix.suppliers.common.data.RequestHeader; import com.cnk.travelogix.suppliers.common.data.SupplierCredentials; import com.cnk.travelogix.suppliers.common.data.SupplierID; public class GetDetailsTest { public static void main(String[] args) { ApplicationContext appContext = new ClassPathXmlApplicationContext(new String[] { "suppliers-spring.xml" }); SupplierAccoService accoService = (SupplierAccoService) appContext.getBean("supplierAccoService"); GetDetailsRequestWrapper requestWrapper = new GetDetailsRequestWrapper(); RequestHeader requestHeader = new RequestHeader(); requestHeader.setSessionID("2"); requestHeader.setUserID("1"); requestHeader.setTransactionID("3"); Map<String, String> credentialsMap = new HashMap<String, String>(); credentialsMap.put("Username", "teze3568"); credentialsMap.put("Password", "teze4875"); SupplierCredentials supplierCredential = new SupplierCredentials(); List<SupplierCredentials> supplierCredentials = new ArrayList<>(); SupplierID supplierIDHeader = new SupplierID(); supplierIDHeader.setValue("ATI"); supplierCredential.setSupplierID(supplierIDHeader); supplierCredentials.add(supplierCredential); Credentials credentials = new Credentials(); List<Credential> credentialList = new ArrayList<>(); for (final Map.Entry<String, String> keyValueMap : credentialsMap.entrySet()) { Credential credential = new Credential(); credential.setName(keyValueMap.getKey()); credential.setValue(keyValueMap.getValue()); credentialList.add(credential); } credentials.setCredential(credentialList); List<OperationURL> operationURLList = new ArrayList<>(); OperationURL operationURL = new OperationURL(); operationURL.setValue("https://sws3-crt.cert.sabre.com/"); operationURL.setOperation("all"); operationURLList.add(operationURL); credentials.setOperationURL(operationURLList); supplierCredential.setCredentials(credentials); requestHeader.setSupplierCredentials(supplierCredentials); GetDetailsReadRequest getDetailsReadRequest = new GetDetailsReadRequest(); List<GetDetailsReadRequest> hotelAvailReadRequest = new ArrayList<>(); getDetailsReadRequest.setSequence(1); getDetailsReadRequest.setSupplierID("ATI"); HotelAvailRQ hotelAvailRQ = new HotelAvailRQ(); BigDecimal bigDecimal = new BigDecimal("1.0"); hotelAvailRQ.setVersion(bigDecimal); AvailRequestSegment availRequestSegment = new AvailRequestSegment(); List<AvailRequestSegment> availRequestSegments = new ArrayList<>(); List<Criterion> criterions = new ArrayList<>(); HotelSearchCriteria hotelSearchCriteria = new HotelSearchCriteria(); Criterion criterion = new Criterion(); HotelRef hotelRef = new HotelRef(); List<HotelRef> hotelRefs = new ArrayList<>(); hotelRef.setHotelCode("HNLAQP"); hotelRefs.add(hotelRef); criterion.setHotelRef(hotelRefs); DateTimeSpanType dateTimeSpanType = new DateTimeSpanType(); dateTimeSpanType.setEnd("2016-07-30"); dateTimeSpanType.setStart("2016-07-25"); criterion.setStayDateRange(dateTimeSpanType); RoomStayCandidate roomStayCandidate = new RoomStayCandidate(); List<RoomStayCandidate> roomStayCandidates = new ArrayList<>(); GuestCountType guestCountType = new GuestCountType(); GuestCount guestCount = new GuestCount(); GuestCount guestCountData = new GuestCount(); List<GuestCount> guestCounts = new ArrayList<>(); guestCount.setAgeQualifyingCode("10"); guestCount.setCount(1); guestCountData.setCount(1); guestCountData.setAgeQualifyingCode("8"); guestCountData.setAge(3); guestCounts.add(guestCount); guestCounts.add(guestCountData); guestCountType.setGuestCount(guestCounts); roomStayCandidate.setGuestCounts(guestCountType); roomStayCandidates.add(roomStayCandidate); criterion.setRoomStayCandidates(roomStayCandidates); criterions.add(criterion); hotelSearchCriteria.setCriterion(criterions); availRequestSegment.setHotelSearchCriteria(hotelSearchCriteria); availRequestSegments.add(availRequestSegment); hotelAvailRQ.setAvailRequestSegments(availRequestSegments); getDetailsReadRequest.setHotelAvailRQ(hotelAvailRQ); requestWrapper.setRequestHeader(requestHeader); hotelAvailReadRequest.add(getDetailsReadRequest); requestWrapper.setGetDetailsReadRequest(hotelAvailReadRequest); GetDetailsResponseWrapper response = accoService.otaAccoGetDetails(requestWrapper); System.out.println("***************************************************=" + response); } }
package com.baomidou.mybatisplus.samples.quickstart.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.samples.quickstart.domain.CityConstant; import com.baomidou.mybatisplus.samples.quickstart.domain.User; public interface CityConstantMapper extends BaseMapper<CityConstant> { }
import java.util.Scanner; public class Miegas { public static void main(String[] args) { Boolean darboDiena= false; Boolean atostogos= true; Scanner sc = new Scanner(System.in); System.out.println("darbo diena?"); darboDiena = sc.hasNext(); sc.next(); System.out.println("atostogos?"); atostogos = sc.hasNext(); if ( darboDiena == false ||(atostogos == true && darboDiena == true)) { System.out.println("galima miegoti"); } else { System.out.println("kelkis i darba!"); } sc.close(); } }
package jp.naist.se.codehash; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import jp.naist.se.codehash.util.StringMultiset; public class MurmurMinHash { private int k; private NgramMultiset ngramMultiset; /** * 1-bit minhash using k hash functions for N-gram Jaccard Index. * @param k the number of bits. It should be a multiple of 8. * @param N * @param reader */ public MurmurMinHash(int k, int N, TokenReader reader) { if (k <= 0) throw new IllegalArgumentException("k must be a positive integer. " + k); this.k = k; this.ngramMultiset = new NgramMultiset(new NgramReader(N, reader)); } private byte[] computeMinHash(int k, StringMultiset mset) { // Initialize minhash int[] hash = new int[k]; Arrays.fill(hash, Integer.MAX_VALUE); // Compute hash for (String key: mset.keySet()) { int count = mset.get(key); for (int c=0; c<count; c++) { String s = key + "\0" + Integer.toString(c); int h = MurmurHash3.murmurhash3_x86_32(s, 0, s.length(), 0); for (int i=0; i<k; i++) { if (h < hash[i]) { hash[i] = h; } h = MurmurHash3.fmix32(h); } } } return packMinHash(hash); } private byte[] packMinHash(int[] hash) { // Translate b-bit minhash byte[] bitminhash = new byte[hash.length / 8]; for (int i=0; i<hash.length; i++) { int j = i / 8; int idx = i % 8; if ((hash[i] & 1) == 1) bitminhash[j] |= (1 << (7-idx)); } // Sanity checker for (int i=0; i<bitminhash.length; i++) { for (int j=0; j<8; j++) { if ((bitminhash[i] & (1 << (7-j))) != 0) { assert (hash[i * 8 + j] & 1) == 1; } else { assert (hash[i * 8 + j] & 1) == 0; } } } return bitminhash; } /** * Calculate k-bit minhash representing a given multiset using SHA-1 hash algorithm. * @param k is the number of minhash bits. * @param mset represents a multiset to be translated. * @return a bit array. */ private byte[] getSHA1MinHash(int k, StringMultiset mset) { try { MessageDigest digest = MessageDigest.getInstance("SHA-1"); // Initialize minhash int[] minhash = new int[k]; Arrays.fill(minhash, Integer.MAX_VALUE); // Compute hash for (String key: mset.keySet()) { int count = mset.get(key); for (int c=0; c<count; c++) { String s = key + "\0" + Integer.toString(c); byte[] hash = digest.digest(s.getBytes()); for (int i=0; i<k; i++) { int h = extractIntHash(hash); if (h < minhash[i]) { minhash[i] = h; } hash = digest.digest(hash); } } } return packMinHash(minhash); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } private int extractIntHash(byte[] digest) { int hash = 0; for (int i=0; i<4; i++) { hash = (hash << 4) + digest[i]; } return hash; } /** * @return 1-bit minhash array. */ public byte[] getHash() { return computeMinHash(k, ngramMultiset.getRegular()); } public byte[] getNormalizedHash() { return computeMinHash(k, ngramMultiset.getNormalized()); } public byte[] getSHA1MinHash() { return getSHA1MinHash(k, ngramMultiset.getRegular()); } public byte[] getNormalizedSHA1MinHash() { return getSHA1MinHash(k, ngramMultiset.getNormalized()); } public int getNgramCount() { return ngramMultiset.getNgramCount(); } public byte[] getHashIgnoreDuplicatedElements() { return computeMinHash(k, ngramMultiset.getRegular().toOrdinarySet()); } public byte[] getNormalizedHashIgnoreDuplicatedElements() { return computeMinHash(k, ngramMultiset.getNormalized().toOrdinarySet()); } public int getUniqueNgramCount() { return ngramMultiset.getUniqueNgramCount(); } public StringMultiset getNgramMultiset() { return ngramMultiset.getRegular(); } public StringMultiset getNormalizedNgramMultiset() { return ngramMultiset.getNormalized(); } }
package uz.projects.wallpaper.ui; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import uz.projects.wallpaper.MainActivity; import uz.projects.wallpaper.R; import uz.projects.wallpaper.adapter.RecyclerAdapter; import uz.projects.wallpaper.databinding.FragmentLikedBinding; import uz.projects.wallpaper.models.Category; import uz.projects.wallpaper.models.ImageData; import uz.projects.wallpaper.preference.MySharedPreference; /** * A simple {@link Fragment} subclass. * Use the {@link LikedFragment#newInstance} factory method to * create an instance of this fragment. */ public class LikedFragment extends Fragment { private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; public LikedFragment() { // Required empty public constructor } public static LikedFragment newInstance(String param1, String param2) { LikedFragment fragment = new LikedFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } private Gson gson = new Gson(); private FragmentLikedBinding binding; private MySharedPreference preference; private List<Category> categoryList; private RecyclerAdapter adapter; private List<ImageData> imageDataList = new ArrayList<>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentLikedBinding.inflate(inflater, container, false); preference = MySharedPreference.getInstance(requireContext()); String listString = preference.getNumberListString(); if (!listString.equalsIgnoreCase("")) { imageDataList = new ArrayList<>(); Type type = new TypeToken<List<Category>>() { }.getType(); categoryList = gson.fromJson(listString, type); } List<ImageData> dataList = categoryList.get(0).getImageDataList(); for (int i = 0; i < dataList.size(); i++) { if (dataList.get(i).isLiked()) { imageDataList.add(dataList.get(i)); } } adapter = new RecyclerAdapter(imageDataList, new RecyclerAdapter.onItemClickListener() { @Override public void onItemClick(ImageData imageData) { Bundle bundle = new Bundle(); bundle.putSerializable("image", imageData); Navigation.findNavController(requireView()).navigate(R.id.action_likedFragment_to_imageFragment, bundle); } }); binding.recycler.setAdapter(adapter); return binding.getRoot(); } }
package com.levislv.statistics.fully.navigationbar.view; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.widget.AppCompatImageView; import com.levislv.statistics.R; import com.levislv.statistics.fully.navigationbar.view.base.BaseFragment; import com.levislv.statisticssdk.plugin.annotation.StatisticsPage; @StatisticsPage( type = StatisticsPage.Type.FRAGMENT, id = R.layout.fragment_notfirst, name = "TabNotFirst页", data = "{'pageKey0':'pageValue0', 'pageKey01':'pageValue1', 'pageKey02':'pageValue2'}" ) public class NotFirstFragment extends BaseFragment implements View.OnClickListener { private static final String TAG = "NotFirstFragment"; private static final String KEY_PAGE_TEXT = "key_page_text"; private AppCompatImageView ivTitleBackward; private TextView tvTitle; private Button btnForward; private CharSequence pageText; @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_title_backward: getFragmentManager().popBackStack(); break; case R.id.btn_forward: String tag, name; tag = name = String.valueOf(pageText) + (getFragmentManager().getBackStackEntryCount() + 2) + "级"; getFragmentManager().beginTransaction() .replace(R.id.layout_frag, NotFirstFragment.newInstance(pageText), tag) .addToBackStack(name) .commitAllowingStateLoss(); break; default: break; } } public static BaseFragment newInstance(CharSequence pageText) { BaseFragment notFirstFragment = new NotFirstFragment(); Bundle args = new Bundle(); args.putCharSequence(KEY_PAGE_TEXT, pageText); notFirstFragment.setArguments(args); return notFirstFragment; } @Override protected void initData() { Bundle args = getArguments(); if (args != null && args.containsKey(KEY_PAGE_TEXT)) { pageText = args.getCharSequence(KEY_PAGE_TEXT); } } @Override protected int getContentViewId() { return R.layout.fragment_notfirst; } @Override protected void bindView(View view) { ivTitleBackward = view.findViewById(R.id.iv_title_backward); tvTitle = view.findViewById(R.id.tv_title); btnForward = view.findViewById(R.id.btn_forward); } @Override protected void initView() { ivTitleBackward.setOnClickListener(this); tvTitle.setText(String.valueOf(pageText) + (getFragmentManager().getBackStackEntryCount() + 1) + "级"); btnForward.setOnClickListener(this); } }
package ast; import java.util.ArrayList; import ast.types.TypeNode; import exceptions.NotDeclaredException; import exceptions.TypeException; import semanticAnalysis.Environment; import semanticAnalysis.SemanticError; /** * Interface representing a generic node in the AST */ public interface Node { /** * Node as a string * @param indent characters before the string * @return the string version of the node */ String toPrint(String indent); /** * Effectively checks the types of every nodes * @return the type of the identifier or expression */ TypeNode typeCheck() throws TypeException; /** * Generates the intermediate code * @return a string which is the ASM code */ String codeGeneration(); /** * Checks if there are any errors in the subtree given the environment * @param env is the environment at the moment of the typechecking * @return list of {@code SemanticError} */ ArrayList<SemanticError> checkSemantics(Environment env); ArrayList<SemanticError> checkEffects(Environment env) ; /** * Checks if a Node is of the same type of another Node * @param n1 first node * @param n2 second node * @return true if match, false otherwise */ static boolean sametype(TypeNode n1, TypeNode n2) { return n1.getClass().equals(n2.getClass()); } }
package hirondelle.web4j.security; import hirondelle.web4j.request.RequestParser; /** Determines if a request has an ownership constraint which needs explicit validation for a user id proxy. <P>This interface addresses the issue of <a href='http://www.owasp.org/index.php/Top_10_2007-A4'>Insecure Direct Object Reference</a>, which is an important security issue for web applications. The issue centers around proper enforcement of <b>data ownership constraints</b>. <P>Please see the <a href='http://www.web4j.com/UserGuide.jsp#DataOwnershipConstraints'>User Guide</a> for more information on this important topic. <a name='UntrustedProxyForUserId'></a> <h3>Untrusted Proxy For User Id</h3> An untrusted proxy for the user id is defined here as satisfying these two criteria: <ul> <li>it's "owned" by a specific user (that is, it has an associated data ownership constraint) <li>it's open to manipulation by the end user (for example, by simply changing a request parameter) </ul> <P>An untrusted identifier typically appears in a link, or in a form's target URL. This interface is for defining which requests use an untrusted identifier, and which need to enforce a data ownership constraint in a particular way. <P>Note that, as explained in the <a href='http://www.web4j.com/UserGuide.jsp#DataOwnershipConstraints'>User Guide</a>, not all data ownership constraints involve an untrusted proxy for the user id - only some do. <P>The {@link hirondelle.web4j.Controller} processes each request using your application's configured implementation of this interface. Most applications will likely use the default implementation, {@link hirondelle.web4j.security.UntrustedProxyForUserIdImpl}. The <tt>Controller</tt> logic is roughly as follows: <PRE> get the configured implementation of UntrustedProxyForUserId if the current request has an untrusted id { cast the Action to {@link hirondelle.web4j.security.FetchIdentifierOwner} fetch the login name of the user who owns the untrusted id compare it to the login name of the current user proceed with the Action only if there is a match }</PRE> (Reminder: whenever a user logs in, the login name of the current user is always placed into session scope by the Servlet Container.) <P>Implementations of this interface will typically extract two items from the underlying request, to determine if the request has an untrusted proxy for the user id : <ul> <li>the 'noun' - identifies <i>what data</i> is being operated on <li>the 'verb' - what is being <i>done</i> to the data (the operation) </ul> <P>In some cases, only the noun will be important, since <i>all</i> operations on the data can be restricted to the owner. In other cases, both the noun <i>and</i> the verb will be needed to determine if there is a data ownership constraint. */ public interface UntrustedProxyForUserId { /** Returns <tt>true</tt> only if the given request uses an untrusted proxy for the user id. */ boolean usesUntrustedIdentifier(RequestParser aRequestParser); }
package com.charith.codility.maximumSliceProblem.MaxSliceSum; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class SolutionTest { @Test void solution() { Assertions.assertEquals(6, Solution.solution(new int[]{-2, 4, 2})); Assertions.assertEquals(2, Solution.solution(new int[]{2, -4, 2})); } }
package com.xiruan.demand.entity.automation; import com.xiruan.demand.entity.IdEntity; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; /** * Created by Chen.Ju on 2015/8/11. */ @Entity @Table(name = "DEMAND_ROLE_MENU") public class DemandRoleMenu extends IdEntity { private DemandMenu demandMenu; private DemandRole demandRole; @ManyToOne @JoinColumn(name = "menu_id") public DemandMenu getDemandMenu() { return demandMenu; } public void setDemandMenu(DemandMenu demandMenu) { this.demandMenu = demandMenu; } @ManyToOne @JoinColumn(name = "role_id") public DemandRole getDemandRole() { return demandRole; } public void setDemandRole(DemandRole demandRole) { this.demandRole = demandRole; } }
package com.athena.marketo.utils; import java.text.SimpleDateFormat; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class JsonUtils { private JsonUtils() { } private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); static { OBJECT_MAPPER.setDateFormat(new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'")); } public static ObjectMapper getObjectMapper() { return OBJECT_MAPPER; } public static ObjectNode objectNode() { return OBJECT_MAPPER.createObjectNode(); } public static ArrayNode arrayNode() { return OBJECT_MAPPER.createArrayNode(); } }
/** * Copyright (c) 2012, Ben Fortuna * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * o Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * o Neither the name of Ben Fortuna nor the names of any other contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.fortuna.ical4j.vcard; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.codec.DecoderException; import net.fortuna.ical4j.data.ParserException; import net.fortuna.ical4j.data.UnfoldingReader; import net.fortuna.ical4j.util.CompatibilityHints; /** * vCard object builder. * * $Id$ * * Created on: 02/11/2008 * * @author Ben * */ public final class VCardBuilder { private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); private static final Pattern VCARD_BEGIN = Pattern.compile("^BEGIN:VCARD$", Pattern.CASE_INSENSITIVE); private static final Pattern RELAXED_VCARD_BEGIN = Pattern.compile("^BEGIN:VCARD\\s*$", Pattern.CASE_INSENSITIVE); private static final Pattern VCARD_END = Pattern.compile("^END:VCARD$", Pattern.CASE_INSENSITIVE); private static final Pattern RELAXED_VCARD_END = Pattern.compile("^END:VCARD\\s*$", Pattern.CASE_INSENSITIVE); // private static final Pattern PROPERTY_NAME_PATTERN = Pattern.compile("^\\w*\\.?\\w*(?=[;:])"); /** * This is supposed to cover following cases */ static final Pattern PROPERTY_NAME_PATTERN = Pattern.compile( "^(([a-zA-Z-\\d]+\\.)?[a-zA-Z]+(?=[;:]))|" + "(([a-zA-Z-\\d]+\\.)?[Xx]-[a-zA-Z-]+(?=[;:]))"); private static final Pattern PROPERTY_VALUE_PATTERN = Pattern.compile("(?<=[:]).*$"); private static final Pattern PARAMETERS_PATTERN = Pattern.compile("(?<=[;])[^:]*(?=[:])"); private static final int BUFFER_SIZE = 1024; private final BufferedReader reader; private final GroupRegistry groupRegistry; private final PropertyFactoryRegistry propertyFactoryRegistry; private final ParameterFactoryRegistry parameterFactoryRegistry; private final boolean relaxedParsing; /** * @param in an input stream providing vCard data */ public VCardBuilder(InputStream in) { this(new InputStreamReader(in, DEFAULT_CHARSET)); } /** * @param in a reader providing vCard data */ public VCardBuilder(Reader in) { this(in, new GroupRegistry(), new PropertyFactoryRegistry(), new ParameterFactoryRegistry()); } /** * @param in a reader providing vCard data * @param registry a group registry used to construct vCard objects * @param propertyFactoryRegistry a property factory registry used to construct * vCard objects * @param parameterFactoryRegistry a parameter factory registry used to construct * vCard objects */ public VCardBuilder(Reader in, GroupRegistry registry, PropertyFactoryRegistry propertyFactoryRegistry, ParameterFactoryRegistry parameterFactoryRegistry) { this.reader = new BufferedReader(new UnfoldingReader(in, BUFFER_SIZE), BUFFER_SIZE); this.groupRegistry = registry; this.propertyFactoryRegistry = propertyFactoryRegistry; this.parameterFactoryRegistry = parameterFactoryRegistry; this.relaxedParsing = CompatibilityHints.isHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING); } /** * @return a new vCard object instance * @throws IOException where a problem occurs reading vCard data * @throws ParserException where parsing vCard data fails */ public VCard build() throws IOException, ParserException { return build(true); } /** * @return a list of vCard object instances * @throws IOException where a problem occurs reading vCard data * @throws ParserException where parsing vCard data fails */ public List<VCard> buildAll() throws IOException, ParserException { final List<VCard> cards = new ArrayList<VCard>(); while (true) { final VCard card = build(false); if (card == null) { break; } else { cards.add(card); } } return Collections.unmodifiableList(cards); } /** * @return * @throws IOException * @throws ParserException */ private VCard build(boolean single) throws IOException, ParserException { VCard vcard = null; String line = null; String lastLine = null; int nonBlankLineNo = 0; int totalLineNo = 0; boolean end = false; Pattern beginPattern = null; Pattern endPattern = null; if (relaxedParsing) { beginPattern = RELAXED_VCARD_BEGIN; endPattern = RELAXED_VCARD_END; } else { beginPattern = VCARD_BEGIN; endPattern = VCARD_END; } while ((single || !end) && (line = reader.readLine()) != null) { totalLineNo++; if (line.trim().length() == 0) { continue; // ignore blank lines } nonBlankLineNo++; if (nonBlankLineNo == 1) { if (!beginPattern.matcher(line).matches()) { throw new ParserException(nonBlankLineNo); } vcard = new VCard(); } else if (!endPattern.matcher(line).matches()) { Property property; try { property = parseProperty(line); } catch (URISyntaxException e) { throw new ParserException("Error parsing line", totalLineNo, e); } catch (ParseException e) { throw new ParserException("Error parsing line", totalLineNo, e); } catch (DecoderException e) { throw new ParserException("Error parsing line", totalLineNo, e); } if (property != null) { vcard.getProperties().add(property); } } else if (endPattern.matcher(line).matches()) { end = true; } if (line.trim().length() > 0) { lastLine = line; } } if (single && (nonBlankLineNo <= 1 || !endPattern.matcher(lastLine).matches())) { throw new ParserException(totalLineNo); } return vcard; } /** * @param line * @return * @throws ParseException * @throws URISyntaxException * @throws DecoderException */ private Property parseProperty(final String line) throws URISyntaxException, ParseException, DecoderException { Matcher matcher = PROPERTY_NAME_PATTERN.matcher(line); if (matcher.find()) { PropertyFactory<?> factory = null; Group group = null; final String propertyName = matcher.group().toUpperCase(); if (propertyName.indexOf('.') >= 0) { final String[] groupProperty = propertyName.split("\\."); group = groupRegistry.getGroup(groupProperty[0]); factory = propertyFactoryRegistry.getFactory(groupProperty[1]); } else { factory = propertyFactoryRegistry.getFactory(propertyName); } if (factory == null) { return null; } matcher = PROPERTY_VALUE_PATTERN.matcher(line); if (matcher.find()) { final String propertyValue = matcher.group(0); final List<Parameter> params = parseParameters(line); if (group != null) { return factory.createProperty(group, params, propertyValue); } else { return factory.createProperty(params, propertyValue); } } } return null; } /** * @param line * @return */ private List<Parameter> parseParameters(final String line) { final List<Parameter> parameters = new ArrayList<Parameter>(); final Matcher matcher = PARAMETERS_PATTERN.matcher(line); if (matcher.find()) { final String[] params = matcher.group().split(";"); for (String param : params) { final String[] vals = param.split("="); final ParameterFactory<? extends Parameter> factory = parameterFactoryRegistry.getFactory( vals[0].toUpperCase()); if (factory == null) { continue; } if (vals.length > 1) { parameters.add(factory.createParameter(vals[1])); } else { parameters.add(factory.createParameter(null)); } } } return parameters; } }
package com.mitelcel.pack.utils; import android.content.Context; import com.mitelcel.pack.Config; import com.mitelcel.pack.R; /** * Created by sudhanshu.thanedar on 10/26/2015. */ public class Validator { Context context; public Validator(Context context) { this.context = context; } public String isNumberValid(String msisdn){ if(msisdn.length() < Config.MSISDN_LENGTH) return this.context.getString(R.string.msisdn_not_valid); // If null return the referral code is OK return null; } public String isValidPassSignUp(String pass) { if(pass.length() < Config.PASS_LENGTH) return this.context.getString(R.string.invalid_password, Config.PASS_LENGTH); return null; } public String doesPassMatchSignUp(String pass, String passConfirm) { if(!pass.equals(passConfirm)){ return this.context.getString(R.string.password_does_not_match); } return null; } public String isTransferAmountValid(float amount){ if(amount <= 0 || amount > MiUtils.MiAppPreferences.getCurrentBalance()) return this.context.getString(R.string.transfer_invalid_amount); // If null return the referral code is OK return null; } }
package com.d.algorithm.sort; /** * 选择排序 * Created by D on 2017/6/24. */ public class SelectSort extends Sort { public static void sort(int[] arr) { if (!valid(arr)) { return; } //只需要比较n-1次 for (int i = 0, index = 0; i < arr.length - 1; i++, index = i) { //从i+1开始比较,因为index默认为i了,i就没必要比 for (int j = i + 1; j < arr.length; j++) { if (arr[j] < arr[index]) { index = j; } } //如果index不为i,说明找到了更小的值,交换之 if (index != i) { swap(arr, i, index); } } } }
package com.moon.process.impl; import com.moon.process.*; import com.moon.vo.BaseResponseVo; import org.springframework.stereotype.Service; import java.util.Map; /** * Created by maguoqiang on 2016/11/15. * 流程a */ @Service("processA") public class ProcessAImpl implements com.moon.process.Process { public BaseResponseVo process(Map<String, Object> paramMap) { BaseResponseVo responseVo=new BaseResponseVo(); responseVo.setResponseCode("00"); responseVo.setResponseMsg("a流程返回成功"); return responseVo; } }
package com.tencent.mm.plugin.freewifi.ui; import android.os.Message; import com.tencent.mm.sdk.platformtools.ag; class FreeWifiManufacturerLoadingUI$1 extends ag { int i = 0; final /* synthetic */ FreeWifiManufacturerLoadingUI jnE; FreeWifiManufacturerLoadingUI$1(FreeWifiManufacturerLoadingUI freeWifiManufacturerLoadingUI) { this.jnE = freeWifiManufacturerLoadingUI; } public final void handleMessage(Message message) { if (message.what == 1) { if (this.i >= FreeWifiManufacturerLoadingUI.a(this.jnE).length) { this.i = 0; } FreeWifiManufacturerLoadingUI.b(this.jnE).setImageResource(FreeWifiManufacturerLoadingUI.a(this.jnE)[this.i]); this.i++; } else if (message.what == 2) { FreeWifiManufacturerLoadingUI.b(this.jnE).setImageResource(FreeWifiManufacturerLoadingUI.a(this.jnE)[FreeWifiManufacturerLoadingUI.a(this.jnE).length - 1]); } else if (message.what == 3 && message.obj != null && (message.obj instanceof String)) { FreeWifiManufacturerLoadingUI.c(this.jnE).setText(message.obj.toString()); } super.handleMessage(message); } }
package com.tencent.mm.plugin.appbrand.launching; import android.util.Pair; import com.tencent.mm.plugin.appbrand.app.e; import com.tencent.mm.plugin.appbrand.appcache.WxaPkgWrappingInfo; import com.tencent.mm.plugin.appbrand.appcache.ak; import com.tencent.mm.plugin.appbrand.appcache.ak.a; import com.tencent.mm.plugin.appbrand.appcache.b; import com.tencent.mm.plugin.appbrand.appcache.d; import com.tencent.mm.plugin.appbrand.appcache.k; import com.tencent.mm.plugin.appbrand.appcache.r; import com.tencent.mm.protocal.c.akl; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.Locale; public final class p extends o { public final String appId; public final int bPh; public final String fgp; public final int gfU; public final boolean gfV; public p(String str, String str2, int i) { this(str, str2, i, true); } public p(String str, String str2, int i, boolean z) { super(new r(str, str2)); this.bPh = 0; this.appId = str; this.fgp = str2; this.gfU = i; this.gfV = z; } public final String akH() { return String.format(Locale.US, "pkg %s, targetVersion %d, pkgType %d", new Object[]{this.gfS.toString(), Integer.valueOf(this.gfU), Integer.valueOf(0)}); } public final void prepare() { Pair t = ak.t(this.gfS.toString(), 0, this.gfU); if (t.second != null) { x.i("MicroMsg.AppBrand.LaunchPkgPrepareJobReleaseCode", "%s prepare ok", new Object[]{akH()}); ((WxaPkgWrappingInfo) t.second).name = this.fgp; d((WxaPkgWrappingInfo) t.second); } else if (a.fhF.equals(t.first)) { x.i("MicroMsg.AppBrand.LaunchPkgPrepareJobReleaseCode", "%s getDownloadURL", new Object[]{akH()}); akl akl = new akl(); akl.bPS = this.appId; akl.rkb = this.gfU; akl.rNa = 0; if (!bi.oW(this.fgp)) { akl.rLl = this.fgp; akl.rNa = 4; } akl.rMZ = e.abi().a(this.gfS.toString(), 0, new String[]{"versionMd5"}).field_versionMd5; if (k.abE() && d.a.jC(0)) { WxaPkgWrappingInfo aG = e.aG(this.gfS.toString(), 1); if (aG != null) { akl.rNb = aG.fii; } } new b(akl).KM().h(new 1(this, akl)); } else { x.e("MicroMsg.AppBrand.LaunchPkgPrepareJobReleaseCode", "%s, local check failed ret=%s", new Object[]{akH(), t.first}); d(null); } } }
package com.canfield010.mygame.item.tool; import com.canfield010.mygame.Main; import com.canfield010.mygame.item.Item; import com.canfield010.mygame.item.Log; import com.canfield010.mygame.mapsquare.MapSquare; import com.canfield010.mygame.mapsquare.uppermapsquare.plant.OakTree; import javax.imageio.ImageIO; import java.awt.*; import java.io.File; public class Axe extends Item { public static Image image; public Axe() { super("Axe", (byte)1); } @Override public void use(MapSquare square) { if (square.upperMapSquare instanceof OakTree) { int logsToGive = Math.random()>0.5 ? 4 : 5; square.upperMapSquare = null; for (int i = 0; i<12; i++) { if (Main.player.inventory.storage[i] instanceof Log) { while (Main.player.inventory.storage[i].count<Main.player.inventory.storage[i].maximumCount && logsToGive>0) { Main.player.inventory.storage[i].count++; logsToGive--; } if (logsToGive==0) break; } } if (logsToGive == 0) return; for (int i = 0; i<12; i++) { if (Main.player.inventory.storage[i] == null) { Main.player.inventory.storage[i] = new Log(); while (Main.player.inventory.storage[i].count<Main.player.inventory.storage[i].maximumCount && logsToGive>0) { Main.player.inventory.storage[i].count++; logsToGive--; } if (logsToGive==0) break; } } } } @Override public boolean isUseful(MapSquare square) { if (square.upperMapSquare instanceof OakTree) { return true; } else { return false; } } public static void setImage() { try { image = ImageIO.read(new File("img/axe.png")); } catch (Exception e) { System.out.println(e); } } public Image getImage() { return image; }; }
package ru.sprikut.sd.refactoring.servlet; import ru.sprikut.sd.refactoring.database.Database; import ru.sprikut.sd.refactoring.product.Product; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * @author sprikut */ public class GetProductsServlet extends HttpServlet { private final Database<Product> database; public GetProductsServlet(Database<Product> database) { this.database = database; } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { List<Product> allProducts = database.selectAll(); response.getWriter().println("<html><body>"); for (Product product : allProducts) { response.getWriter().println(product.toHtml()); } response.getWriter().println("</body></html>"); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); } }
package com.packers.movers.configuration; import com.packers.movers.commons.config.utils.Property; public interface DatabaseConfiguration { @Property(key = "environment.jdbc.driver") String getDriver(); @Property(key = "environment.jdbc.url") String getUrl(); @Property(key = "environment.jdbc.user") String getUsername(); @Property(key = "environment.jdbc.password") String getPassword(); @Property(key = "environment.jdbc.suppress.close") boolean getSuppressClose(); }
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; import steps.GenericStep; public class BasePage { //---------------GENERIC METHODS-------------------// public WebElement getVisibleElementById(String id) { WebDriverWait wait = new WebDriverWait(GenericStep.getDriver(), 20); return wait.until(ExpectedConditions.visibilityOf(GenericStep.getDriver().findElement(By.id(id)))); } public WebElement getClickableElementById(String id) { WebDriverWait wait = new WebDriverWait(GenericStep.getDriver(), 20); return wait.until(ExpectedConditions.elementToBeClickable((By.id(id)))); } public Actions actionById(String id) { WebElement element = GenericStep.getDriver().findElement(By.id(id)); Actions actions = new Actions(GenericStep.getDriver()); return actions.moveToElement(element); } public WebElement getElementByText(String text) { return GenericStep.getDriver().findElement(By.xpath("//*[contains(text(),'"+text+"')]")); } public WebElement getElementByName(String name) { return GenericStep.getDriver().findElement(By.name(name)); } public WebElement getElementByXpath(String xpath) { WebDriverWait wait = new WebDriverWait(GenericStep.getDriver(), 20); return wait.until(ExpectedConditions.elementToBeClickable(By.xpath(xpath))); } public void selectInComboById(String id, String text) { WebDriverWait wait = new WebDriverWait(GenericStep.getDriver(), 20); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id(id))); Select combo = new Select(element); combo.selectByVisibleText(text); } //---------------GENERIC ELEMENTS-------------------// public void clickInNextButton() { switch (returnTextTabSelected()) { case "Enter Vehicle Data": getVisibleElementById("nextenterinsurantdata").click(); break; case "Enter Insurant Data": getVisibleElementById("nextenterproductdata").click(); break; case "Enter Product Data": getVisibleElementById("nextselectpriceoption").click(); break; case "Select Price Option": getVisibleElementById("nextsendquote").click(); break; } } public String returnTextTabSelected() { return getElementByXpath("//li[@class='idealsteps-step-active']/a") .getText() .replaceAll("[^A-Za-z- ]", ""); } public Boolean msgBlockExist() { if (getElementByXpath("//*[@id='xLoaderPrice']/p") .getText() .contains("Please, complete the first three steps to see the price table.")) { return true; }else { return false; } } }
package com.tencent.mm.plugin.sns.a.b; class i$3 implements Runnable { final /* synthetic */ i njJ; i$3(i iVar) { this.njJ = iVar; } public final void run() { if (System.currentTimeMillis() - i.b(this.njJ) >= 60000 || i.a(this.njJ).rbN.size() > 1000) { if (i.a(this.njJ) != null && i.a(this.njJ).rbN.size() > 0) { i.d(this.njJ); } i.a(this.njJ, 0); } } }
package com.osce.result; import java.io.Serializable; import java.util.Arrays; /** * @ClassName: Result * @Description: 返回结果 * @Author yangtongbin * @Date 2017/9/13 16:21 */ public class Result implements Serializable { private static final long serialVersionUID = 1757313404681564926L; /** 是否成功 */ private Boolean isSuccess; /** 业务错误编码,isSuccess为false时必须 */ private String errorCode; /** 业务错误描述,isSuccess为false时必须 */ private String errorDesc; /** 用户显示客户端的消息,可选 */ private String displayMsg; /** 错误异常堆栈信息,调用多个TR服务的异常堆积 */ private ErrorContext errorContext; /** 错误参数集合,比如某多个校验失败的结果集 */ private Object[] errorParameters; public Result(){ } public Result(Boolean isSuccess, String errorCode, String errorDesc) { this.isSuccess = isSuccess; this.errorCode = errorCode; this.errorDesc = errorDesc; } public Result(Boolean isSuccess, String errorCode, String errorDesc, String displayMsg, ErrorContext errorContext, Object[] errorParameters) { this.isSuccess = isSuccess; this.errorCode = errorCode; this.errorDesc = errorDesc; this.displayMsg = displayMsg; this.errorContext = errorContext; this.errorParameters = errorParameters; } public Result change(Boolean isSuccess, String errorCode, String errorDesc) { this.isSuccess = isSuccess; this.errorCode = errorCode; this.errorDesc = errorDesc; return this; } public Boolean getIsSuccess() { return isSuccess; } public void setIsSuccess(Boolean isSuccess) { this.isSuccess = isSuccess; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getErrorDesc() { return errorDesc; } public void setErrorDesc(String errorDesc) { this.errorDesc = errorDesc; } public String getDisplayMsg() { return displayMsg; } public void setDisplayMsg(String displayMsg) { this.displayMsg = displayMsg; } public ErrorContext getErrorContext() { return errorContext; } public void setErrorContext(ErrorContext errorContext) { this.errorContext = errorContext; } public Object[] getErrorParameters() { return errorParameters; } public void setErrorParameters(Object[] errorParameters) { this.errorParameters = errorParameters; } @Override public String toString() { return "Result [isSuccess=" + isSuccess + "; errorCode=" + errorCode + "; errorDesc=" + errorDesc + "; displayMsg=" + displayMsg + "; errorContext=" + errorContext + "; errorParameters=" + Arrays.toString(errorParameters) + "]"; } public static boolean checkSuccess(Result result) { return result != null && result.isSuccess; } }
module communicatorshared { exports communicatorshared; }
import greenfoot.*; import greenfoot.util.*; import java.awt.geom.Point2D; public class MenuNavButton extends TextButton { private static final int SPEED = 30; private double theta; private Point2D.Double velocity; private int numSteps; private int count; private boolean moving; Point2D.Double menuLocation; public MenuNavButton(String text, Point2D.Double menuLocation) { super(text); this.menuLocation = menuLocation; this.velocity = new Point2D.Double(); } private void setupManeuver(Point2D.Double start, Point2D.Double end) { double dy = end.y - start.y; double dx = end.x - start.x; this.numSteps = (int) Math.round(Math.sqrt(dx*dx + dy*dy)/SPEED); this.theta = Math.atan2(dy, dx); velocity.x = SPEED*Math.cos(theta); velocity.y = SPEED*Math.sin(theta); count = 0; moving = true; } @Override public void onClick() { Point2D.Double currentLocation = new Point2D.Double(world.getCameraX(), world.getCameraY()); setupManeuver(currentLocation, this.menuLocation); } private void updateManeuver() { if (++count < numSteps) { int x = (int) Math.round(world.getCameraX() + velocity.x); int y = (int) Math.round(world.getCameraY() + velocity.y); moveCamera(x, y); } else { moveCamera((int) menuLocation.x, (int)menuLocation.y); moving = false; } } @Override public void act() { if (moving) { updateManeuver(); } else { super.act(); } } }
package com.wanglu.movcat.repository; import com.wanglu.movcat.model.Comment; import com.wanglu.movcat.model.GiftArticle; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface CommentRepository extends JpaRepository<Comment, Integer>{ Comment findFirstByIsIndexAndAndGiftArticleId(String IsIndex, Integer giftArticleId); List<Comment> findByIsSonAndIsGrandsonAndGiftArticleId(String isSon, String isGrandson, Integer giftArticleId); List<Comment> findByFatherIdAndIsSon(Integer fatherId, String isSon); List<Comment> findByFatherIdAndIsGrandson(Integer fatherId, String isGrandson); }
package com.example.journey_datn.Model; import android.os.Parcel; import android.os.Parcelable; import androidx.room.Ignore; import androidx.room.PrimaryKey; public class User implements Parcelable { private String idUser; private String firstName, lastName, username; public User(String id, String firstName, String lastName, String username) { this.idUser = id; this.firstName = firstName; this.lastName = lastName; this.username = username; } public User(String firstName, String lastName, String username) { this.firstName = firstName; this.lastName = lastName; this.username = username; } public User() { } protected User(Parcel in) { idUser = in.readString(); firstName = in.readString(); lastName = in.readString(); username = in.readString(); } public static final Creator<User> CREATOR = new Creator<User>() { @Override public User createFromParcel(Parcel in) { return new User(in); } @Override public User[] newArray(int size) { return new User[size]; } }; public String getId() { return idUser; } public void setId(String id) { this.idUser = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(idUser); dest.writeString(firstName); dest.writeString(lastName); dest.writeString(username); } }
package org.adv25.ADVNTRIP.Databases; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.adv25.ADVNTRIP.Tools.Config; import java.sql.Connection; import java.sql.SQLException; import java.time.ZoneId; public class DataSource { private static HikariConfig configHikari = new HikariConfig(); private static HikariDataSource ds; static { // Config config = Config.getInstance(); // String host = config.getProperties("mysqlHost"); // String user = config.getProperties("mysqlUser"); // String db = config.getProperties("mysqlDb"); // String port = config.getProperties("mysqlPort"); // configHikari.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + db + "?serverTimezone=" + ZoneId.systemDefault()); // configHikari.setUsername(config.getProperties("mysqlUser")); // configHikari.setPassword(config.getProperties("mysqlPass")); // configHikari.addDataSourceProperty( "cachePrepStmts" , "true" ); // configHikari.addDataSourceProperty( "prepStmtCacheSize" , "250" ); // configHikari.addDataSourceProperty( "prepStmtCacheSqlLimit" , "2048" ); String configFile = "src/main/resources/db.properties"; HikariConfig cfg = new HikariConfig(configFile); ds = new HikariDataSource(cfg); } private DataSource() {} public static Connection getConnection() throws SQLException { return ds.getConnection(); } }
package com.example.lenovo.medleybranch; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.textfield.TextInputEditText; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.Query; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class AddNewBill extends AppCompatActivity { TextInputEditText etCurrentDateForBill; TextInputEditText etCarRegistrationNumber; TextInputEditText etProductNumberForBill; TextInputEditText etProductDescriptionForBill; TextInputEditText etDiscountInRupees; TextInputEditText etDiscountInPercentage; Button btnAddProductToBill; TextView product_number_for_total_bill,product_name_for_total_bill,total_customer_bill; TextView total_discounted_amount; TextView product_price_for_total_bill; Button btnProceedBill, btnApplyDiscount; Button validateCustomer; boolean flagValidate; String pname; float pprice; int totalprice; //Button btnAddCustomerFirst; final int ADDNEWBILL = 2; ArrayList<String> productsIDsToUpdateStock; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_new_bill); etDiscountInRupees = findViewById(R.id.etDiscountInRupees); etDiscountInPercentage = findViewById(R.id.etDiscountInPercentage); total_discounted_amount = findViewById(R.id.total_discounted_amount); productsIDsToUpdateStock = new ArrayList<>(); etCurrentDateForBill = findViewById(R.id.etCurrentDateForBill); etCarRegistrationNumber = findViewById(R.id.etCarRegistrationNumber); etProductNumberForBill = findViewById(R.id.etProductNumberForBill); etProductDescriptionForBill = findViewById(R.id.etProductDescriptionForBill); btnAddProductToBill = findViewById(R.id.btnAddProductToBill); product_number_for_total_bill = findViewById(R.id.product_number_for_total_bill); product_name_for_total_bill = findViewById(R.id.product_name_for_total_bill); total_customer_bill = findViewById(R.id.total_customer_bill); btnProceedBill = findViewById(R.id.btnProceedBill); btnApplyDiscount = findViewById(R.id.btnApplyDiscount); validateCustomer = findViewById(R.id.validateCustomer); product_price_for_total_bill = findViewById(R.id.product_price_for_total_bill); // btnAddCustomerFirst = findViewById(R.id.btnAddCustomerFirst); btnApplyDiscount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String dis = etDiscountInPercentage.getText().toString().trim(); String price = etDiscountInRupees.getText().toString().trim(); if(dis.isEmpty() && price.isEmpty()) { } else { if(!dis.isEmpty()) { float temp = Float.parseFloat(dis); float totaldisbill = totalprice*temp/100; totaldisbill = totalprice-totaldisbill; total_discounted_amount.setText(totaldisbill+""); } if(!price.isEmpty()) { float temp = Float.parseFloat(price); float totaldisbill = totalprice-temp; total_discounted_amount.setText(totaldisbill+""); } } } }); validateCustomer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String carRegistrationID = etCarRegistrationNumber.getText().toString().trim(); if(carRegistrationID.isEmpty()) { Toast.makeText(AddNewBill.this, "Enter Car Registration Number", Toast.LENGTH_SHORT).show(); } else { DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(); Query q = dbRef.child("Customers"); q.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot data: dataSnapshot.getChildren()) { if(data.child("carRegistrationNumber").getValue().toString().equals(carRegistrationID)) { validateCustomer.setText("VALIDATED"); etCurrentDateForBill.setText(Add_Product.getCurrentDate()); flagValidate = false; Toast.makeText(AddNewBill.this, data.child("carRegistrationNumber").getValue()+"", Toast.LENGTH_SHORT).show(); break; } } if(flagValidate) { startActivityForResult(new Intent(AddNewBill.this, AddCustomer.class),ADDNEWBILL); finish(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } }); btnAddProductToBill.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(flagValidate) { Toast.makeText(AddNewBill.this, "Validate Customer First.", Toast.LENGTH_SHORT).show(); } else { final String productNumber = etProductNumberForBill.getText().toString().trim(); if(productNumber.isEmpty()) { etProductNumberForBill.setBackgroundColor(getResources().getColor(R.color.error)); } else { DatabaseReference dbRefForStock = FirebaseDatabase.getInstance().getReference(); Query query = dbRefForStock.child("Stocks"); query.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { boolean productFoundInStock = false; final boolean[] informationFetchedFromProducts = {false}; for(DataSnapshot stockData: dataSnapshot.getChildren()) { if(stockData.child("productId").getValue().toString().trim().equals(productNumber)) { productFoundInStock=true; int quantity = Integer.parseInt(stockData.child("productLeftQuantity").getValue().toString().trim()); // Toast.makeText(AddNewBill.this, "Quantity : "+quantity, Toast.LENGTH_SHORT).show(); if(quantity>0) { // fetching information of product price final DatabaseReference[] dbRef = {FirebaseDatabase.getInstance().getReference()}; Query q = dbRef[0].child("Products"); q.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot data: dataSnapshot.getChildren()) { // Toast.makeText(AddNewBill.this, ""+data.child("productId").getValue().toString(), Toast.LENGTH_SHORT).show(); if(data.child("productNumber").getValue().toString().trim().equals(productNumber)) { productsIDsToUpdateStock.add(productNumber); pname = data.child("productName").getValue().toString().trim(); if(etProductDescriptionForBill.getText().toString().isEmpty()) { pprice = Float.parseFloat(data.child("salePrice").getValue().toString().trim()); } else { String getDescription = etProductDescriptionForBill.getText().toString().trim(); getDescription = getDescription.replaceAll("[^\\d.]", ""); float litre = Float.parseFloat(getDescription); pprice = Float.parseFloat(data.child("salePrice").getValue().toString().trim()); String getFirebaseDescription = data.child("productDescription").getValue().toString().trim(); getFirebaseDescription = getFirebaseDescription.replaceAll("[^\\d.]", ""); float firebaselitre = Float.parseFloat(getFirebaseDescription); pprice = (pprice/firebaselitre)*litre; } totalprice+=pprice; String temp =product_name_for_total_bill.getText().toString().trim()+"\n"+pname; product_name_for_total_bill.setText(temp); temp = product_price_for_total_bill.getText().toString().trim()+"\n"+pprice; product_price_for_total_bill.setText(temp); total_customer_bill.setText(totalprice+""); total_discounted_amount.setText(totalprice+""); informationFetchedFromProducts[0] =true; etProductNumberForBill.setText(""); etProductDescriptionForBill.setText(""); break; } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } else { Toast.makeText(AddNewBill.this, "Sorry the product is out of stock", Toast.LENGTH_SHORT).show(); } } } if(!productFoundInStock) { Toast.makeText(AddNewBill.this, "Sorry This Product Not Found", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } } } }); btnProceedBill.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final DatabaseReference updateStocks = FirebaseDatabase.getInstance().getReference(); Query q = updateStocks.child("Stocks"); for(int i=0; i<productsIDsToUpdateStock.size(); i++) { DatabaseReference getStockRef = FirebaseDatabase.getInstance().getReference("Stocks"); final int finalI = i; getStockRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { for(DataSnapshot data:dataSnapshot.getChildren()) { if(data.child("productId").getValue().toString().equals(productsIDsToUpdateStock.get(finalI))) { String key = data.getKey(); Map<String, Object> map = new HashMap<>(); int quantity = Integer.parseInt(data.child("productLeftQuantity").getValue().toString()); quantity--; map.put("productLeftQuantity", quantity); updateStocks.child("Stocks"). child(key). updateChildren(map) .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { } }); } } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { } }); } generateCustomerBill(); } }); } public void generateCustomerBill() { DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Customer_bill"); String uniqueBillId = ref.push().getKey(); String ID = uniqueBillId; String CarID = etCarRegistrationNumber.getText().toString().trim().toUpperCase(); String billDate = etCurrentDateForBill.getText().toString().trim(); String nextDate = etCurrentDateForBill.getText().toString().trim(); String meterReading = ""; Customer_Bill customer_bill = new Customer_Bill(ID, CarID, billDate, nextDate, meterReading); ref.child(ID).setValue(customer_bill); DatabaseReference addProductsToCustomerProducts = FirebaseDatabase.getInstance().getReference("Customer_Products"); for(int i=0; i<productsIDsToUpdateStock.size(); i++) { CustomerProductsList customerProductsList = new CustomerProductsList(ID,productsIDsToUpdateStock.get(i)); addProductsToCustomerProducts.child(ID).setValue(customerProductsList); } } @Override protected void onStart() { super.onStart(); flagValidate = true; totalprice = 0; pprice=0; } @Override protected void onRestart() { super.onRestart(); flagValidate=true; } }
import java.util.HashSet; import java.util.Scanner; import java.util.Set; class Main { public static void main(String[] args) { // put your code here Scanner scanner = new Scanner(System.in); int d = scanner.nextInt(); //System.out.println(d); Set<String> enterSet = new HashSet<>(); for (int i = 0; i <= d; i++){ String string = scanner.nextLine().toLowerCase(); enterSet.add(string); } int l = Integer.parseInt(scanner.nextLine()); Set<String> resultSet = new HashSet<>(); for (int i = 0; i < l; i++){ String[] s = scanner.nextLine().split(" "); for (String ss: s ) { if (!enterSet.contains(ss.toLowerCase())) resultSet.add(ss.toLowerCase()); } } for (String ss: resultSet ) { System.out.println(ss); } } }
package com.travelportal.vm; import java.util.ArrayList; import java.util.List; public class SearchSpecialsVM { public long id; public String fromDate; public String toDate; public String promotionName; public Long supplierCode; public List<String> roomTypes = new ArrayList<>(); public List<SpecialsMarketVM> markets = new ArrayList<SpecialsMarketVM>(); }
package saim_only_05_01; import java.util.ArrayList; import java.util.Arrays; public class TargetWord { public static void main(String[] args) { ArrayList<String> words =new ArrayList<>(Arrays.asList("java","html","css","java", "javascript","selenium")); int count= 0; String target = "java"; for(String each : words){ if(each.contains("java")){ count ++; } } System.out.println("There are "+ count+" "+ target +" in our String"); } }