text
stringlengths 10
2.72M
|
|---|
package com.youthchina.dto.applicant;
import com.youthchina.domain.qingyang.ResumeJson;
import com.youthchina.dto.ResponseDTO;
import java.util.ArrayList;
import java.util.List;
/**
* @program: youthchina
* @description: 简历json返回
* @author: Qinghong Wang
* @create: 2019-02-28 10:04
**/
public class ResumeJsonResponseDTO implements ResponseDTO<ResumeJson> {
private Integer id;
private List<String> jsons;
public ResumeJsonResponseDTO() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getJsons() {
return jsons;
}
public void setJsons(List<String> jsons) {
this.jsons = jsons;
}
@Override
public void convertToDTO(ResumeJson domain) {
this.id = domain.getResumeId();
this.jsons = new ArrayList<>();
this.jsons.add(domain.getJsonContent());
}
}
|
package test.nz.org.take.r2ml.c.generated;
import nz.org.take.rt.*;
/**
* Class generated by the take compiler.
* @version Tue Nov 20 16:02:05 GMT+01:00 2007
*/
@SuppressWarnings("unchecked")
class KBFragement_isFamily_11 {
/**
* Method generated for query /isFamily[in,in]
* @param slot1 input parameter generated from slot 0
* @param slot2 input parameter generated from slot 1
* @return an iterator for instances of isFamily
*/
public static ResultSet<isFamily> isFamily_11(
final test.nz.org.take.r2ml.c.Person slot1,
final test.nz.org.take.r2ml.c.Person slot2) {
DerivationController _derivation = new DefaultDerivationController();
ResultSet<isFamily> _result = new ResultSet(KBFragement_isFamily_11.isFamily_11(
slot1, slot2, _derivation), _derivation);
return _result;
}
/**
* Method generated for query /isFamily[in,in]
* @param slot1 input parameter generated from slot 0
* @param slot2 input parameter generated from slot 1
* @return an iterator for instances of isFamily
*/
static ResourceIterator<isFamily> isFamily_11(
final test.nz.org.take.r2ml.c.Person slot1,
final test.nz.org.take.r2ml.c.Person slot2,
final DerivationController _derivation) {
final int _derivationlevel = _derivation.getDepth();
ResourceIterator<isFamily> result = new IteratorChain<isFamily>(1) {
public Object getIteratorOrObject(int pos) {
switch (pos) {
// equalityTestRule IF lastname(<person1>,<lastname1>) AND lastname(<person2>,<lastname2>) AND equals(<lastname1>,<lastname2>) AND equals(<lastname2>,<lastname1>) THEN /isFamily(<person1>,<person2>)
case 0:
return isFamily_11_0(slot1, slot2,
_derivation.reset(_derivationlevel));
default:
return EmptyIterator.DEFAULT;
} // switch(pos)
} // getIterator()
public String getRuleRef(int pos) {
switch (pos) {
// equalityTestRule IF lastname(<person1>,<lastname1>) AND lastname(<person2>,<lastname2>) AND equals(<lastname1>,<lastname2>) AND equals(<lastname2>,<lastname1>) THEN /isFamily(<person1>,<person2>)
case 0:
return "equalityTestRule";
default:
return "";
} // switch(pos)
} // getRuleRef()
};
return result;
}
/**
* Method generated for query /isFamily[in,in]
* @param slot1 input parameter generated from slot 0
* @param slot2 input parameter generated from slot 1
* @return an iterator for instances of isFamily
*/
private static ResourceIterator<isFamily> isFamily_11_0(
final test.nz.org.take.r2ml.c.Person slot1,
final test.nz.org.take.r2ml.c.Person slot2,
final DerivationController _derivation) {
_derivation.log("equalityTestRule", DerivationController.RULE, slot1,
slot2);
// Variable bindings in rule: IF lastname(<person1>,<lastname1>) AND lastname(<person2>,<lastname2>) AND equals(<lastname1>,<lastname2>) AND equals(<lastname2>,<lastname1>) THEN /isFamily(<person1>,<person2>)
class bindingsInRule1 {
// Property generated for term "<person1>"
test.nz.org.take.r2ml.c.Person p1;
// Property generated for term "<person2>"
test.nz.org.take.r2ml.c.Person p2;
// Property generated for term "<lastname2>"
java.lang.String p3;
// Property generated for term "<lastname1>"
java.lang.String p4;
}
;
final bindingsInRule1 bindings = new bindingsInRule1();
bindings.p1 = slot1;
bindings.p2 = slot2;
// code for prereq lastname(<person1>,<lastname1>)
final ResourceIterator<lastname> iterator1 = KBFragement_lastname_10.lastname_10(slot1,
_derivation.increaseDepth());
// code for prereq lastname(<person2>,<lastname2>)
final ResourceIterator<lastname> iterator2 = new NestedIterator<lastname, lastname>(iterator1) {
public ResourceIterator<lastname> getNextIterator(
lastname object) {
bindings.p1 = object.slot1;
bindings.p4 = object.slot2;
return KBFragement_lastname_10.lastname_10(bindings.p2,
_derivation.increaseDepth());
}
};
// code for prereq equals(<lastname1>,<lastname2>)
final ResourceIterator<equals> iterator3 = new NestedIterator<lastname, equals>(iterator2) {
public ResourceIterator<equals> getNextIterator(lastname object) {
bindings.p2 = object.slot1;
bindings.p3 = object.slot2;
return KBFragement_equals_11.equals_11(bindings.p4,
bindings.p3, _derivation.increaseDepth());
}
};
// code for prereq equals(<lastname2>,<lastname1>)
final ResourceIterator<equals> iterator4 = new NestedIterator<equals, equals>(iterator3) {
public ResourceIterator<equals> getNextIterator(equals object) {
bindings.p4 = object.slot1;
bindings.p3 = (java.lang.String) object.slot2;
return KBFragement_equals_11.equals_11(bindings.p3,
bindings.p4, _derivation.increaseDepth());
}
};
// code for prereq /isFamily(<person1>,<person2>)
final ResourceIterator<isFamily> iterator5 = new NestedIterator<equals, isFamily>(iterator4) {
public ResourceIterator<isFamily> getNextIterator(equals object) {
bindings.p3 = object.slot1;
bindings.p4 = (java.lang.String) object.slot2;
return new SingletonIterator(new isFamily(bindings.p1,
bindings.p2));
}
};
return iterator5;
}
}
|
/*
* 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 View;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.io.IOException;
import javax.swing.ImageIcon;
/**
*
* @author DESENVOLVIMENTO
*/
public class Cadastro extends javax.swing.JFrame {
Font roboto = null;
Font rodape = null;
public Cadastro() {
initComponents();
try{
roboto = Font.createFont(Font.TRUETYPE_FONT, getClass().getClassLoader().getResourceAsStream("fonts/Roboto-Regular.ttf"));
}
catch(IOException|FontFormatException e){
System.out.println("Erro: " + e);
}
rodape = roboto.deriveFont(Font.PLAIN, 13);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(rodape);
jLabel_Rodape1.setFont(rodape);
jLabel_Rodape2.setFont(rodape);
}
/**
* 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() {
btn_cadastro = new javax.swing.JLabel();
txt_comp = new javax.swing.JTextField();
form_Comp = new javax.swing.JLabel();
txt_numero = new javax.swing.JTextField();
form_Numero = new javax.swing.JLabel();
txt_estado = new javax.swing.JTextField();
form_Estado = new javax.swing.JLabel();
txt_cidade = new javax.swing.JTextField();
form_Cidade = new javax.swing.JLabel();
txt_bairro = new javax.swing.JTextField();
form_Bairro = new javax.swing.JLabel();
txt_rua = new javax.swing.JTextField();
form_Rua = new javax.swing.JLabel();
txt_CPF = new javax.swing.JTextField();
form_CPF = new javax.swing.JLabel();
txt_nascimento = new javax.swing.JTextField();
form_Nascimento = new javax.swing.JLabel();
txt_cargo = new javax.swing.JTextField();
form_Cargo = new javax.swing.JLabel();
txt_celular = new javax.swing.JTextField();
form_Celular = new javax.swing.JLabel();
txt_nome = new javax.swing.JTextField();
form_Nome = new javax.swing.JLabel();
txt_email = new javax.swing.JTextField();
form_Email = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel_Rodape2 = new javax.swing.JLabel();
jLabel_Rodape1 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Hotel Plus Service - Cadastro");
setResizable(false);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
btn_cadastro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/btn_CadastroF_A.png"))); // NOI18N
btn_cadastro.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
btn_cadastro.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
btn_cadastroMouseEntered(evt);
}
public void mouseExited(java.awt.event.MouseEvent evt) {
btn_cadastroMouseExited(evt);
}
});
getContentPane().add(btn_cadastro, new org.netbeans.lib.awtextra.AbsoluteConstraints(87, 435, -1, -1));
txt_comp.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_comp.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_comp.setForeground(new java.awt.Color(83, 83, 83));
txt_comp.setBorder(null);
txt_comp.setOpaque(false);
txt_comp.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_compActionPerformed(evt);
}
});
txt_comp.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_compKeyPressed(evt);
}
});
getContentPane().add(txt_comp, new org.netbeans.lib.awtextra.AbsoluteConstraints(555, 380, 190, 30));
form_Comp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Comp_A.png"))); // NOI18N
getContentPane().add(form_Comp, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 360, -1, -1));
txt_numero.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_numero.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_numero.setForeground(new java.awt.Color(83, 83, 83));
txt_numero.setBorder(null);
txt_numero.setOpaque(false);
txt_numero.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_numeroActionPerformed(evt);
}
});
txt_numero.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_numeroKeyPressed(evt);
}
});
getContentPane().add(txt_numero, new org.netbeans.lib.awtextra.AbsoluteConstraints(335, 380, 190, 30));
form_Numero.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Numero_A.png"))); // NOI18N
getContentPane().add(form_Numero, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 360, -1, -1));
txt_estado.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_estado.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_estado.setForeground(new java.awt.Color(83, 83, 83));
txt_estado.setBorder(null);
txt_estado.setOpaque(false);
txt_estado.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_estadoActionPerformed(evt);
}
});
txt_estado.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_estadoKeyPressed(evt);
}
});
getContentPane().add(txt_estado, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 380, 180, 30));
form_Estado.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Estado_A.png"))); // NOI18N
getContentPane().add(form_Estado, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 360, -1, -1));
txt_cidade.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_cidade.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_cidade.setForeground(new java.awt.Color(83, 83, 83));
txt_cidade.setBorder(null);
txt_cidade.setOpaque(false);
txt_cidade.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_cidadeActionPerformed(evt);
}
});
txt_cidade.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_cidadeKeyPressed(evt);
}
});
getContentPane().add(txt_cidade, new org.netbeans.lib.awtextra.AbsoluteConstraints(555, 320, 190, 30));
form_Cidade.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Cidade_A.png"))); // NOI18N
getContentPane().add(form_Cidade, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 300, -1, -1));
txt_bairro.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_bairro.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_bairro.setForeground(new java.awt.Color(83, 83, 83));
txt_bairro.setBorder(null);
txt_bairro.setOpaque(false);
txt_bairro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_bairroActionPerformed(evt);
}
});
txt_bairro.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_bairroKeyPressed(evt);
}
});
getContentPane().add(txt_bairro, new org.netbeans.lib.awtextra.AbsoluteConstraints(335, 320, 190, 30));
form_Bairro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Bairro_A.png"))); // NOI18N
getContentPane().add(form_Bairro, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 300, -1, -1));
txt_rua.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_rua.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_rua.setForeground(new java.awt.Color(83, 83, 83));
txt_rua.setBorder(null);
txt_rua.setOpaque(false);
txt_rua.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_ruaActionPerformed(evt);
}
});
txt_rua.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_ruaKeyPressed(evt);
}
});
getContentPane().add(txt_rua, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 320, 190, 30));
form_Rua.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Rua_A.png"))); // NOI18N
getContentPane().add(form_Rua, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 300, -1, -1));
txt_CPF.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_CPF.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_CPF.setForeground(new java.awt.Color(83, 83, 83));
txt_CPF.setBorder(null);
txt_CPF.setOpaque(false);
txt_CPF.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_CPFActionPerformed(evt);
}
});
txt_CPF.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_CPFKeyPressed(evt);
}
});
getContentPane().add(txt_CPF, new org.netbeans.lib.awtextra.AbsoluteConstraints(555, 220, 190, 30));
form_CPF.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_CPF_A.png"))); // NOI18N
getContentPane().add(form_CPF, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 200, -1, -1));
txt_nascimento.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_nascimento.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_nascimento.setForeground(new java.awt.Color(83, 83, 83));
txt_nascimento.setBorder(null);
txt_nascimento.setOpaque(false);
txt_nascimento.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_nascimentoActionPerformed(evt);
}
});
txt_nascimento.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_nascimentoKeyPressed(evt);
}
});
getContentPane().add(txt_nascimento, new org.netbeans.lib.awtextra.AbsoluteConstraints(335, 220, 190, 30));
form_Nascimento.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Nasc_A.png"))); // NOI18N
getContentPane().add(form_Nascimento, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 200, -1, -1));
txt_cargo.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_cargo.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_cargo.setForeground(new java.awt.Color(83, 83, 83));
txt_cargo.setBorder(null);
txt_cargo.setOpaque(false);
txt_cargo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_cargoActionPerformed(evt);
}
});
txt_cargo.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_cargoKeyPressed(evt);
}
});
getContentPane().add(txt_cargo, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 220, 190, 30));
form_Cargo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Cargo_A.png"))); // NOI18N
getContentPane().add(form_Cargo, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 200, -1, -1));
txt_celular.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_celular.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_celular.setForeground(new java.awt.Color(83, 83, 83));
txt_celular.setBorder(null);
txt_celular.setOpaque(false);
txt_celular.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_celularActionPerformed(evt);
}
});
txt_celular.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_celularKeyPressed(evt);
}
});
getContentPane().add(txt_celular, new org.netbeans.lib.awtextra.AbsoluteConstraints(555, 160, 190, 30));
form_Celular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Cel_A.png"))); // NOI18N
getContentPane().add(form_Celular, new org.netbeans.lib.awtextra.AbsoluteConstraints(540, 140, -1, -1));
txt_nome.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_nome.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_nome.setForeground(new java.awt.Color(83, 83, 83));
txt_nome.setBorder(null);
txt_nome.setOpaque(false);
txt_nome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_nomeActionPerformed(evt);
}
});
txt_nome.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_nomeKeyPressed(evt);
}
});
getContentPane().add(txt_nome, new org.netbeans.lib.awtextra.AbsoluteConstraints(335, 160, 180, 30));
form_Nome.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Nome_A.png"))); // NOI18N
getContentPane().add(form_Nome, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 140, -1, -1));
txt_email.setBackground(new java.awt.Color(255, 255, 255, 0));
txt_email.setFont(new java.awt.Font("Tahoma", 0, 13)); // NOI18N
txt_email.setForeground(new java.awt.Color(83, 83, 83));
txt_email.setBorder(null);
txt_email.setOpaque(false);
txt_email.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txt_emailActionPerformed(evt);
}
});
txt_email.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
txt_emailKeyPressed(evt);
}
});
getContentPane().add(txt_email, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 160, 180, 30));
form_Email.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/form_Email_A.png"))); // NOI18N
getContentPane().add(form_Email, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 140, -1, -1));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/BG_Cadastro.png"))); // NOI18N
getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 40, -1, -1));
jLabel_Rodape2.setForeground(new java.awt.Color(255, 255, 255));
jLabel_Rodape2.setText("de Análise e Desenvolvimento de Sistemas peos Discentes Caio Alexandre de Sousa Ramos e Lucas Eduardo Sampaio Andrade.");
getContentPane().add(jLabel_Rodape2, new org.netbeans.lib.awtextra.AbsoluteConstraints(65, 560, -1, -1));
jLabel_Rodape1.setForeground(new java.awt.Color(255, 255, 255));
jLabel_Rodape1.setText("Este software é um protótipo desenvolvido durante uma avaliação da disciplina de Linguagem de Programação II no curso Tecnológico");
getContentPane().add(jLabel_Rodape1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 545, -1, -1));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/assets/BG_login.png"))); // NOI18N
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void txt_emailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_emailActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_emailActionPerformed
private void txt_emailKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_emailKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Email_B.png"));
form_Email.setIcon( ii );
}//GEN-LAST:event_txt_emailKeyPressed
private void txt_nomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_nomeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_nomeActionPerformed
private void txt_nomeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_nomeKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Nome_B.png"));
form_Nome.setIcon( ii );
}//GEN-LAST:event_txt_nomeKeyPressed
private void txt_celularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_celularActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_celularActionPerformed
private void txt_celularKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_celularKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Cel_B.png"));
form_Celular.setIcon( ii );
}//GEN-LAST:event_txt_celularKeyPressed
private void txt_cargoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_cargoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_cargoActionPerformed
private void txt_cargoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_cargoKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Cargo_B.png"));
form_Cargo.setIcon( ii );
}//GEN-LAST:event_txt_cargoKeyPressed
private void txt_nascimentoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_nascimentoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_nascimentoActionPerformed
private void txt_nascimentoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_nascimentoKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Nasc_B.png"));
form_Nascimento.setIcon( ii );
}//GEN-LAST:event_txt_nascimentoKeyPressed
private void txt_CPFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_CPFActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_CPFActionPerformed
private void txt_CPFKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_CPFKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_CPF_B.png"));
form_CPF.setIcon( ii );
}//GEN-LAST:event_txt_CPFKeyPressed
private void txt_compActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_compActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_compActionPerformed
private void txt_compKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_compKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Comp_B.png"));
form_Comp.setIcon( ii );
}//GEN-LAST:event_txt_compKeyPressed
private void txt_numeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_numeroActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_numeroActionPerformed
private void txt_numeroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_numeroKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Numero_B.png"));
form_Numero.setIcon( ii );
}//GEN-LAST:event_txt_numeroKeyPressed
private void txt_estadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_estadoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_estadoActionPerformed
private void txt_estadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_estadoKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Estado_B.png"));
form_Estado.setIcon( ii );
}//GEN-LAST:event_txt_estadoKeyPressed
private void txt_cidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_cidadeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_cidadeActionPerformed
private void txt_cidadeKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_cidadeKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Cidade_B.png"));
form_Cidade.setIcon( ii );
}//GEN-LAST:event_txt_cidadeKeyPressed
private void txt_bairroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_bairroActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_bairroActionPerformed
private void txt_bairroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_bairroKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Bairro_B.png"));
form_Bairro.setIcon( ii );
}//GEN-LAST:event_txt_bairroKeyPressed
private void txt_ruaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_ruaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_ruaActionPerformed
private void txt_ruaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_ruaKeyPressed
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/form_Rua_B.png"));
form_Rua.setIcon( ii );
}//GEN-LAST:event_txt_ruaKeyPressed
private void btn_cadastroMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cadastroMouseEntered
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/btn_CadastroF_B.png"));
btn_cadastro.setIcon( ii );
}//GEN-LAST:event_btn_cadastroMouseEntered
private void btn_cadastroMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btn_cadastroMouseExited
ImageIcon ii = new ImageIcon(getClass().getResource("/assets/btn_CadastroF_A.png"));
btn_cadastro.setIcon( ii );
}//GEN-LAST:event_btn_cadastroMouseExited
/**
* @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(Cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Cadastro().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel btn_cadastro;
private javax.swing.JLabel form_Bairro;
private javax.swing.JLabel form_CPF;
private javax.swing.JLabel form_Cargo;
private javax.swing.JLabel form_Celular;
private javax.swing.JLabel form_Cidade;
private javax.swing.JLabel form_Comp;
private javax.swing.JLabel form_Email;
private javax.swing.JLabel form_Estado;
private javax.swing.JLabel form_Nascimento;
private javax.swing.JLabel form_Nome;
private javax.swing.JLabel form_Numero;
private javax.swing.JLabel form_Rua;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel_Rodape1;
private javax.swing.JLabel jLabel_Rodape2;
private javax.swing.JTextField txt_CPF;
private javax.swing.JTextField txt_bairro;
private javax.swing.JTextField txt_cargo;
private javax.swing.JTextField txt_celular;
private javax.swing.JTextField txt_cidade;
private javax.swing.JTextField txt_comp;
private javax.swing.JTextField txt_email;
private javax.swing.JTextField txt_estado;
private javax.swing.JTextField txt_nascimento;
private javax.swing.JTextField txt_nome;
private javax.swing.JTextField txt_numero;
private javax.swing.JTextField txt_rua;
// End of variables declaration//GEN-END:variables
}
|
package com.tt.miniapp.media.base;
import android.util.Size;
import java.util.ArrayList;
import java.util.List;
public class MediaEditParams {
private List<AudioElement> audioList;
private int bitRate;
private int fps;
private String outputPath;
private Size outputSize;
private List<StickerElement> stickerList;
private List<String> transitionList;
private List<VideoElement> videoList;
public MediaEditParams(Builder paramBuilder) {
this.outputPath = paramBuilder.outputPath;
this.outputSize = paramBuilder.outputSize;
this.fps = paramBuilder.outFps;
this.bitRate = paramBuilder.outBitRate;
this.videoList = paramBuilder.videos;
this.audioList = paramBuilder.audios;
this.stickerList = paramBuilder.stickers;
this.transitionList = paramBuilder.transitions;
}
public List<AudioElement> getAudioList() {
return this.audioList;
}
public int getBitRate() {
return this.bitRate;
}
public int getFps() {
return this.fps;
}
public String getOutputPath() {
return this.outputPath;
}
public Size getOutputSize() {
return this.outputSize;
}
public List<StickerElement> getStickerList() {
return this.stickerList;
}
public List<String> getTransitionList() {
return this.transitionList;
}
public List<VideoElement> getVideoList() {
return this.videoList;
}
public static class AudioElement {
public int endTime;
public String path;
public int seqInTime;
public int seqOutTime;
public int startTime;
public AudioElement(String param1String, int param1Int1, int param1Int2, int param1Int3, int param1Int4) {
this.path = param1String;
this.startTime = param1Int1;
this.endTime = param1Int2;
this.seqInTime = param1Int3;
this.seqOutTime = param1Int4;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder("AudioElement{path='");
stringBuilder.append(this.path);
stringBuilder.append('\'');
stringBuilder.append(", startTime=");
stringBuilder.append(this.startTime);
stringBuilder.append(", endTime=");
stringBuilder.append(this.endTime);
stringBuilder.append(", seqInTime=");
stringBuilder.append(this.seqInTime);
stringBuilder.append(", seqOutTime=");
stringBuilder.append(this.seqOutTime);
stringBuilder.append('}');
return stringBuilder.toString();
}
}
public static class Builder {
public List<MediaEditParams.AudioElement> audios = new ArrayList<MediaEditParams.AudioElement>();
public int outBitRate;
public int outFps;
public String outputPath;
public Size outputSize;
public List<MediaEditParams.StickerElement> stickers = new ArrayList<MediaEditParams.StickerElement>();
public List<String> transitions = new ArrayList<String>();
public List<MediaEditParams.VideoElement> videos = new ArrayList<MediaEditParams.VideoElement>();
public Builder addAudioElement(MediaEditParams.AudioElement param1AudioElement) {
this.audios.add(param1AudioElement);
return this;
}
public Builder addStickerElement(MediaEditParams.StickerElement param1StickerElement) {
this.stickers.add(param1StickerElement);
return this;
}
public Builder addTransition(String param1String) {
this.transitions.add(param1String);
return this;
}
public Builder addVideoElement(MediaEditParams.VideoElement param1VideoElement) {
this.videos.add(param1VideoElement);
return this;
}
public MediaEditParams build() {
return new MediaEditParams(this);
}
public Builder outBitRate(int param1Int) {
this.outBitRate = param1Int;
return this;
}
public Builder outFps(int param1Int) {
this.outFps = param1Int;
return this;
}
public Builder outputPath(String param1String) {
this.outputPath = param1String;
return this;
}
public Builder outputSize(Size param1Size) {
this.outputSize = param1Size;
return this;
}
}
public static class StickerElement {
public float height;
public String path;
public float width;
public float x;
public float y;
public StickerElement(String param1String, float param1Float1, float param1Float2, float param1Float3, float param1Float4) {
this.path = param1String;
this.x = param1Float1;
this.y = param1Float2;
this.width = param1Float3;
this.height = param1Float4;
}
}
public static class Transition {}
public static class VideoElement {
public int endTime;
public String path;
public float speed;
public int startTime;
public VideoElement(String param1String, int param1Int1, int param1Int2, float param1Float) {
this.path = param1String;
this.startTime = param1Int1;
this.endTime = param1Int2;
this.speed = param1Float;
}
public String toString() {
StringBuilder stringBuilder = new StringBuilder("VideoElement{path='");
stringBuilder.append(this.path);
stringBuilder.append('\'');
stringBuilder.append(", startTime=");
stringBuilder.append(this.startTime);
stringBuilder.append(", endTime=");
stringBuilder.append(this.endTime);
stringBuilder.append(", speed=");
stringBuilder.append(this.speed);
stringBuilder.append('}');
return stringBuilder.toString();
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\media\base\MediaEditParams.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
|
package recursionAndBacktracking;
public class CountNumberSumPowers {
public static void main(String[] args) {
int x = 100;
int n = 3;
System.out.println(countWays(x, n));
}
// their is an another approach using Dynamic Programming
static int countWays(int x, int n) {
return countWaysUtil(x, n, 1);
}
static int countWaysUtil(int x, int n, int num) {
int val = (int) (x - Math.pow(num, n));
if (val == 0) {
return 1;
}
if (val < 0) {
return 0;
}
return countWaysUtil(val, n, num + 1) + countWaysUtil(x, n, num + 1);
}
}
|
package vanadis.jmx;
import vanadis.core.collections.Generic;
import javax.management.*;
import java.util.List;
import java.util.Map;
import static vanadis.jmx.MapAttributes.attributes;
public class DynamicMapMBean implements DynamicMBean {
private final Map<String, Object> map;
private final boolean writable;
private final boolean toString;
public DynamicMapMBean(Map<String, Object> map) {
this(map, true, false);
}
public DynamicMapMBean(Map<String, Object> map, boolean writable, boolean toString) {
this.map = map;
this.writable = writable;
this.toString = toString;
}
@Override
public Object getAttribute(String attribute) {
return val(map.get(attribute));
}
@Override
public void setAttribute(Attribute attribute) {
if (!writable) {
throw new IllegalStateException("Received set call: " + attribute);
}
String name = attribute.getName();
Object value = map.get(name);
if (value == null) {
throw new IllegalArgumentException("No value " + name);
}
map.put(name, attribute.getValue());
}
@Override
public AttributeList getAttributes(String[] attributes) {
List<Attribute> values = Generic.list();
for (String attribute : attributes) {
Object value = map.get(attribute);
values.add(new Attribute(attribute, val(value)));
}
return new AttributeList();
}
@Override
public AttributeList setAttributes(AttributeList attributes) {
if (!writable) {
throw new IllegalStateException("Received set call: " + attributes);
}
for (Attribute attribute : attributes.asList()) {
setAttribute(attribute);
}
return attributes;
}
@Override
public Object invoke(String actionName, Object[] params, String[] signature) {
throw new IllegalStateException("No invokations!");
}
@Override
public MBeanInfo getMBeanInfo() {
return new MBeanInfo(Map.class.getName(), "A map", attributes(map, writable, toString), null, null, null, null);
}
private Object val(Object value) {
return toString ? String.valueOf(value) : value;
}
}
|
package com.lingnet.vocs.dao.remoteDebug;
import org.hibernate.criterion.DetachedCriteria;
import com.lingnet.common.dao.BaseDao;
import com.lingnet.util.Pager;
import com.lingnet.vocs.entity.Question;
public interface QuestionDao extends BaseDao<Question, String> {
public Pager findByDetachedCriteria(DetachedCriteria detachedCriteria,Pager pager);
}
|
package com.tencent.mm.plugin.exdevice.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class ExdeviceRankDataSourceUI$1 implements OnMenuItemClickListener {
final /* synthetic */ ExdeviceRankDataSourceUI iFe;
ExdeviceRankDataSourceUI$1(ExdeviceRankDataSourceUI exdeviceRankDataSourceUI) {
this.iFe = exdeviceRankDataSourceUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
ExdeviceRankDataSourceUI.a(this.iFe);
return true;
}
}
|
package com.jscherrer.personal.deployment.appspec;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class AppSpecCreatorTest {
private static final String validAppSpecYamlFilePath = "src/test/resources/validAppSpec.yaml";
AppSpecCreator creator = new AppSpecCreator();
@Test
public void canCreateAppSpecYamlWithCorrectFormat() throws IOException {
String expectedYamlContents = new String(Files.readAllBytes(Paths.get(validAppSpecYamlFilePath)));
AppSpecFormat formatToCreate = new AppSpecFormat()
.withFile("Config/config.txt", "/webapps/Config")
.withFile("source", "/webapps/myApp");
String createdAppSpecYaml = creator.createAppSpecYaml(formatToCreate);
Assertions.assertThat(createdAppSpecYaml).isEqualTo(expectedYamlContents);
}
@Test
public void canWriteYamlToFile() throws IOException {
String yamlContents = new String(Files.readAllBytes(Paths.get(validAppSpecYamlFilePath)));
File tmpFileToWriteTo = File.createTempFile("yamlTmpTestFile", ".tmp");
tmpFileToWriteTo.deleteOnExit();
creator.writeYamlToFile(yamlContents, tmpFileToWriteTo.getAbsolutePath());
Assertions.assertThat(tmpFileToWriteTo).exists();
String createdYamlContents = new String(Files.readAllBytes(Paths.get(tmpFileToWriteTo.getAbsolutePath())));
Assertions.assertThat(createdYamlContents).isEqualTo(yamlContents);
}
}
|
package strategy_engine;
public class Program1 {
public static void main(String[] args)
{
Car skoda = Car.NewDieselCar();
Car bmw = Car.NewPetrolCar();
skoda.StartEngine();
bmw.StartEngine();
skoda.Run();
bmw.Run();
skoda.StopEngine();
bmw.StopEngine();
}
}
|
package com.assignment4.question1;
import java.util.*;
/**
* @author C2
*
*/
public class RegionalTransportService {
// Map RTO CODE with Area Name
private static final Map<String, String> rtoCodeMap = new TreeMap<String, String>();
// RTO Codes and Area Names of Regional Transport offices in Bangalore
static {
rtoCodeMap.put("KA-01", "Koramangala");
rtoCodeMap.put("KA-02", "Rajajinagar");
rtoCodeMap.put("KA-03", "Indiranagar");
rtoCodeMap.put("KA-04", "Yeshwanthpur");
rtoCodeMap.put("KA-05", "Jayanagar");
rtoCodeMap.put("KA-50", "Yelahanka");
rtoCodeMap.put("KA-51", "Electronics City");
rtoCodeMap.put("KA-52", "Nelamangala");
rtoCodeMap.put("KA-53", "K.R.Puram");
rtoCodeMap.put("KA-54", "Nagamangala");
rtoCodeMap.put("KA-55", "Mysore East");
rtoCodeMap.put("KA-56", "Basvakalyan");
rtoCodeMap.put("KA-57", "Shantinagar");
}
/**
*
* @param vehicleList
* @return sorted list of vehicles based on Area Name
*/
private static String getKey(String value) {
String requiredKey = "";
for (String key : rtoCodeMap.keySet()) {
if (rtoCodeMap.get(key).equals(value)) {
requiredKey = key;
break;
}
}
return requiredKey;
}
public static List<String> sortVehiclesRegisteredBasedOnArea(List<String> vehicleList) {
List<String> result = new ArrayList<String>();
Map<String, String> rtoCodeMapSorted = new TreeMap<String, String>();
ArrayList<String> listOfKeys = new ArrayList<String>();
ArrayList<String> listOfKeys1 = new ArrayList<String>();
ArrayList<String> listOfValues = new ArrayList<String>();
for (String s : rtoCodeMap.keySet())
listOfKeys.add(s);
for (String s : rtoCodeMap.values())
listOfValues.add(s);
Collections.sort(listOfValues);
for (String s : listOfValues)
rtoCodeMapSorted.put(s, getKey(s));
for (String s : rtoCodeMapSorted.values())
listOfKeys1.add(s);
for (String s : listOfKeys1) {
int count = 0;
for (int i = 0; i < vehicleList.size(); i++) {
if (vehicleList.get(i).substring(0, 5).equals(s) && count <1) {
result.add(vehicleList.get(i));
count++;
}
if (!result.contains(vehicleList.get(i))) {
String s1=vehicleList.get(i);
result.add(s1);
}
}
}
for (String s : result) {
System.out.println(s);
System.out.println(" ");
}
System.out.println(" ");
// List<VehicleNumber> vnList = new ArrayList<VehicleNumber>();
//
// for (String vn : vehicleList) {
// String rtoCode = vn.substring(0, 5);
// String vehicleNo = vn.substring(6);
// String rtoName = rtoCodeMap.get(rtoCode);
// VehicleNumber vnObject = new VehicleNumber(rtoName, vehicleNo);
// vnList.add(vnObject);
// }
// // Collections.sort(vnList);
// vnList.sort(new Comparator<VehicleNumber>() {
//
// @Override
// public int compare(VehicleNumber o1, VehicleNumber o2) {
// int r = o1.getRtoCode().compareTo(o2.getRtoCode());
// if (r == 0) {
// r = o1.getVehicleNumber().compareTo(o2.getVehicleNumber());
// }
//
// return r;
// }
// });
//
// for (VehicleNumber vn : vnList) {
//
// // String n = getKey(vn.getRtoCode()) + "-" + vn.getVehicleNumber();
// // System.out.println(n);
// result.add(getKey(vn.getRtoCode()) + "-" + vn.getVehicleNumber());
// }
return result;
}
}
|
package com.cognitive.newswizard.service.repository;
import java.util.List;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import com.cognitive.newswizard.service.entity.ProperNounEntity;
public interface ProperNounRepository extends MongoRepository<ProperNounEntity, String> {
@Query(value="{}", fields="{rootNoun : 1, _id : 0}")
List<String> findAllRootNouns();
}
|
package com.yt.s_server.home;
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.yt.s_server.R;
import com.yt.s_server.user.Score;
import com.yt.s_server.user.ScoreDBHelper;
import java.util.ArrayList;
public class ScoreActivity extends AppCompatActivity {
ListView scoreList;
TextView totalCredit;
TextView gpa;
Button chooseTerm;
AlertDialog alertDialog3;
ArrayList<Score> scores;
ArrayList<Score> scores_0;
ScoreAdapter scoreAdapter;
int creditSum = 0;
float _gpa = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
scoreList = findViewById(R.id.ll_score);
totalCredit = findViewById(R.id.tv_total_credit);
gpa = findViewById(R.id.tv_gpa);
chooseTerm = findViewById(R.id.btn_choose_term);
try{
ScoreDBHelper dbHelper = new ScoreDBHelper(ScoreActivity.this,"ESS", null, 1);
SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
scores = new ArrayList<>();
scores_0 = new ArrayList<>();
Cursor cursor = sqliteDatabase.rawQuery("select * from score", new String[]{});
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
String year = cursor.getString(1);
String term = cursor.getString(2);
String id = cursor.getString(3);
String name = cursor.getString(4);
String type_1 = cursor.getString(5);
String type = cursor.getString(6);
int credit = cursor.getInt(7);
int mark = cursor.getInt(8);
float gp = cursor.getFloat(9);
String type_2 = cursor.getString(10);
cursor.moveToNext();
creditSum += credit;
_gpa += (credit * mark);
scores.add(new Score(year, term, id, name, type_1, type, credit, mark, gp, type_2));
scores_0.add(new Score(year, term, id, name, type_1, type, credit, mark, gp, type_2));
}
cursor.close();
totalCredit.setText("学分:" + String.valueOf(creditSum));
gpa.setText("成绩:" + String.valueOf(_gpa / creditSum));
scoreAdapter = new ScoreAdapter(ScoreActivity.this, R.layout.view_score, scores, false);
scoreList.setAdapter(scoreAdapter);
} catch (Exception e){
e.printStackTrace();
}
chooseTerm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
scores = new ArrayList<Score>(scores_0);
System.out.println(scores.size());
System.out.println(scoreAdapter.getCount());
showMultiAlertDialog(v);
}
});
}
public void showMultiAlertDialog(View view){
final String[] items = {"大一上学期", "大一下学期", "大二上学期", "大二下学期", "大三上学期", "大三下学期", "大四上学期", "大四下学期"};
final ArrayList<Integer> terms = new ArrayList<>();
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setTitle("选择学期");
alertBuilder.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
if (isChecked){
terms.add(i);
}else {
for(int j = 0; j < terms.size(); j++){
if(terms.get(j) == i){
terms.remove(j);
break;
}
}
}
}
});
final SharedPreferences sharedPreferences = getSharedPreferences("studentInfo", MODE_PRIVATE);
String ln = sharedPreferences.getString("stuId", "");
int userYear = Integer.parseInt(ln.substring(0, 2));
final ArrayList<String> termNum = new ArrayList<>();
for(int i = 0; i < 4; i++){
termNum.add("20" + String.valueOf(userYear + i) + "-20" + String.valueOf(userYear + 1 + i) + "1");
termNum.add("20" + String.valueOf(userYear + i) + "-20" + String.valueOf(userYear + 1 + i) + "2");
}
alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
int count = 0;
for(Score s : scores_0){
String termId = s.getYear()+s.getTerm();
boolean flag = true;
for(Integer t : terms){
if(termId.equals(termNum.get(t))){
count = count + 1;
flag = false;
}
}
if(flag){
scores.remove(count);
scoreAdapter.remove(s);
System.out.println(s.getName());
}
}
alertDialog3.dismiss();
System.out.println(scoreAdapter.getCount());
System.out.println(scores.size());
scoreAdapter.notifyDataSetChanged();
}
});
alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
alertDialog3.dismiss();
}
});
alertDialog3 = alertBuilder.create();
alertDialog3.show();
}
}
|
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import javax.swing.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Objects;
public class XLStoSAV639 {
public static void main(String[] args) throws IOException {
JFileChooser fileopen = new JFileChooser(new File("").getAbsolutePath());//в папке приложения
int choose = fileopen.showDialog(null,"Выбрать XLS файл");
if(choose == JFileChooser.APPROVE_OPTION){
File file = fileopen.getSelectedFile();
readFromExcel(file);
}
JOptionPane.showMessageDialog(null, "Работа программы завершена");
}
public static void readFromExcel(File file) throws IOException {
HSSFWorkbook myExcelBook = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = myExcelBook.getSheetAt(0);
String filePath = file.getPath();
String[] cell = new String[8];
Iterator<Row> it = sheet.iterator();
int count = 0;
//пропуск первых двух строк
it.next();
it.next();
OutputStreamWriter fileWriter = null;
try {
fileWriter = new OutputStreamWriter(new FileOutputStream("F639_razd1_"+getDayToday()+".sav"), "cp866"); //файл создаётся новый или затирается существующий
try {
//Записываем текст у файл
System.out.println("<F639_1>");
fileWriter.append("<F639_1>\n\r");//без \r даёт в клико несовпадение форматов
//проходим по всему листу
while (it.hasNext()) {
Row row = it.next();
for(int i = 0; i<8; i++){
try{
if(row.getCell(i).getCellType() == HSSFCell.CELL_TYPE_STRING){
cell[i] = row.getCell(i).getStringCellValue();
if (cell[i].contains("\"")) cell[i] = cell[i].replace("\"","~^");
}
else if(row.getCell(i).getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
cell[i] = String.valueOf(row.getCell(i).getNumericCellValue());
if (cell[i].contains(".0")) cell[i] = cell[i].replace(".0","");
if (cell[i].equals("12.1")&& count>23) cell[i] = "12.10";//отлов пропуска 12.1 вместо 12.10
}
else cell[i] = "";
}
catch (NullPointerException e){
cell[i]="";
}
System.out.print("\""+cell[i]+"\""+",");
fileWriter.append("\""+cell[i]+"\""+",");
}
if (cell[0].equals("")){
System.out.print("\"1\","+"\"0\","+"\""+count+"\"");
fileWriter.append("\"1\","+"\"0\","+"\""+count+"\"");
}
else {
count++;
System.out.print("\"1\","+"\""+count+"\""+",\"\"");
fileWriter.append("\"1\","+"\""+count+"\""+",\"\"");
}
System.out.println();
fileWriter.append("\n\r");
}
} finally {
fileWriter.flush();
fileWriter.close();
}
} catch(IOException e) {
throw new RuntimeException(e);
}
myExcelBook.close();
}
public static String getDayToday(){
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 0);
SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
return format1.format(cal.getTime());
}
}
|
package test.thread.art.four;
import test.thread.SleepUtils;
/**
* Created by maguoqiang on 16/7/6.
* 等待/通知
*/
public class WaitNotify {
private static Boolean flag=true;
private static Object lock=new Object();
public static void main(String[] args) {
Thread wait=new Thread(new Wait());
Thread notify=new Thread(new Notify());
wait.start();
notify.start();
}
static class Wait implements Runnable{
public void run() {
synchronized (lock){
while (flag){
try {
System.out.println("lock is true");
lock.wait();
System.out.println("wait is over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("lock is false");
}
}
}
static class Notify implements Runnable{
public void run() {
synchronized (lock){
System.out.println("hold lock notify");
flag=false;
lock.notifyAll();
SleepUtils.second(5);
}
synchronized (lock){
System.out.println("hold lock again");
SleepUtils.second(5);
}
}
}
}
|
package com.xhpower.qianmeng.service.impl;
import com.xhpower.qianmeng.entity.Case;
import com.xhpower.qianmeng.dao.CaseMapper;
import com.xhpower.qianmeng.service.CaseService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author xc
* @since 2018-07-27
*/
@Service
public class CaseServiceImpl extends ServiceImpl<CaseMapper, Case> implements CaseService {
}
|
package de.jmda.gen.java.impl;
import java.util.ArrayList;
import java.util.List;
import de.jmda.gen.Generator;
import de.jmda.gen.impl.AbstractCompoundGenerator;
import de.jmda.gen.java.InstanceFieldGenerator;
import de.jmda.gen.java.InstanceFieldDeclarationsGenerator;
/**
* Maintains a list of {@link InstanceFieldGenerator}s in {@link
* #generators}.
*
* @author rwegner
*/
public class DefaultInstanceFieldDeclarationsGenerator
extends AbstractCompoundGenerator
implements InstanceFieldDeclarationsGenerator
{
private List<InstanceFieldGenerator> generators;
public DefaultInstanceFieldDeclarationsGenerator()
{
super();
setComponentSeparator(DOUBLE_LINE_SEPARATOR);
}
/**
* @return list of <code>Generator</code>s with the return values of the
* following methods in the following order:
* <ul>
* <li>{@link #getGenerators()}</li>
* </ul>
*
* @see de.jmda.gen.CompoundGenerator#getGeneratorComponents()
*/
@Override
public List<Generator> getGeneratorComponents()
{
// copy specific generators to non-specific generators and make Java happy
List<Generator> result = new ArrayList<Generator>();
result.addAll(getGenerators());
return result;
}
/**
* @see de.jmda.gen.java.InstanceFieldDeclarationsGenerator#getGenerators()
*/
@Override
public List<InstanceFieldGenerator> getGenerators()
{
if (generators == null)
{
generators = new ArrayList<InstanceFieldGenerator>();
}
return generators;
}
@Override
public boolean add(InstanceFieldGenerator generator)
{
return getGenerators().add(generator);
}
}
|
package com.example.chargethedebt;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.example.chargethedebt.Model.debtor;
public class AddNewDebtorActivity extends AppCompatActivity {
EditText edtName, edtPhoneNumber, edtPurpose, edtAmount, edtAddress, edtInterestRate;
Button btnAddNew;
DebtorAdapter debtorAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_debtor);
edtName = findViewById(R.id.edtName);
edtPhoneNumber = findViewById(R.id.edtPhone);
edtPurpose = findViewById(R.id.purpose);
edtAddress = findViewById(R.id.edtAddress);
edtAmount = findViewById(R.id.edtAmount);
edtInterestRate = findViewById(R.id.edtInterestRate);
btnAddNew = findViewById(R.id.btnAddNew);
btnAddNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String dtName, dtPhone, dtPurpose, dtAddress;
Double dtAmount, dtInterestRate;
// Lấy giá trị bên EditText làm thông tin truyền vào deb1
dtName = edtName.getText().toString();
dtPhone = edtPhoneNumber.getText().toString();
dtPurpose = edtPurpose.getText().toString();
dtAddress = edtAddress.getText().toString();
dtAmount = Double.parseDouble(edtAmount.getText().toString());
dtInterestRate = Double.parseDouble(edtInterestRate.getText().toString());
debtor deb1 = new debtor(dtName, dtPhone, dtAddress, dtPurpose, dtAmount, dtInterestRate);
debtorAdapter.data.add(deb1);
// chuyển về lại màn hình chính
finish();
}
});
}
}
|
package mc.alk.arena.events.players;
import mc.alk.arena.objects.ArenaLocation;
import mc.alk.arena.objects.ArenaPlayer;
import mc.alk.arena.objects.LocationType;
import mc.alk.arena.objects.TeleportDirection;
import mc.alk.arena.objects.arenas.ArenaType;
import mc.alk.arena.objects.teams.ArenaTeam;
public class ArenaPlayerTeleportEvent extends ArenaPlayerEvent{
final ArenaTeam team;
final ArenaLocation src;
final ArenaLocation dest;
final TeleportDirection direction;
final ArenaType arenaType;
public ArenaPlayerTeleportEvent(ArenaType at, ArenaPlayer arenaPlayer, ArenaTeam team,
ArenaLocation src, ArenaLocation dest, TeleportDirection direction) {
super(arenaPlayer);
this.arenaType = at;
this.team = team;
this.src = src;
this.dest = dest;
this.direction = direction;
}
public ArenaType getArenaType(){
return arenaType;
}
public ArenaTeam getTeam() {
return team;
}
public TeleportDirection getDirection(){
return direction;
}
public LocationType getSrcType(){
return src.getType();
}
public LocationType getDestType(){
return dest.getType();
}
public ArenaLocation getSrcLocation() {
return src;
}
public ArenaLocation getDestLocation() {
return dest;
}
}
|
package com.aummn.suburb.resource;
import com.aummn.suburb.SuburbApplication;
import com.aummn.suburb.exception.SuburbExistsException;
import com.aummn.suburb.exception.SuburbNotFoundException;
import com.aummn.suburb.resource.dto.request.SuburbWebRequest;
import com.aummn.suburb.service.SuburbService;
import com.aummn.suburb.service.dto.response.SuburbServiceResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.reactivex.Completable;
import io.reactivex.Single;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SuburbApplication.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SuburbResourceTest {
@Autowired
private ObjectMapper objectMapper;
@MockBean
private SuburbService suburbService;
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(context).dispatchOptions(true).build();
}
@Test
@WithMockUser(roles = "ADMIN")
public void givenASuburbRequest_whenAddSuburb_Success_thenReturn201() throws Exception {
when(suburbService.addSuburb(any()))
.thenReturn(Single.just(1L));
MvcResult mvcResult = mockMvc.perform(post("/api/suburb/add")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(new SuburbWebRequest("Carlton", "3003"))))
.andExpect(status().isOk())
.andReturn();
verify(suburbService, times(1)).addSuburb(any());
}
@WithMockUser(roles = "NOTADMIN")
public void givenASuburbRequest_whenAddSuburb_NotAdminRole_thenReturn403() throws Exception {
when(suburbService.addSuburb(any()))
.thenReturn(Single.just(1L));
MvcResult mvcResult = mockMvc.perform(post("/api/suburb/add")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(new SuburbWebRequest("Southbank", "3006"))))
.andExpect(status().isForbidden())
.andReturn();
}
@Test
@WithMockUser(roles = "ADMIN")
public void givenASuburbRequest_whenAddSuburb_SuburbExist_thenReturn409SuburbConflicts() throws Exception {
when(suburbService.addSuburb(any()))
.thenReturn(Single.error(new SuburbExistsException()));
MvcResult mvcResult = mockMvc.perform(post("/api/suburb/add")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(objectMapper.writeValueAsString(new SuburbWebRequest("Clayton", "3068"))))
.andExpect(status().isOk())
.andReturn();
verify(suburbService, times(1)).addSuburb(any());
}
@Test
public void givenAPostcode_whenGetSuburbDetailByPostcode_andGetAListOfSuburbDTO_thenReturn200WithSuburbWebResponses() throws Exception {
SuburbServiceResponse s1dto = new SuburbServiceResponse(1L, "Southbank", "3006");
SuburbServiceResponse s2dto = new SuburbServiceResponse(2L, "Melbourne", "3000");
SuburbServiceResponse s3dto = new SuburbServiceResponse(3L, "Carlton", "3001");
List<SuburbServiceResponse> dtos = Arrays.asList(s1dto, s2dto, s3dto);
when(suburbService.getSuburbDetailByPostcode(anyString()))
.thenReturn(Single.just(dtos));
MvcResult mvcResult = mockMvc.perform(get("/api/suburb/postcode/1234")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(jsonPath("$.error", nullValue()))
.andExpect(jsonPath("$.data.length()", equalTo(3)));
verify(suburbService, times(1)).getSuburbDetailByPostcode(anyString());
}
@Test
public void givenAPostcode_whenGetSuburbDetailByPostcode_andPostcodeNotFound_thenReturn404SuburbNotFound() throws Exception {
when(suburbService.getSuburbDetailByPostcode(anyString()))
.thenReturn(Single.error(new SuburbNotFoundException("suburb with postcode [1234] not found")));
MvcResult mvcResult = mockMvc.perform(get("/api/suburb/postcode/1234")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.status", equalTo(404)))
.andExpect(jsonPath("$.message", equalTo("suburb with postcode [1234] not found")));
verify(suburbService, times(1)).getSuburbDetailByPostcode(anyString());
}
@Test
public void givenASuburbName_whengetGuburbDetailByName_andGetAListOfSuburbDTO_thenReturn200WithSuburbWebResponses() throws Exception {
SuburbServiceResponse s1dto = new SuburbServiceResponse(1L, "Southbank", "3006");
SuburbServiceResponse s2dto = new SuburbServiceResponse(2L, "Melbourne", "3000");
SuburbServiceResponse s3dto = new SuburbServiceResponse(3L, "Carlton", "3001");
List<SuburbServiceResponse> dtos = Arrays.asList(s1dto, s2dto, s3dto);
when(suburbService.getSuburbDetailByName(anyString()))
.thenReturn(Single.just(dtos));
MvcResult mvcResult = mockMvc.perform(get("/api/suburb/name/Southbank")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(jsonPath("$.error", nullValue()))
.andExpect(jsonPath("$.data.length()", equalTo(3)));
verify(suburbService, times(1)).getSuburbDetailByName(anyString());
}
@Test
public void givenASuburbName_whenGetSuburbDetailByName_andNameNotFound_thenReturn404SuburbNotFound() throws Exception {
when(suburbService.getSuburbDetailByName(anyString()))
.thenReturn(Single.error(new SuburbNotFoundException("suburb with name [Carlton] not found")));
MvcResult mvcResult = mockMvc.perform(get("/api/suburb/name/Carlton")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.status", equalTo(404)))
.andExpect(jsonPath("$.message", equalTo("suburb with name [Carlton] not found")));
verify(suburbService, times(1)).getSuburbDetailByName(anyString());
}
@Test
public void givenASuburbId_whenGetSuburbDetailById_andGetSuburb_thenReturn200WithSuburbWebResponses() throws Exception {
SuburbServiceResponse s1dto = new SuburbServiceResponse(123456L, "Southbank", "3006");
when(suburbService.getSuburbById(anyLong()))
.thenReturn(Single.just(s1dto));
MvcResult mvcResult = mockMvc.perform(get("/api/suburb/id/123456")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isOk())
.andExpect(jsonPath("$.error", nullValue()))
.andExpect(jsonPath("$.data.id", equalTo(123456)));
verify(suburbService, times(1)).getSuburbById(anyLong());
}
@Test
public void givenASuburbId_whenGetSuburbDetailById_andSuburbNotFound_thenReturn404SuburbNotFound() throws Exception {
when(suburbService.getSuburbById(anyLong()))
.thenReturn(Single.error(new SuburbNotFoundException("suburb with id [123456] not found")));
MvcResult mvcResult = mockMvc.perform(get("/api/suburb/id/123456")
.contentType(MediaType.APPLICATION_JSON_VALUE))
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.status", equalTo(404)))
.andExpect(jsonPath("$.message", equalTo("suburb with id [123456] not found")));
verify(suburbService, times(1)).getSuburbById(anyLong());
}
}
|
package com.tencent.mm.plugin.record.ui;
import android.content.Intent;
import android.view.MenuItem;
import com.tencent.mm.R;
import com.tencent.mm.bg.d;
import com.tencent.mm.plugin.fav.a.b;
import com.tencent.mm.plugin.fav.a.h;
import com.tencent.mm.plugin.record.ui.FavRecordDetailUI.2;
import com.tencent.mm.ui.base.n$d;
class FavRecordDetailUI$2$2 implements n$d {
final /* synthetic */ 2 msI;
FavRecordDetailUI$2$2(2 2) {
this.msI = 2;
}
public final void onMMMenuItemSelected(MenuItem menuItem, int i) {
Intent intent;
switch (menuItem.getItemId()) {
case 0:
intent = new Intent();
intent.putExtra("Select_Conv_Type", 3);
intent.putExtra("scene_from", 1);
intent.putExtra("mutil_select_is_ret", true);
intent.putExtra("select_fav_local_id", FavRecordDetailUI.b(this.msI.msF).field_localId);
d.b(this.msI.msF, ".ui.transmit.SelectConversationUI", intent, 4097);
h.f(FavRecordDetailUI.b(this.msI.msF).field_localId, 1, 0);
return;
case 2:
com.tencent.mm.ui.base.h.a(this.msI.msF.mController.tml, this.msI.msF.getString(R.l.app_delete_tips), "", new 1(this), null);
return;
case 3:
intent = new Intent();
intent.putExtra("key_fav_scene", 2);
intent.putExtra("key_fav_item_id", FavRecordDetailUI.a(this.msI.msF));
b.a(this.msI.msF.mController.tml, ".ui.FavTagEditUI", intent);
return;
case 4:
intent = new Intent();
intent.putExtra("key_fav_scene", 1);
intent.putExtra("key_fav_item_id", FavRecordDetailUI.b(this.msI.msF).field_localId);
b.a(this.msI.msF.mController.tml, ".ui.FavTagEditUI", intent);
return;
default:
return;
}
}
}
|
package lk.cmb.ucsc.drivingschool.repo;
import lk.cmb.ucsc.drivingschool.model.Teacher;
import org.springframework.data.repository.CrudRepository;
public interface TeacherRepository extends CrudRepository<Teacher, String> {
}
|
package site.com.google.anywaywrite.component.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LinearGradientPaint;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.Map.Entry;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.MatteBorder;
import site.com.google.anywaywrite.component.BgCardPointChangedHook;
import site.com.google.anywaywrite.component.BgCardSelectionChangedHook;
import site.com.google.anywaywrite.component.layout.BgAreaLayout;
import site.com.google.anywaywrite.component.layout.BgSingleSimpleLayout;
import site.com.google.anywaywrite.component.menu.BgCreateActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateAllDirectionActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateAllMoveActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateAllSideActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateAreaDetailActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateCardDetailActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateCardDirectionActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateCardMoveActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateCardSideActionMenu;
import site.com.google.anywaywrite.component.menu.BgCreateShuffleActionMenu;
import site.com.google.anywaywrite.component.menu.BgMenuItem;
import site.com.google.anywaywrite.item.card.BgCardItem;
/**
* ボードゲームにおいてコンポーネントを置いたりする場所の基準となる 【エリア】を描画するクラスです。 現在は、カードが置かれることのみを想定しています。
*
* @author y-kitajima
*
*/
public class BgAreaLabel extends JLabel implements BgCardArea {
private static final long serialVersionUID = 1L;
/** ���̉�ʂ� */
private final List<BgCardItem> cards;
private BgAreaLayout areaLayout;
private String areaName;
private Set<Integer> selectedIndexes;
private int pointedCardIndex;
private boolean displayAreaName;
private Color borderColor;
private Color selectionCardBorderColor;
private static final String AREA_NAME_SUFFIX = " ▼ ";
private BgAreaNamePosition areaNamePosition;
private boolean inAreaName;
private float[] areaNameFractions;
private Color[] areaNameGradientColors;
private Font areaNameFont;
private Color areaNameFontColor;
private Color areaNameSelectionFontColor;
private JPopupMenu areaActionMenu;
private JPopupMenu cardActionMenu;
private Map<String, BgCreateActionMenu> areaActionMenuMap;
private Map<String, BgCreateActionMenu> selectedCardActionMenuMap;
private Map<String, BgCreateActionMenu> pointedCardActionMenuMap;
private BgAreaLabelPane playBoard;
private BgTempAreaInternalFrame playFrame;
public enum BgAreaNamePosition {
LEFT_TOP, LEFT_BOTTOM, RIGHT_BOTTOM, RIGHT_TOP;
}
public enum BgDefaultAreaActionMenuMame {
allMove, allDirection, allSide, shuffle, detail, ;
public String getActionName() {
return this.name();
}
}
public enum BgDefaultCardActionMenuMame {
move, direction, side, detail, ;
public String getActionName() {
return this.name();
}
}
private BgAreaLabel(List<BgCardItem> cards, BgAreaLayout layout,
boolean displayAreaName) {
super();
setOpaque(false);
this.cards = new ArrayList<BgCardItem>();
addAllCards(cards);
if (layout == null) {
setAreaLayout(createDefaultAreaLayout());
} else {
setAreaLayout(layout);
}
verifyCards();
setPointedCardIndex(-1);
setInAreaName(false);
setDisplayAreaName(displayAreaName);
setBorderColor(Color.BLUE);
setSelectionCardBorderColor(Color.YELLOW);
setAreaNamePosition(BgAreaNamePosition.LEFT_TOP);
setAreaNameFractions(new float[] { 0.0f, 0.249f, 0.25f, 1.0f });
setAreaNameGradientColors(new Color[] { new Color(0x63a5f7),
new Color(0x3799f4), new Color(0x2d7eeb), new Color(0x30a5f9) });
setAreaNameFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 12));
setAreaNameFontColor(Color.WHITE);
setAreaNameSelectionFontColor(Color.ORANGE);
addMouseMotionListener();
installAreaActionMenuItem(BgDefaultAreaActionMenuMame.allMove
.getActionName(), BgCreateAllMoveActionMenu.newInstance());
installAreaActionMenuItem(BgDefaultAreaActionMenuMame.allDirection
.getActionName(), BgCreateAllDirectionActionMenu.newInstance());
installAreaActionMenuItem(BgDefaultAreaActionMenuMame.allSide
.getActionName(), BgCreateAllSideActionMenu.newInstance());
installAreaActionMenuItem(BgDefaultAreaActionMenuMame.shuffle
.getActionName(), BgCreateShuffleActionMenu.newInstance());
installAreaActionMenuItem(BgDefaultAreaActionMenuMame.detail
.getActionName(), BgCreateAreaDetailActionMenu.newInstance());
installSelectedCardActionMenuItem(BgDefaultCardActionMenuMame.move
.getActionName(), BgCreateCardMoveActionMenu.newInstance());
installSelectedCardActionMenuItem(BgDefaultCardActionMenuMame.direction
.getActionName(), BgCreateCardDirectionActionMenu.newInstance());
installSelectedCardActionMenuItem(BgDefaultCardActionMenuMame.side
.getActionName(), BgCreateCardSideActionMenu.newInstance());
installSelectedCardActionMenuItem(BgDefaultCardActionMenuMame.detail
.getActionName(), BgCreateCardDetailActionMenu.newInstance());
installPointedCardActionMenuItem(BgDefaultCardActionMenuMame.detail
.getActionName(), BgCreateCardDetailActionMenu.newInstance());
}
public static BgAreaLabel newInstance(List<BgCardItem> cards,
BgAreaLayout layout) {
return new BgAreaLabel(cards, layout, true);
}
public static BgAreaLabel newDefaultLayoutInstance(List<BgCardItem> cards) {
return new BgAreaLabel(cards, null, true);
}
@Override
public Component getComponent() {
return this;
}
@Override
public List<BgCardItem> getCards() {
return cards;
// return Collections.unmodifiableList(cards);
}
public void setAreaName(String name) {
this.areaName = name;
}
@Override
public String getAreaName() {
return this.areaName;
}
// TODO 外部に公開する場合、Unmodifiableにするべき。どう実装するか考えること
@Override
public Set<Integer> getSelectedIndexes() {
if (selectedIndexes == null) {
selectedIndexes = new TreeSet<Integer>();
}
return selectedIndexes;
}
private void setPointedCardIndex(int val) {
this.pointedCardIndex = val;
}
public final int getPointedCardIndex() {
return pointedCardIndex;
}
public void setDisplayAreaName(boolean val) {
this.displayAreaName = val;
}
@Override
public boolean isDisplayAreaName() {
return this.displayAreaName;
}
public void setBorderColor(Color val) {
this.borderColor = val;
}
public Color getBorderColor() {
return this.borderColor;
}
public void setSelectionCardBorderColor(Color val) {
this.selectionCardBorderColor = val;
}
@Override
public Color getSelectionCardBorderColor() {
return this.selectionCardBorderColor;
}
private boolean isInAreaName() {
return this.inAreaName;
}
private void setInAreaName(boolean val) {
if (val != this.inAreaName) {
this.inAreaName = val;
paintImmediately(getAreaNameRectangle());
}
}
public void setAreaNamePosition(BgAreaNamePosition val) {
this.areaNamePosition = val;
}
public BgAreaNamePosition getAreaNamePosition() {
return this.areaNamePosition;
}
public void setAreaNameFractions(float[] fractions) {
this.areaNameFractions = fractions;
}
private float[] getAreaNameFractions() {
return this.areaNameFractions;
}
private Color[] getAreaNameGradientColors() {
return this.areaNameGradientColors;
}
public void setAreaNameGradientColors(Color[] colors) {
this.areaNameGradientColors = colors;
}
private Font getAreaNameFont() {
return this.areaNameFont;
}
public void setAreaNameFont(Font f) {
this.areaNameFont = f;
}
private Color getAreaNameFontColor() {
return this.areaNameFontColor;
}
public void setAreaNameFontColor(Color c) {
this.areaNameFontColor = c;
}
private Color getAreaNameSelectionFontColor() {
return areaNameSelectionFontColor;
}
public void setAreaNameSelectionFontColor(Color c) {
this.areaNameSelectionFontColor = c;
}
private JPopupMenu getAreaActionMenu() {
if (this.areaActionMenu == null) {
this.areaActionMenu = new JPopupMenu();
}
return this.areaActionMenu;
}
public Map<String, BgCreateActionMenu> getAreaActionMenuMap() {
if (this.areaActionMenuMap == null) {
this.areaActionMenuMap = new LinkedHashMap<String, BgCreateActionMenu>();
}
return this.areaActionMenuMap;
}
public void installAreaActionMenuItem(String actionName,
BgCreateActionMenu menuItem) {
getAreaActionMenuMap().put(actionName, menuItem);
}
public BgCreateActionMenu uninstallAreaActionMenu(String actionName) {
return getAreaActionMenuMap().remove(actionName);
}
public List<BgCreateActionMenu> uninstallAllAreaActionMenu() {
List<BgCreateActionMenu> ret = new ArrayList<BgCreateActionMenu>();
for (Iterator<Entry<String, BgCreateActionMenu>> it = getAreaActionMenuMap()
.entrySet().iterator(); it.hasNext();) {
ret.add(it.next().getValue());
it.remove();
}
return ret;
}
private JPopupMenu getCardActionMenu() {
if (this.cardActionMenu == null) {
this.cardActionMenu = new JPopupMenu();
}
return this.cardActionMenu;
}
public Map<String, BgCreateActionMenu> getSelectedCardActionMenuMap() {
if (this.selectedCardActionMenuMap == null) {
this.selectedCardActionMenuMap = new LinkedHashMap<String, BgCreateActionMenu>();
}
return this.selectedCardActionMenuMap;
}
public void installSelectedCardActionMenuItem(String actionName,
BgCreateActionMenu menuItem) {
getSelectedCardActionMenuMap().put(actionName, menuItem);
}
public BgCreateActionMenu uninstallSelectedCardActionMenu(String actionName) {
return getSelectedCardActionMenuMap().remove(actionName);
}
public List<BgCreateActionMenu> uninstallAllSelectedCardActionMenu() {
List<BgCreateActionMenu> ret = new ArrayList<BgCreateActionMenu>();
for (Iterator<Entry<String, BgCreateActionMenu>> it = getSelectedCardActionMenuMap()
.entrySet().iterator(); it.hasNext();) {
ret.add(it.next().getValue());
it.remove();
}
return ret;
}
public Map<String, BgCreateActionMenu> getPointedCardActionMenuMap() {
if (this.pointedCardActionMenuMap == null) {
this.pointedCardActionMenuMap = new LinkedHashMap<String, BgCreateActionMenu>();
}
return this.pointedCardActionMenuMap;
}
public void installPointedCardActionMenuItem(String actionName,
BgCreateActionMenu menuItem) {
getPointedCardActionMenuMap().put(actionName, menuItem);
}
public BgCreateActionMenu uninstallPointedCardActionMenu(String actionName) {
return getPointedCardActionMenuMap().remove(actionName);
}
public List<BgCreateActionMenu> uninstallAllPointedCardActionMenu() {
List<BgCreateActionMenu> ret = new ArrayList<BgCreateActionMenu>();
for (Iterator<Entry<String, BgCreateActionMenu>> it = getPointedCardActionMenuMap()
.entrySet().iterator(); it.hasNext();) {
ret.add(it.next().getValue());
it.remove();
}
return ret;
}
public void setPlayBoard(BgAreaLabelPane val) {
this.playBoard = val;
}
public BgAreaLabelPane getPlayBoard() {
return this.playBoard;
}
public void setPlayFrame(BgTempAreaInternalFrame val) {
this.playFrame = val;
}
public BgTempAreaInternalFrame getPlayFrame() {
return this.playFrame;
}
public void addCard(BgCardItem card) {
clearCardsSelection();
if (getAreaLayout() != null && card != null) {
card.setDirection(getAreaLayout().getInitialDirection());
card.setSide(getAreaLayout().getInitialSide());
}
this.cards.add(card);
verifyCards();
}
public void addCard(int idx, BgCardItem card) {
clearCardsSelection();
if (getAreaLayout() != null && card != null) {
card.setDirection(getAreaLayout().getInitialDirection());
card.setSide(getAreaLayout().getInitialSide());
}
this.cards.add(idx, card);
verifyCards();
}
public void addAllCards(List<BgCardItem> cards) {
clearCardsSelection();
if (getAreaLayout() != null && cards != null) {
for (BgCardItem card : cards) {
card.setDirection(getAreaLayout().getInitialDirection());
card.setSide(getAreaLayout().getInitialSide());
}
}
this.cards.addAll(cards);
verifyCards();
}
public void addAllCards(int idx, List<BgCardItem> cards) {
clearCardsSelection();
if (getAreaLayout() != null && cards != null) {
for (BgCardItem card : cards) {
card.setDirection(getAreaLayout().getInitialDirection());
card.setSide(getAreaLayout().getInitialSide());
}
}
this.cards.addAll(idx, cards);
verifyCards();
}
public List<BgCardItem> removeAllCards() {
clearCardsSelection();
List<BgCardItem> ret = new ArrayList<BgCardItem>();
ret.addAll(cards);
this.cards.clear();
verifyCards();
return ret;
}
public BgCardItem removeCardFromTop() {
clearCardsSelection();
if (this.cards.size() == 0) {
throw new IllegalStateException(
"the cards no is zero, so colud not remove top site.com.google.anywaywrite.card.");
}
BgCardItem remove = this.cards.remove(this.cards.size() - 1);
verifyCards();
return remove;
}
public List<BgCardItem> removeCardsFromTop(int no) {
clearCardsSelection();
if (this.cards.size() < no) {
throw new IllegalStateException("the rest cards no is "
+ this.cards.size() + ", so colud not remove top " + no
+ " site.com.google.anywaywrite.card.");
}
List<BgCardItem> ret = new ArrayList<BgCardItem>();
for (int idx = 0; idx < no; idx++) {
ret.add(this.cards.remove(this.cards.size() - 1));
}
verifyCards();
return ret;
}
/**
* 下から指定された枚数目のカードを取り除きます。<br />
* 一番下を取り除く時は、0を指定します。
*
* @param no
* @return
*/
public BgCardItem removeCardFromBottom(int no) {
if (no < 0) {
throw new IllegalArgumentException(
"the no should be more than or equal ZERO, but was " + no);
}
if (this.cards.size() <= no) {
throw new IllegalStateException("the rest cards no is "
+ this.cards.size() + ", so colud not remove top " + no
+ " site.com.google.anywaywrite.card.");
}
clearCardsSelection();
BgCardItem remove = this.cards.remove(no);
verifyCards();
return remove;
}
/**
* 一番上から数えて指定枚数目のカードを取り除きます。<br />
* 一番上を取り除くときは、1を指定します。(0ではありません)
*/
public BgCardItem removeCardFromTop(int no) {
if (no <= 0) {
throw new IllegalArgumentException(
"the no should be more than ZERO, but was " + no);
}
if (this.cards.size() < no) {
throw new IllegalStateException("the rest cards no is "
+ this.cards.size() + ", so colud not remove top " + no
+ " site.com.google.anywaywrite.card.");
}
clearCardsSelection();
BgCardItem remove = this.cards.remove(this.cards.size() - no);
verifyCards();
return remove;
}
public void clearCardsSelection() {
Set<Integer> selIdxes = getSelectedIndexes();
getSelectedIndexes().clear();
for (int selIdx : selIdxes) {
paintRectangleImmediately(selIdx);
if (getSelectionChangedHook() != null) {
getSelectionChangedHook().selectionChanged(BgAreaLabel.this,
selIdx);
}
}
}
private void verifyCards() {
if (getAreaLayout() != null) {
String errMsg = getAreaLayout().verify(this.cards);
if (errMsg != null) {
throw new RuntimeException(errMsg);
}
}
}
public void setAreaLayout(BgAreaLayout layout) {
this.areaLayout = layout;
this.areaLayout.setArea(this);
}
public BgAreaLayout getAreaLayout() {
return this.areaLayout;
}
protected BgAreaLayout createDefaultAreaLayout() {
return BgSingleSimpleLayout.newDefaultInstance();
}
private void addMouseMotionListener() {
this.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
setInAreaName(e);
List<Rectangle> recs = BgAreaLabel.this.getAreaLayout()
.getCardRectangles();
int index = -1;
for (int idx = 0, size = recs.size(); idx < size; idx++) {
if (recs.get(idx).contains(e.getPoint())) {
index = idx;
}
}
if (index == getPointedCardIndex()) {
return;
}
setPointedCardIndex(index);
if (getPointChangedHook() != null) {
getPointChangedHook().pointChanged(BgAreaLabel.this, index);
}
}
private void setInAreaName(MouseEvent e) {
if (isDisplayAreaName()) {
if (getAreaNameRectangle().contains(e.getPoint())) {
BgAreaLabel.this.setInAreaName(true);
} else {
BgAreaLabel.this.setInAreaName(false);
}
} else {
BgAreaLabel.this.setInAreaName(false);
}
}
});
this.addMouseListener(new MouseAdapter() {
// JPopupMenu menu = new JPopupMenu();
@Override
public void mouseEntered(MouseEvent mouseevent) {
setBorder(new MatteBorder(2, 2, 2, 2, getBorderColor()));
}
@Override
public void mouseExited(MouseEvent mouseevent) {
setBorder(new EmptyBorder(2, 2, 2, 2));
setInAreaName(false);
setPointedCardIndex(-1);
}
@Override
public void mouseClicked(MouseEvent me) {
if (SwingUtilities.isLeftMouseButton(me)) {
if (BgAreaLabel.this.getCards() == null
|| BgAreaLabel.this.getCards().size() == 0) {
return;
}
if (isDisplayAreaName()
&& getAreaNameRectangle().contains(me.getPoint())) {
getAreaActionMenu().removeAll();
for (Iterator<Entry<String, BgCreateActionMenu>> it = getAreaActionMenuMap()
.entrySet().iterator(); it.hasNext();) {
BgCreateActionMenu createMenu = it.next()
.getValue();
BgMenuItem item = createMenu
.createActionMenu(BgAreaLabel.this);
if (item.isHasSeparator()
&& getAreaActionMenu().getComponentCount() > 0) {
getAreaActionMenu().addSeparator();
}
getAreaActionMenu().add(item.getMenuItem());
}
getAreaActionMenu().show(BgAreaLabel.this,
(int) getAreaNameRectangle().getX(),
(int) getAreaNameRectangle().getHeight());
return;
}
if (getPointedCardIndex() == -1) {
return;
}
if (getSelectedIndexes().contains(getPointedCardIndex())) {
getSelectedIndexes().remove(getPointedCardIndex());
} else {
getSelectedIndexes().add(getPointedCardIndex());
}
// Rectangle rec = getAreaLayout().getCardRectangles().get(
// getPointedCardIndex());
// BgAreaLabel.this.paintImmediately(rec.x - 3, rec.y - 3,
// rec.width + 6, rec.height + 6);
paintRectangleImmediately(getPointedCardIndex());
if (isDisplayAreaName()) {
BgAreaLabel.this
.paintImmediately(getAreaNameRectangle());
}
if (getSelectionChangedHook() != null) {
getSelectionChangedHook().selectionChanged(
BgAreaLabel.this, getPointedCardIndex());
}
} else if (SwingUtilities.isRightMouseButton(me)) {
if (getCards() == null || getCards().size() == 0) {
return;
}
getCardActionMenu().removeAll();
if (isInSelectedCards()) {
for (Iterator<Entry<String, BgCreateActionMenu>> it = getSelectedCardActionMenuMap()
.entrySet().iterator(); it.hasNext();) {
BgCreateActionMenu createMenu = it.next()
.getValue();
BgMenuItem item = createMenu
.createActionMenu(BgAreaLabel.this);
if (item.isHasSeparator()
&& getCardActionMenu().getComponentCount() > 0) {
getCardActionMenu().addSeparator();
}
getCardActionMenu().add(item.getMenuItem());
}
// menu.add(createMoveMenu(area, me));
// // menu.add(createAllMoveMenu(area));// →BgAreaLabel
// // menu.addSeparator();
//
// menu.add(createCardsDirectionMenu(area, me));
// // menu.add(createAreaDirectionMenu(area));//
// // →BgAreaLabel
// menu.add(createCardsSideMenu(area, me));
// // menu.add(createAreaSideMenu(area));// →BgAreaLabel
//
// // menu.addSeparator();
// // menu.add(new JMenuItem(new
// // BgAreaShuffleAction(area)));//
// // →BgAreaLabel
// menu.addSeparator();
} else {
if (getPointedCardIndex() != -1) {
for (Iterator<Entry<String, BgCreateActionMenu>> it = getPointedCardActionMenuMap()
.entrySet().iterator(); it.hasNext();) {
BgCreateActionMenu createMenu = it.next()
.getValue();
BgMenuItem item = createMenu
.createActionMenu(BgAreaLabel.this);
if (item.isHasSeparator()
&& getCardActionMenu()
.getComponentCount() > 0) {
getCardActionMenu().addSeparator();
}
getCardActionMenu().add(item.getMenuItem());
}
}
}
// menu.add(createAreaDetailMenu(area));// →BgAreaLabel
// menu.add(createCardDetailMenu(BgAreaLabel.this, me));
getCardActionMenu().show(BgAreaLabel.this, me.getX(),
me.getY());
}
}
private boolean isInSelectedCards() {
return getSelectedIndexes().contains(getPointedCardIndex());
}
});
}
private BgCardPointChangedHook pointChangedHook;
/** カードの指し示す場所が変更された直後に行いたい処理を記述します */
public final void setPointChangedHook(BgCardPointChangedHook hook) {
pointChangedHook = hook;
}
public final BgCardPointChangedHook getPointChangedHook() {
return this.pointChangedHook;
}
public BgCardSelectionChangedHook selectionChangedHook;
/** カードの選択状態が変更された直後に行いたい処理を記述します */
public final void setSelectionChangedHook(BgCardSelectionChangedHook hook) {
selectionChangedHook = hook;
}
public final BgCardSelectionChangedHook getSelectionChangedHook() {
return this.selectionChangedHook;
}
@Override
public void paintComponent(Graphics g) {
// System.out.println("BgAreaLabel#getSelectedIndexes()#size() == "
// + getSelectedIndexes().size());
if (isInAreaName() || getAreaActionMenu().isVisible()) {
getAreaLayout().paintComponent(g);
if (isDisplayAreaName()) {
paintAreaName(g);
}
// RadialGradientPaint rgp = new RadialGradientPaint(
// new Point2D.Double(getAreaNameRectangle().width / 2.0,
// // getAreaNameRectangle().height * 1.5),
// getAreaNameRectangle().height * 1.0),
// getAreaNameRectangle().width / 2.3f, new Point2D.Double(
// getAreaNameRectangle().width / 2.0,
// // getAreaNameRectangle().height * 1.75 + 6),
// getAreaNameRectangle().height * 1.25), new float[] {
// 0.0f, 0.8f }, new Color[] {
// new Color(64, 142, 203, 255),
// new Color(64, 142, 203, 0) },
// RadialGradientPaint.CycleMethod.NO_CYCLE,
// RadialGradientPaint.ColorSpaceType.SRGB, AffineTransform
// .getScaleInstance(1.0, 0.5));
// Graphics2D g2d = (Graphics2D) g.create();
// g2d.setPaint(rgp);
// g2d.fillOval(0, 0, getAreaNameRectangle().width,
// getAreaNameRectangle().height);
// g2d.dispose();
} else {
if (getSelectedIndexes().size() > 0) {
if (isDisplayAreaName()) {
paintAreaName(g);
}
getAreaLayout().paintComponent(g);
} else {
getAreaLayout().paintComponent(g);
if (isDisplayAreaName()) {
paintAreaName(g);
}
}
}
}
private void paintRectangleImmediately(int idx) {
if (idx < 0) {
throw new IllegalArgumentException(
"idx should not be less than ZERO, but was.");
}
Rectangle rec = getAreaLayout().getCardRectangles().get(idx);
BgAreaLabel.this.paintImmediately(rec.x - 3, rec.y - 3, rec.width + 6,
rec.height + 6);
}
public void addSelection(int idx) {
if (idx < 0) {
throw new IllegalArgumentException(
"idx should not be less than ZERO, but was.");
}
if (getSelectedIndexes().contains(idx)) {
return;
}
getSelectedIndexes().add(idx);
paintRectangleImmediately(idx);
if (getSelectionChangedHook() != null) {
getSelectionChangedHook().selectionChanged(BgAreaLabel.this, idx);
}
}
public void removeSelection(int idx) {
if (idx < 0) {
throw new IllegalArgumentException(
"idx should not be less than ZERO, but was.");
}
if (!getSelectedIndexes().contains(idx)) {
return;
}
getSelectedIndexes().remove(idx);
paintRectangleImmediately(idx);
if (getSelectionChangedHook() != null) {
getSelectionChangedHook().selectionChanged(BgAreaLabel.this, idx);
}
}
@Override
public void paintAreaName(Graphics g) {
drawGradient(g);
drawAreaName(g);
}
public String getAreaDisplayName() {
return getAreaName() + AREA_NAME_SUFFIX;
}
private void drawAreaName(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setFont(getAreaNameFont());
if (isInAreaName() || getAreaActionMenu().isVisible()) {
g2d.setColor(getAreaNameSelectionFontColor());
} else {
g2d.setColor(getAreaNameFontColor());
}
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.drawString(getAreaDisplayName(), getAreaNameRectangle().x + 5,
getAreaNameRectangle().y + 12);
g2d.dispose();
}
private void drawGradient(Graphics g) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.setFont(getAreaNameFont());
FontMetrics fm = g2d.getFontMetrics(getAreaNameFont());
LinearGradientPaint lgp = new LinearGradientPaint(0.0f, 0.0f, 0.0f, 16,
getAreaNameFractions(), getAreaNameGradientColors());
g2d.setPaint(lgp);
Rectangle rec = getDisplayRectangle(fm, getAreaDisplayName());
g2d.fillRect(rec.x, rec.y, rec.width, rec.height);
g2d.dispose();
}
private Rectangle getDisplayRectangle(FontMetrics fm, String dispAreaName) {
Rectangle ret = new Rectangle();
ret.width = fm.stringWidth(dispAreaName) + 20;
ret.height = 16;
switch (getAreaNamePosition()) {
case LEFT_TOP:
ret.x = 0;
ret.y = 0;
break;
case LEFT_BOTTOM:
ret.x = 0;
ret.y = getHeight() - ret.height;
break;
case RIGHT_BOTTOM:
ret.x = getWidth() - ret.width;
ret.y = getHeight() - ret.height;
break;
case RIGHT_TOP:
ret.x = getWidth() - ret.width;
ret.y = 0;
break;
default:
throw new RuntimeException("Program error.");
}
return ret;
}
public Rectangle getAreaNameRectangle() {
Graphics g = this.getGraphics();
Graphics2D g2d = (Graphics2D) g.create();
Rectangle ret = new Rectangle();
ret.width = g2d.getFontMetrics(getAreaNameFont()).stringWidth(
getAreaDisplayName()) + 20;
ret.height = 16;
switch (getAreaNamePosition()) {
case LEFT_TOP:
ret.x = 0;
ret.y = 0;
break;
case LEFT_BOTTOM:
ret.x = 0;
ret.y = getHeight() - ret.height;
break;
case RIGHT_BOTTOM:
ret.x = getWidth() - ret.width;
ret.y = getHeight() - ret.height;
break;
case RIGHT_TOP:
ret.x = getWidth() - ret.width;
ret.y = 0;
break;
default:
throw new RuntimeException("Program error.");
}
g2d.dispose();
return ret;
}
}
|
package entity;
import java.util.*;
/**
* An implentation of the Graph
*
* @author Vanesa Georgieva
*
*/
public class Graph {
private HashMap<Integer, Vertex> vertices;
private HashMap<Integer, Vertex> namedVertices;
private HashMap<Integer, Vertex> indexedVertices;
private HashMap<Integer, Edge> edges;
public Graph(){
this.vertices = new HashMap<Integer, Vertex>();
this.edges = new HashMap<Integer, Edge>();
this.namedVertices = new HashMap<Integer, Vertex>();
}
/**
* @param vertices The initial Vertices to populate this Graph
*/
public Graph(ArrayList<Vertex> vertices){
this.vertices = new HashMap<Integer, Vertex>();
this.edges = new HashMap<Integer, Edge>();
for(Vertex v: vertices){
this.vertices.put(v.getLabel(), v);
}
}
/**
* Add edge to graph with given weight
*/
public boolean addEdge(Vertex one, Vertex two, int weight, boolean convert) {
if(one.equals(two)){
return false;
}
//ensures the Edge is not in the Graph
Edge e = new Edge(one, two, weight);
if(edges.containsKey(e.hashCode())){
return false;
}
//and that the Edge isn't already incident to one of the vertices
else if((one.containsNeighbor(e) || two.containsNeighbor(e)) && !convert){
return false;
}
edges.put(e.hashCode(), e);
one.addNeighbor(e);
two.addNeighbor(e);
one.addNeighborVertex(two);
two.addNeighborVertex(one);
return true;
}
/*
* check if the graph contains edge
*/
public boolean containsEdge(Edge e){
if(e.getOne() == null || e.getTwo() == null){
return false;
}
return this.edges.containsKey(e.hashCode());
}
/**
* removes the specified Edge from the Graph
*/
public Edge removeEdge(Edge e){
e.getOne().removeNeighbor(e);
e.getTwo().removeNeighbor(e);
return this.edges.remove(e.hashCode());
}
/**
*check if the graph contains vertex
*/
public boolean containsVertex(Vertex vertex){
return this.vertices.get(vertex.getLabel()) != null;
}
/**
*/
public Vertex getVertex(Integer label){
return vertices.get(label);
}
public Vertex getVertexByName(int vertexName){
return namedVertices.get(vertexName);
}
public Vertex getVertexByIndex(int vertexIndex){
return indexedVertices.get(vertexIndex);
}
/**
* add vertex to the graph
*/
public boolean addVertex(Vertex vertex, boolean overwriteExisting){
Vertex current = this.vertices.get(vertex.getLabel());
if(current != null){
if(!overwriteExisting){
return false;
}
while(current.getNeighborCount() > 0){
this.removeEdge(current.getNeighbor(0));
}
}
vertices.put(vertex.getLabel(), vertex);
namedVertices.put(vertex.getName(), vertex);
return true;
}
/**
*
* remove vertex by label
*/
public Vertex removeVertex(Integer label){
Vertex v = vertices.remove(label);
while(v.getNeighborCount() > 0){
this.removeEdge(v.getNeighbor((0)));
}
return v;
}
/**
*
* @return Set<String> The unique labels of the Graph's Vertex objects
*/
public Set<Integer> vertexKeys(){
return this.vertices.keySet();
}
/**
*
* @return Set<Edge> The Edges of this graph
*/
public Set<Edge> getEdges(){
return new HashSet<Edge>(this.edges.values());
}
/**
*
* @return Set<Vertex> The Vertices of this graph
*/
public Set<Vertex> getVertices(){
return new HashSet<Vertex>(this.vertices.values());
}
public Set<Vertex> getIndexedVertices(){
return new HashSet<Vertex>(this.indexedVertices.values());
}
/**
*
* @return Edge Search for edge in the graph
*/
public Edge findConnected(Vertex v1, Vertex v2) {
Edge edge = new Edge(v1, v2);
if (!this.getEdges().contains(edge))
return null;
return edge;
}
public boolean isConnected(Vertex v1, Vertex v2) {
Edge leftEdge = new Edge(v1, v2);
Edge rigthEdge = new Edge(v2, v1);
if (!this.getEdges().contains(leftEdge) || !this.getEdges().contains(rigthEdge))
return false;
return true;
}
}
|
/*
* Copyright (C) 2019-2023 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hedera.mirror.common.converter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
import java.util.List;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@SuppressWarnings("unchecked")
public class ListToStringSerializer extends JsonSerializer<List<?>> {
public static final JsonSerializer<List<?>> INSTANCE = new ListToStringSerializer();
private static final Class<?> HANDLED_TYPE = ListToStringSerializer.class;
private static final String PREFIX = "{";
private static final String SEPARATOR = ",";
private static final String SUFFIX = "}";
@Override
public Class<List<?>> handledType() {
return (Class<List<?>>) HANDLED_TYPE;
}
@Override
public void serialize(List<?> list, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (list != null) {
gen.writeString(PREFIX + StringUtils.join(list, SEPARATOR) + SUFFIX);
}
}
}
|
package KundenVerwaltung;
import java.util.ArrayList;
public class Kundenliste extends Thread {
private ArrayList<Kunde> kunden = null;
public Kundenliste() {
// suche eine Kundenliste und hole sie in kunden andernfals erstelle eine leere
// kundenliste
// if() {
//
// }else {
kunden = new ArrayList<Kunde>();
kunden.add(new Kunde("Klaus", "Kellermann", "15.11.1998", "Ich heise nicht manni",Kunde.Age.ERWACHSEN));
kunden.add(new Kunde("Hans", "Kellermann", "04.12.1979", "ich bin nicht kurt",Kunde.Age.RENTNER));
kunden.add(new Kunde("Schorsch", "Kellermann", "29.05.1934", "ich mag dih nicht",Kunde.Age.KIND));
kunden.add(new Kunde("Freddy", "Kellermann", "09.01.1986", "du bist dumm",Kunde.Age.ERWACHSEN));
kunden.add(new Kunde("Manni", "Kellermann", "10.05.1967", "ich bins",Kunde.Age.KIND));
kunden.add(new Kunde("Kurt", "Kellermann", "06.03.2008", "ich bin groß",Kunde.Age.RENTNER));
// }
start();
}
public void run() {
// sort the list
}
public String[] getKundenNamen() {
String[] ret = new String[kunden.size()];
int i = 0;
for (Kunde k : kunden) {
ret[i] = k.getFirstName() + " " + k.getLastName() + " ";
i++;
}
return ret;
}
public ArrayList<Kunde> getKunden() {
return kunden;
}
public void setNewKunden(Kunde k) {
kunden.add(k);
}
public void removeKunde(int index) {
if (kunden.size() == 1)
kunden.get(0).setBlank();
else if (index < kunden.size() && index > 0)
kunden.remove(index);
}
public void updateKunde(Kunde k, String firstName, String lastName, String gebDatum, String comment) {
for (Kunde kunde : kunden) {
if (kunde.equals(k)) {
kunde.setFirstName(firstName);
kunde.setLastName(lastName);
kunde.setComment(comment);
kunde.setGebDatum(gebDatum);
}
}
}
}
|
package login;
import java.util.Date;
import exception.ExceptionAlreadyExistingMember;
import member.DaoMember;
import member.Member;
import register.RegisterRequest;
public class ServiceMemberRegister {
private DaoMember daoMember;
public ServiceMemberRegister(DaoMember daoMember) {
super();
this.daoMember = daoMember;
}
public void regist(RegisterRequest req) {
Member member = daoMember.selectByEmail(req.getEmail());
if (member != null) {
throw new ExceptionAlreadyExistingMember("중복 email" + req.getEmail());
}
Member newMember = new Member(req.getEmail(), req.getPassword(), req.getName(), new Date());
daoMember.insert(newMember);
}
}
|
/*
* 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 com.ua.kafkaconsumer;
import java.util.ArrayList;
import java.util.Scanner;
/**
* This is a simple kafka consumer that connects to the merchUpdateTopic and
* retrieves the information stored by the kafka producer
*
* @author diogo
*/
public class main
{
/**
* consumer instance
*/
private static Consumer consumer;
/**
* scanner
*/
private static Scanner sc;
/**
* tries 100 times to retrieve information from the kafka cluster
*/
private static int nTries = 100;
public static void main(String args[])
{
consumer = new Consumer("merchUpdateTopic");
sc = new Scanner(System.in);
boolean exit = false;
while(!exit)
{
for (int i = 0; i < nTries; i++)
{
ArrayList<String> records = consumer.consumeRecordsFromKafka();
// print all the retrieved events
for (int j = 0; j < records.size(); j++)
{
System.out.println(records.get(j));
}
}
System.out.println("Enter \"Y\" to try receiving kafka messages again. or <ENTER> to exit this kafka consumer.");
String input = sc.nextLine();
if (input.toLowerCase().equals("y"))
continue;
else
exit = true;
}
}
}
|
package BikeStore;
import enums.BrakeType;
import enums.MaterialType;
public class Bicycle {
// variáveis de instancia de bicycle
private int id;
private int numberOfGears;
private String mainColor;
private double wheelSize;
private BrakeType brakes;
private MaterialType material;
private double price;
private int guarantee;
// construtor default de bicycle
public Bicycle() {
}
// construtor de bicycle
public Bicycle(int id, int numberOfGears, String mainColor, double wheelSize, BrakeType brakes, MaterialType material, double price, int guarantee) {
this.id = id;
this.numberOfGears = numberOfGears;
this.mainColor = mainColor;
this.wheelSize = wheelSize;
this.brakes = brakes;
this.material = material;
this.price = price;
this.guarantee = guarantee;
}
// TODOS GETTERS AND SETTERS
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getNumberOfGears() {
return numberOfGears;
}
public void setNumberOfGears(int numberOfGears) {
this.numberOfGears = numberOfGears;
}
public String getMainColor() {
return mainColor;
}
public void setMainColor(String mainColor) {
this.mainColor = mainColor;
}
public double getWheelSize() {
return wheelSize;
}
public void setWheelSize(double wheelSize) {
this.wheelSize = wheelSize;
}
public BrakeType getBrakes() {
return brakes;
}
public void setBrakes(BrakeType brakes) {
this.brakes = brakes;
}
public MaterialType getMaterial() {
return material;
}
public void setMaterial(MaterialType material) {
this.material = material;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getGuarantee() {
return guarantee;
}
public void setGuarantee(int guarantee) {
this.guarantee = guarantee;
}
/**
* Metodo para modificar um material colocando um novo e substituir o antigo
*
* @param material old type
* @param newmaterial new type
*/
public void editmaterial(MaterialType material, MaterialType newmaterial) {
this.material = newmaterial;
}
/**
* Printar materiais
*/
public void printmat() {
System.out.println(this.material);
}
/**
* Printar all Bikes
*
* @return Bikes
*/
@Override
public String toString() {
String text = "ID : " + id + "\n"
+ "Number of gears : " + numberOfGears + "\n"
+ "Cor : " + mainColor + "\n"
+ "Garantia : " + guarantee + "\n";
return text;
}
}
|
package com.atgem.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.atgem.dao.ShopDao;
import com.atgem.daoImpl.ShopDaoImpl;
/**
* Servlet implementation class UpdateUserMoneyServlet
*/
@WebServlet("/UpdateUserMoneyServlet")
public class UpdateUserMoneyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//.getWriter().append("Served at: ").append(request.getContextPath());
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String u_id=request.getParameter("u_id");
String money=request.getParameter("money");
ShopDao dao=new ShopDaoImpl();
boolean hasUpdate;
hasUpdate= dao.updateUserMoney(Integer.parseInt(money),Integer.parseInt(u_id));
if(hasUpdate){
response.getWriter().println("success");
}else{
response.getWriter().println("failed");
}
}
}
|
/**
*
* @author 500062053
*/
public class CricPlayer
{
public static void main(String[] args)
{
String ob=new String("Hell");
String obj=new String("Hell");
System.out.println("h");
String s1="Java";
String s2="Java";
System.out.println(s1+s2);
System.out.println(s1==s2);
System.out.println(s1.equals(s2));
System.out.println(ob+obj);
System.out.println(ob==obj);
System.out.println(ob.equals(obj));
}
}
|
package com.examle.multi.service;
import com.examle.multi.entity.User;
import com.examle.multi.repository1.UserRepository1;
import com.examle.multi.repository2.UserRepository2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Random;
@Service
public class UserService {
@Autowired
private UserRepository1 userRepository1;
@Autowired
private UserRepository2 userRepository2;
public User add1(){
User user = new User();
user.setName("张三");
user.setAge(new Random().nextInt(30)+20);
return userRepository1.save(user);
}
public User add2(){
User user = new User();
user.setName("李四");
user.setAge(new Random().nextInt(30)+20);
return userRepository2.save(user);
}
}
|
package com.pajk.pt_examples.rmq;
import com.alibaba.rocketmq.client.QueryResult;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.common.admin.ConsumeStats;
import com.alibaba.rocketmq.common.admin.TopicStatsTable;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.alibaba.rocketmq.common.message.MessageQueue;
import com.alibaba.rocketmq.common.protocol.body.*;
import com.alibaba.rocketmq.common.protocol.route.TopicRouteData;
import com.alibaba.rocketmq.tools.admin.DefaultMQAdminExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Date;
import java.util.Map;
/**
* Created by liqingdong911 on 2015/7/22.
*/
public class FirstMQAdmin {
private static final Logger logger = LoggerFactory.getLogger(FirstMQAdmin.class);
private static volatile boolean isRunning = true;
private static DefaultMQAdminExt mqAdminExt = new DefaultMQAdminExt();
static {
mqAdminExt.setNamesrvAddr("mq1.test.pajkdc.com:9876;mq2.test.pajkdc.com:9876");
mqAdminExt.setInstanceName("admin_inst");
try {
mqAdminExt.start();
} catch (MQClientException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
try {
TopicList topicList = mqAdminExt.fetchAllTopicList();
logger.info("fetchAllTopicList:{}", topicList.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
ClusterInfo clusterInfo = mqAdminExt.examineBrokerClusterInfo();
logger.info("examineBrokerClusterInfo:{}", clusterInfo.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
ConsumerConnection consumerConnection = mqAdminExt.examineConsumerConnectionInfo("FIRST_CONSUMER_GROUP1");
logger.info("examineConsumerConnectionInfo:{}", consumerConnection.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
TopicRouteData topicRouteData = mqAdminExt.examineTopicRouteInfo("FIRST_TOPIC");
logger.info("examineTopicRouteInfo:{}", topicRouteData.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
TopicStatsTable tmp = mqAdminExt.examineTopicStats("FIRST_TOPIC");
logger.info("examineTopicStats:{}", tmp.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
GroupList tmp = mqAdminExt.queryTopicConsumeByWho("FIRST_TOPIC");
logger.info("queryTopicConsumeByWho:{}", tmp.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
//1440756994682
// QueryResult tmp = mqAdminExt.queryMessage("FIRST_TOPIC", "FIRST_TOPIC0", 10, 1441595696000l, 1441682226000l);
//1441682994609
//1441681587892l -3600000*24*30
QueryResult tmp = mqAdminExt.queryMessage("FIRST_TOPIC", "", 1, 0 , new Date().getTime());
logger.info("queryMessage:{},{}", tmp.getIndexLastUpdateTimestamp(), tmp.getMessageList());
logger.info("message detail:{},{}", tmp.getMessageList().get(0), new String(tmp.getMessageList().get(0).getBody(), "utf-8"));
} catch (Throwable e) {
e.printStackTrace();
}
try {
MessageExt tmp = mqAdminExt.viewMessage("0A00805200002AA90000000B9849768D");
logger.info("viewMessage:{},{}", tmp, new String(tmp.getBody(), "utf-8"));
} catch (Throwable e) {
e.printStackTrace();
}
try {
ConsumeStats tmp = mqAdminExt.examineConsumeStats("FIRST_CONSUMER_GROUP1");
logger.info("examineConsumeStats:{}", tmp.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
ProducerConnection tmp = mqAdminExt.examineProducerConnectionInfo("FIRST_PRODUCER_GROUP1", "FIRST_TOPIC");
logger.info("examineProducerConnectionInfo:{}", tmp.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
KVTable tmp = mqAdminExt.fetchBrokerRuntimeStats("10.0.128.82:10921");
logger.info("fetchBrokerRuntimeStats:{}", tmp.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
try {
Map<String, Map<MessageQueue, Long>> tmp = mqAdminExt.getConsumeStatus("FIRST_TOPIC", "FIRST_CONSUMER_GROUP1", "10.0.79.190@33005");
logger.info("getConsumeStatus:{}", tmp);
} catch (Throwable e) {
e.printStackTrace();
}
try {
ConsumerRunningInfo tmp = mqAdminExt.getConsumerRunningInfo("FIRST_CONSUMER_GROUP1", "10.0.79.190@33005");
logger.info("getConsumerRunningInfo:{}", tmp.toJson(true));
} catch (Throwable e) {
e.printStackTrace();
}
final Thread thread = Thread.currentThread();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
logger.info("stop the process");
mqAdminExt.shutdown();
isRunning = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}));
while (isRunning) {
{
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
logger.info("i'm finished");
}
}
|
package com.shoplite.model;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Data
//crea en Mongodb la collection
@Document
public class Empresa {
@Id
private String id;
private String id_persona;
private String fecha;
private int calificacion;
}
|
package onlinepaymentsimulator.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import onlinepaymentsimulator.domain.Token;
import onlinepaymentsimulator.domain.User;
import org.mindrot.jbcrypt.BCrypt;
public class UserDao implements Dao<User> {
private final Connection conn;
public UserDao(Connection connection) {
this.conn = connection;
}
/**
* Login with a username and a password
*
* @param username The username
* @param password The password
* @return Success: a token, error: null
*/
public Token login(Integer username, String password) throws SQLException {
PreparedStatement stmt = conn.prepareStatement("SELECT password FROM \"User\" WHERE name = ?");
// Add username to query and execute query
stmt.setInt(1, username);
ResultSet result = stmt.executeQuery();
// If cannot find user return null
if (!result.next()) {
return null;
}
// If password matches
boolean passwordsMatches = BCrypt.checkpw(password, result.getString("password"));
if (!passwordsMatches) {
return null;
}
// Create a token
long expireTime = new Date().getTime();
expireTime += 15 * 60 * 1000;
Token token = new Token(new Date(expireTime));
return token;
}
@Override
public User single(Integer key) throws SQLException {
PreparedStatement stmt = conn.prepareStatement("SELECT id, name, customer_id FROM \"User\" WHERE name = ?");
stmt.setInt(1, key);
ResultSet result = stmt.executeQuery();
// User found let's create a User object
if(result.next()) {
return new User(result.getInt("id"), result.getInt("name"), new CustomerDao(conn).singlePersonalCustomer(result.getInt("customer_id")));
}
return null;
}
@Override
public List<User> all() throws SQLException {
PreparedStatement stmt = conn.prepareStatement("SELECT id, name, customer_id FROM \"User\"");
ResultSet result = stmt.executeQuery();
// Users found let's create User objects
List<User> users = new ArrayList<>();
while(result.next()) {
users.add(new User(result.getInt("id"), result.getInt("name"), new CustomerDao(conn).singlePersonalCustomer(result.getInt("customer_id"))));
}
return users;
}
public User findById(int id) throws SQLException {
PreparedStatement stmt = conn.prepareStatement("SELECT id, name, customer_id FROM \"User\" WHERE id = ?");
stmt.setInt(1, id);
ResultSet result = stmt.executeQuery();
// User found let's create a User object
if(result.next()) {
return new User(result.getInt("id"), result.getInt("name"), new CustomerDao(conn).singlePersonalCustomer(result.getInt("customer_id")));
}
return null;
}
}
|
package com.kdp.wanandroidclient.ui.core.model.impl;
import com.kdp.wanandroidclient.bean.Article;
import com.kdp.wanandroidclient.bean.PageListData;
import com.kdp.wanandroidclient.net.RxSchedulers;
import com.kdp.wanandroidclient.net.callback.RxObserver;
import com.kdp.wanandroidclient.net.callback.RxPageListObserver;
import com.kdp.wanandroidclient.ui.core.model.IUserModel;
/**
* author: 康栋普
* date: 2018/3/21
*/
public class UserModel extends CommonModel implements IUserModel {
/**
* 收藏的文章列表
* @param page 页码
* @param rxObserver
*/
@Override
public void getCollectArticleList(int page, RxPageListObserver<Article> rxObserver) {
doRxRequest()
.getCollectArticleList(page)
.compose(RxSchedulers.<PageListData<Article>>io_main())
.subscribe(rxObserver);
}
/**
* 删除收藏
* @param id 收藏列表的文章id
* @param originId 首页列表的文章id
* @param callback
*/
@Override
public void deleteCollectArticle(int id, int originId, RxObserver<String> callback) {
doRxRequest()
.deleteCollectArticle(id, originId)
.compose(RxSchedulers.<String>io_main())
.subscribe(callback);
}
}
|
package com.espendwise.manta.web.controllers;
import com.espendwise.manta.dao.EventDAOImpl;
import com.espendwise.manta.i18n.I18nUtil;
import com.espendwise.manta.model.view.BatchOrderView;
import com.espendwise.manta.service.DatabaseUpdateException;
import com.espendwise.manta.service.EventService;
import com.espendwise.manta.spi.AutoClean;
import com.espendwise.manta.spi.SuccessMessage;
import com.espendwise.manta.util.AppComparator;
import com.espendwise.manta.util.AppResourceHolder;
import com.espendwise.manta.util.Constants;
import com.espendwise.manta.util.Pair;
import com.espendwise.manta.util.RefCodeNames;
import com.espendwise.manta.util.SelectableObjects;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.alert.ArgumentedMessage;
import com.espendwise.manta.util.arguments.Args;
import com.espendwise.manta.util.arguments.MessageI18nArgument;
import com.espendwise.manta.util.arguments.NumberArgument;
import com.espendwise.manta.util.arguments.StringArgument;
import com.espendwise.manta.web.forms.BatchOrderLoaderForm;
import com.espendwise.manta.web.forms.BatchOrderLoaderResultForm;
import com.espendwise.manta.web.resolver.DatabaseWebUpdateExceptionResolver;
import com.espendwise.manta.web.util.*;
import com.espendwise.ocean.common.webaccess.BasicResponseValue;
import com.espendwise.ocean.common.webaccess.LoginData;
import com.espendwise.ocean.common.webaccess.ObjectTokenType;
import com.espendwise.ocean.common.webaccess.ResponseError;
import com.espendwise.ocean.common.webaccess.RestRequest;
import com.espendwise.ocean.common.webaccess.WebAccessException;
import com.espendwise.webservice.restful.value.BatchOrderValidationRequestData;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.request.WebRequest;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javassist.bytecode.Descriptor.Iterator;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping(UrlPathKey.BATCH_ORDER.LOADER)
@SessionAttributes({SessionKey.BATCH_ORDER_LOADER, SessionKey.BATCH_ORDER_LOADER_RESULT})
@AutoClean(SessionKey.BATCH_ORDER_LOADER_RESULT)
public class BatchOrderLoaderController extends BaseController {
private static final Logger logger = Logger.getLogger(BatchOrderLoaderController.class);
public static String asSoonAsPossible = new MessageI18nArgument("batchOrder.loader.processWhen.option.asSoonAsPossible").resolve();
public static String moring = new MessageI18nArgument("batchOrder.loader.processWhen.option.moring").resolve();
public static String afternoon = new MessageI18nArgument("batchOrder.loader.processWhen.option.afternoon").resolve();
public static String evening = new MessageI18nArgument("batchOrder.loader.processWhen.option.evening").resolve();
private EventService eventService;
@Autowired
public BatchOrderLoaderController(EventService eventService) {
this.eventService = eventService;
}
public String handleDatabaseUpdateException(DatabaseUpdateException ex, WebRequest request) {
WebErrors webErrors = new WebErrors(request);
webErrors.putErrors(ex, new DatabaseWebUpdateExceptionResolver());
return "batchOrder/loader";
}
@RequestMapping(value = "", method = RequestMethod.POST)
public String save(WebRequest request, @ModelAttribute(SessionKey.BATCH_ORDER_LOADER) BatchOrderLoaderForm loaderForm,
@ModelAttribute(SessionKey.BATCH_ORDER_LOADER_RESULT) BatchOrderLoaderResultForm resultForm, Model model) throws Exception {
logger.info("save()=> BEGIN, batchOrderLoaderForm: "+loaderForm);
WebErrors webErrors = new WebErrors(request);
List<? extends ArgumentedMessage> validationErrors = WebAction.validate(loaderForm);
if (!validationErrors.isEmpty()) {
webErrors.putErrors(validationErrors);
model.addAttribute(SessionKey.BATCH_ORDER_LOADER, loaderForm);
return "batchOrder/loader";
}
// validate file contents with stjohn service
BatchOrderValidationRequestData requestData = new BatchOrderValidationRequestData();
requestData.setStoreId(new Integer(getStoreId().intValue()));
requestData.setAccountId(new Integer(loaderForm.getAccountId()));
requestData.setFileName(loaderForm.getUploadedFile().getOriginalFilename());
requestData.setDataContents(loaderForm.getUploadedFile().getBytes());
Map returnValues = (Map) requestStjohnService(requestData, "/service/validateBatchOrder", webErrors);
if (webErrors.size() > 0){
return "batchOrder/loader";
}
Integer orderCount = new Integer(returnValues.get("orderCount").toString());
List<BatchOrderView> batchOrders = new ArrayList<BatchOrderView>();
BatchOrderView batchOrder = new BatchOrderView();
batchOrder.setEventId(new Long(0));
batchOrder.setStoreId(getStoreId());
batchOrder.setStoreName(getStoreName());
batchOrder.setFileName(loaderForm.getUploadedFile().getOriginalFilename());
String applyToBudget = loaderForm.isApplyToBudget() ? Constants.YES : Constants.NO;
batchOrder.setApplyToBudget(applyToBudget);
String sendConfirmation = loaderForm.isSendConfirmation() ? Constants.YES : Constants.NO;
batchOrder.setSendConfirmation(sendConfirmation);
batchOrder.setOrderCount(orderCount);
batchOrder.setProcessOn(loaderForm.getProcessOn());
batchOrder.setDateFormat(I18nUtil.getDatePattern());
batchOrder.setProcessWhen(loaderForm.getProcessWhen());
batchOrder.setFileBinaryData(loaderForm.getUploadedFile().getBytes());
batchOrder.setAccountId(Long.valueOf(loaderForm.getAccountId()));
batchOrders.add(batchOrder);
try {
batchOrder = eventService.saveBatchOrder(batchOrder, getAppUser().getLocale());
} catch (DatabaseUpdateException e) {
e.printStackTrace();
return handleDatabaseUpdateException(e, request);
}
SelectableObjects<BatchOrderView> selectableObj = new SelectableObjects<BatchOrderView>(
batchOrders,
new ArrayList<BatchOrderView>(),
AppComparator.BATCH_ORDER_VIEW_COMPARATOR);
resultForm.setBatchOrders(selectableObj);
WebAction.success(request, new SuccessActionMessage(), WebRequest.SCOPE_REQUEST);
String qtyIgnoreList = (String) returnValues.get("qtyIgnoreList");
if (qtyIgnoreList != null){
WebAction.success(request, new SuccessActionMessage("batchOrder.loader.lineIgnoredDueToQtyNotGreaterThan0",
new StringArgument[]{new StringArgument(qtyIgnoreList)}), WebRequest.SCOPE_REQUEST);
}
logger.info("save()=> END.");
return "batchOrder/loader";
}
@RequestMapping(value = "", method = RequestMethod.GET)
public String show(@ModelAttribute(SessionKey.BATCH_ORDER_LOADER_RESULT) BatchOrderLoaderResultForm resultForm,
@ModelAttribute(SessionKey.BATCH_ORDER_LOADER) BatchOrderLoaderForm loaderForm, Model model) {
logger.info("show()=> BEGIN");
resultForm.reset();
loaderForm.reset();
model.addAttribute(SessionKey.BATCH_ORDER_LOADER, loaderForm);
logger.info("show()=> END.");
return "batchOrder/loader";
}
@RequestMapping(value = "/cancel", method = RequestMethod.POST)
public String cancel(@ModelAttribute(SessionKey.BATCH_ORDER_LOADER_RESULT) BatchOrderLoaderResultForm resultForm, WebRequest request) throws Exception {
logger.info("cancel()=> BEGIN");
List<Long> selected = new ArrayList<Long>();
List<Long> deSelected = new ArrayList<Long>();
for (BatchOrderView config : resultForm.getBatchOrders().getNewlySelected()){
selected.add(config.getEventId());
}
if (!selected.isEmpty() || !deSelected.isEmpty()){
eventService.cancellEvent(selected);
}
disploayAll(resultForm);
WebAction.success(request, new SuccessActionMessage("batchOrder.loader.cancelledMessage"), WebRequest.SCOPE_REQUEST);
logger.info("cancel()=> END.");
return "batchOrder/loader";
}
@RequestMapping(value = "/displayAll", method = RequestMethod.GET)
public String disploayAll(@ModelAttribute(SessionKey.BATCH_ORDER_LOADER_RESULT) BatchOrderLoaderResultForm resultForm) throws Exception {
logger.info("disploayAll()=> BEGIN");
List<BatchOrderView> batchOrders = eventService.getBatchOrders(getStoreId(), RefCodeNames.EVENT_STATUS_CD.STATUS_HOLD);
SelectableObjects<BatchOrderView> selectableObj = new SelectableObjects<BatchOrderView>(
batchOrders,
new ArrayList<BatchOrderView>(),
AppComparator.BATCH_ORDER_VIEW_COMPARATOR);
resultForm.setBatchOrders(selectableObj);
WebSort.sort(resultForm, "eventId");
logger.info("displayAll()=> END.");
return "batchOrder/loader";
}
@RequestMapping(value = "/sortby/{field}", method = RequestMethod.GET)
public String sort(@ModelAttribute(SessionKey.BATCH_ORDER_LOADER_RESULT) BatchOrderLoaderResultForm resultForm, @PathVariable String field) throws Exception {
WebSort.sort(resultForm, field);
return "batchOrder/loader";
}
@ModelAttribute(SessionKey.BATCH_ORDER_LOADER)
public BatchOrderLoaderForm initModel() {
BatchOrderLoaderForm form = new BatchOrderLoaderForm();
form.initialize();
populateProcessTimeChoices(form);
return form;
}
@ModelAttribute(SessionKey.BATCH_ORDER_LOADER_RESULT)
public BatchOrderLoaderResultForm init(HttpSession session) {
BatchOrderLoaderResultForm batchOrderResult = (BatchOrderLoaderResultForm) session.getAttribute(SessionKey.BATCH_ORDER_LOADER_RESULT);
if (batchOrderResult == null) {
batchOrderResult = new BatchOrderLoaderResultForm();
}
return batchOrderResult;
}
private void populateProcessTimeChoices(BatchOrderLoaderForm form) {
List<Pair<String, String>> processWhenChoices = new ArrayList<Pair<String, String>>();
processWhenChoices.add(new Pair<String, String>(asSoonAsPossible, asSoonAsPossible));
processWhenChoices.add(new Pair<String, String>(moring, moring));
processWhenChoices.add(new Pair<String, String>(afternoon, afternoon));
processWhenChoices.add(new Pair<String, String>(evening, evening));
form.setProcessWhenChoices(processWhenChoices);
}
}
|
package com.company.product;
public class Order {
public Order(Product p1, Product p2) {
products = new Product[2];
products[0] = p1;
products[1] = p2;
}
public String toString() {
return products[0].toString() + products[1].toString() ;
}
Product[] products;
}
|
package org.dota.model;
import lombok.Value;
@Value
public class MatchScores {
private final Integer radiantScore;
private final Integer direScore;
}
|
package org.crama.burrhamilton.validator;
import org.crama.burrhamilton.form.QuestionForm;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
@Component
public class QuestionFormValidator extends LocalValidatorFactoryBean {
@Override
public boolean supports(Class<?> clazz) {
return clazz.isAssignableFrom(QuestionForm.class);
}
@Override
public void validate(Object obj, Errors errors, final Object... validationHints) {
super.validate(obj, errors, validationHints);
}
}
|
package com.zking.ssm.mapper;
import com.zking.ssm.model.SysUser;
import org.springframework.stereotype.Repository;
import java.util.Set;
@Repository
public interface SysUserMapper {
int deleteByPrimaryKey(Integer userid);
int insert(SysUser record);
int insertSelective(SysUser record);
SysUser selectByPrimaryKey(Integer userid);
int updateByPrimaryKeySelective(SysUser record);
int updateByPrimaryKey(SysUser record);
SysUser listUserByName(String username);
Set<String> listRolesByName(String username);
Set<String> listPermissionByName(String username);
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_service_interface;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.app_models.Utility;
import com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.exception.ResourceNotFoundException;
public interface UtilityServiceInterface {
public List<Utility> findAllUtilityInformation();
public ResponseEntity<Utility> findUtilityInformationById(@PathVariable Long utilityid) throws ResourceNotFoundException;
public Utility addUtilityInformation(@Valid @RequestBody Utility utility);
public ResponseEntity<Utility> updateUtilityInformation(@PathVariable long utilityid,
@Valid @RequestBody Utility utilityDetails) throws ResourceNotFoundException;
public Map<String,Boolean> deleteUtilityInformation(@PathVariable long utilityid);
public long findUtilityCount();
}
|
package TimeTable;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Map;
import com.mysql.jdbc.ResultSetMetaData;
public class SelectCourse extends Tinterface{
public ArrayList<String> matchLevel(String level) {
ArrayList courseList = new ArrayList();
DBConnection DBC = new DBConnection();
ResultSet rs = DBC.queryExecute("select NAME from course where LEVEL = ? ", level);
try {
while (rs.next()) {//数据集不为空
courseList.add(rs.getObject(1));
}
System.out.println(courseList);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return courseList;
}
}
|
package com.yoeki.kalpnay.hrporatal.TimeAttendance.Holidays;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.yoeki.kalpnay.hrporatal.R;
import com.yoeki.kalpnay.hrporatal.TimeAttendance.TimeAttendance_Menu;
import java.util.ArrayList;
/**
* Created by IACE on 03-Sep-18.
*/
public class Holiday_activity extends AppCompatActivity {
AppCompatButton /*HolidayTo_date,HolidayFrom_date,*/ holid_home/*, holidayDateSubmit*/;
// Edittextclass Stat_fromdate,Stat_todate;
String Com_fromDate, Com_toDate;
private int mYear, mMonth, mDay;
int whichdate=0;
Boolean validation;
RecyclerView EventView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.holiday);
// HolidayTo_date = (AppCompatButton)findViewById(R.id.HolidayTo_date);
// HolidayFrom_date = (AppCompatButton)findViewById(R.id.HolidayFrom_date);
holid_home = (AppCompatButton)findViewById(R.id.holid_home);
// holidayDateSubmit = (AppCompatButton)findViewById(R.id.holidayDateSubmit);
// Stat_fromdate = (Edittextclass)findViewById(R.id.Stat_fromdate);
// Stat_todate = (Edittextclass)findViewById(R.id.Stat_todate);
EventView = (RecyclerView) findViewById(R.id.eventsList);
// HolidayFrom_date.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// datePicker();
// }
// });
//
// HolidayTo_date.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// whichdate=1;
// datePicker();
// }
// });
holid_home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),TimeAttendance_Menu.class);
startActivity(intent);
finish();
}
});
recyclerData();
// holidayDateSubmit.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// validations();
// if (validation == true) {
// Date fdate;
// Date tdate;
//
// try {
// fdate = new SimpleDateFormat("dd/MM/yyyy").parse(Com_fromDate);
// tdate = new SimpleDateFormat("dd/MM/yyyy").parse(Com_toDate);
//
// if(fdate.after(tdate)){
// Toast.makeText(Holiday_activity.this, "From Date not less then by To date", Toast.LENGTH_SHORT).show();
// }else if(fdate.before(tdate)){
// recyclerData();
// }else if(fdate.equals(tdate)){
// recyclerData();
// }
//
// } catch (ParseException e) {
// e.printStackTrace();
// }
// }
// }
// });
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(getApplicationContext(),TimeAttendance_Menu.class);
startActivity(intent);
finish();
}
public void recyclerData(){
ArrayList<String> EventList = new ArrayList<>();
EventList.add("15~Aug~Independence Day");
EventList.add("5~Sep~Teacher's Day");
EventList.add("2~Oct~Mahatma Gandhi Jayanti");
EventList.add("18~Oct~Maha Navami");
EventList.add("19~Oct~Dussehra");
EventView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
HolidayRecyclerViewAdapter hadapter = new HolidayRecyclerViewAdapter( getApplicationContext() ,EventList);
EventView.setAdapter(hadapter);
}
// private void datePicker(){
// // Get Current Date
// final Calendar c = Calendar.getInstance();
// mYear = c.get(Calendar.YEAR);
// mMonth = c.get(Calendar.MONTH);
// mDay = c.get(Calendar.DAY_OF_MONTH);
//
// DatePickerDialog datePickerDialog = new DatePickerDialog(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT,
// new DatePickerDialog.OnDateSetListener() {
// @Override
// public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// String date_time = (monthOfYear + 1) + "/" + dayOfMonth + "/" + year;
// //*************Call Time Picker Here ********************
// if (whichdate == 1) {
// Com_toDate = date_time;
// Stat_todate.setText(date_time);
// whichdate=0;
// }else{
// Com_fromDate = date_time;
// Stat_fromdate.setText(date_time);
// whichdate=0;
// }
// }
// }, mYear, mMonth, mDay);
// datePickerDialog.show();
// }
//
// public boolean validations() {
// validation = true;
//
// if (Stat_fromdate.getText().toString().equals("") && Stat_todate.getText().toString().equals("")) {
// validation = false;
// Stat_fromdate.setError("Enter From Date");
// Stat_todate.setError("Enter To Date");
//
// }else if (Stat_fromdate.getText().toString().equals("")) {
// validation = false;
// Stat_fromdate.setError("Enter From Date");
// }else if (Stat_todate.getText().toString().equals("")) {
// validation = false;
// Stat_todate.setError("Enter To Date");
// }
// return validation;
// }
}
|
package com.vouz.mobileV2.services;
import android.app.NotificationChannel;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import com.vouz.mobileV2.R;
public class MobileNotificationManager {
private Context context;
private static MobileNotificationManager instance;
private NotificationManagerCompat notificationManagerCompat;
private android.app.NotificationManager notificationManager;
private MobileNotificationManager(Context context){
this.context = context;
notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManager = (android.app.NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
public static MobileNotificationManager getInstance(Context context){
if(instance==null){
instance = new MobileNotificationManager(context);
}
return instance;
}
public void registerNotificationChannelChannel(String channelId, String channelName, String channelDescription) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, android.app.NotificationManager.IMPORTANCE_DEFAULT);
notificationChannel.setDescription(channelDescription);
android.app.NotificationManager notificationManager = context.getSystemService(android.app.NotificationManager.class);
notificationManager.createNotificationChannel(notificationChannel);
}
}
public void triggerNotification(Class targetNotificationActivity, String channelId, String title, String text, String bigText, int priority, boolean autoCancel, int notificationId){
Intent intent = new Intent(context, targetNotificationActivity);
intent.putExtra("count", title);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,channelId)
.setSmallIcon(R.drawable.logo)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo))
.setContentTitle(title)
.setContentText(text)
.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setChannelId(channelId)
.setAutoCancel(true);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(notificationId,builder.build());
}
public void triggerNotification(Class targetNotificationActivity, String channelId, String title, String text, String bigText, int priority, boolean autoCancel, int notificationId, int pendingIntentFlag){
Intent intent = new Intent(context, targetNotificationActivity);
intent.putExtra("count", title);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, pendingIntentFlag);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,channelId)
.setSmallIcon(R.drawable.logo)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo))
.setContentTitle(title)
.setContentText(text)
.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setChannelId(channelId)
.setAutoCancel(true);
notificationManagerCompat.notify(notificationId,builder.build());
}
public void triggerNotificationWithBackStack(Class targetNotificationActivity, String channelId, String title, String text, String bigText, int priority, boolean autoCancel, int notificationId, int pendingIntentFlag){
Intent intent = new Intent(context, targetNotificationActivity);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addNextIntentWithParentStack(intent);
intent.putExtra("count", title);
PendingIntent pendingIntent = taskStackBuilder.getPendingIntent(0, pendingIntentFlag);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,channelId)
.setSmallIcon(R.drawable.logo)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo))
.setContentTitle(title)
.setContentText(text)
.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setChannelId(channelId)
.setOngoing(false)
.setAutoCancel(false);
notificationManagerCompat.notify(notificationId,builder.build());
}
public void updateWithPicture(Class targetNotificationActivity, String title, String text, String channelId, int notificationId, String bigpictureString, int pendingIntentflag) {
Intent intent = new Intent(context, targetNotificationActivity);
intent.putExtra("count", title);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, pendingIntentflag);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,channelId)
.setSmallIcon(R.drawable.logo)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.logo))
.setContentTitle(title)
.setContentText(text)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setChannelId(channelId)
.setAutoCancel(true);
Bitmap androidImage = BitmapFactory.decodeResource(context.getResources(), R.drawable.logo);
builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(androidImage).setBigContentTitle(bigpictureString));
notificationManager.notify(notificationId, builder.build());
}
public void cancelNotification(int notificationId){
notificationManager.cancel(notificationId);
}
}
|
package com.mssql.web;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "SyohinDataPojo")
public class SyohinDataEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "NumId", columnDefinition = "int", nullable = false)
private Integer _NumId;
@Column(name = "SyohinNum", columnDefinition = "smallint", nullable = false)
private Short _SyohinCode;
@Column(name = "SyohinName", columnDefinition = "char(50)", length = 50)
private String _SyohinName;
@Column(name = "EditDate", columnDefinition = "decimal(8, 0)", precision = 8, scale = 0, nullable = false)
private BigDecimal _EditDate;
@Column(name = "EditTime", columnDefinition = "decimal(6, 0)", precision = 6, scale = 0, nullable = false)
private BigDecimal _EditTime;
@Column(name = "Note", columnDefinition = "varchar(255)", length = 50)
private String _Note;
public SyohinDataEntity() {
super();
}
public SyohinDataEntity(Short Code, String Name, BigDecimal Date, BigDecimal Time, String Note) {
super();
_SyohinCode = Code;
_SyohinName = Name;
_EditDate = Date;
_EditTime = Time;
this._Note = Note;
}
public Integer getNumId() {
return _NumId;
}
public Short getSyohinCode() {
return _SyohinCode;
}
public void setSyohinCode(Short value) {
_SyohinCode = value;
}
public String getSyohinName() {
return _SyohinName;
}
public void setSyohinName(String value) {
_SyohinName = value;
}
public BigDecimal getEditDate() {
return _EditDate;
}
public void setEditDate(BigDecimal value) {
_EditDate = value;
}
public BigDecimal getEditTime() {
return _EditTime;
}
public void setEditTime(BigDecimal value) {
_EditTime = value;
}
public String getNote() {
return _Note;
}
public void setNote(String value) {
_Note = value;
}
}
|
package openopoly.control.game;
import java.util.ArrayList;
import openopoly.err.GameException;
import openopoly.util.Card;
import openopoly.util.CardStack;
/**
*
* @author Lucas
* @author Sergio
*/
public class GameChanceStack {
private CardStack chanceStack;
private static GameChanceStack instance;
private boolean prisonChanceDrew;
public static GameChanceStack getInstance(){
if(instance == null){
instance = new GameChanceStack();
}
return instance;
}
public GameChanceStack() {
chanceStack = new CardStack(fillStack());
}
private ArrayList<Card> fillStack() {
ArrayList<Card> stack = new ArrayList<Card>();
stack.add(new Card( 1, "Advance To Go - Collect $200", Card.Type.GOUNTIL, 40, 0));
stack.add(new Card( 2, "Advance To - Illinois Avenue", Card.Type.GOTO, 24, 0));
stack.add(new Card( 3, "Advance To St. Charles Place - If you pass Go, Collect $200", Card.Type.GOUNTIL, 11, 0));
stack.add(new Card( 4, "Advance Token To Nearest Utility - If unowned you may buy it from the bank. If owned, throw dice and pay owner a total ten times the amount thrown.", Card.Type.NEXTUTIL, 0, 0));
stack.add(new Card( 5, "Advance Token To The Nearest Railroad - Pay Owner Twice The Rental To Which He Is Otherwise entitled. If Railroad Is Unowned, You May Buy It From The Bank.", Card.Type.NEXTRAIL, 0, 0));
stack.add(new Card( 6, "Bank Pays You Dividend Of - $50", Card.Type.MODIFY, 50, 0));
stack.add(new Card( 7, "Go Back 3 Spaces", Card.Type.BACK, 0, 0));
stack.add(new Card( 8, "Go Directly To Jail - Do Not Pass Go, Do Not Collect $200", Card.Type.PRISON, 0, 0));
stack.add(new Card( 9, "Make General Repairs On All Your Property - For Each House Pay $25, For Each Hotel $100", Card.Type.REPAIR, 25, 100));
stack.add(new Card(10, "Pay Poor Tax Of - $15", Card.Type.MODIFY, -15, 0));
stack.add(new Card(11, "This Card May Be Kept Until Needed Or Sold - Get Out Of Jail Free", Card.Type.PRISONCARD_CHANCE, 0, 0));
stack.add(new Card(12, "Take A Ride On The Reading - If You Pass Go Collect $200", Card.Type.GOUNTIL, 5, 0));
stack.add(new Card(13, "Take A Walk On The Board Walk - Advance Token To Board Walk", Card.Type.GOUNTIL, 39, 0));
stack.add(new Card(14, "You Have Been Elected Chairman Of The Board - Pay Each Player $50", Card.Type.PAYTOALL, 50, 0));
stack.add(new Card(15, "Your Building And Loan Matures - Collect $150", Card.Type.MODIFY, 150, 0));
stack.add(new Card(16, "Advance Token To The Nearest Railroad - Pay Owner Twice The Rental To Which He Is Otherwise entitled. If Railroad Is Unowned, You May Buy It From The Bank.", Card.Type.NEXTRAIL, 0, 0));
return stack;
}
public void shuffleCards(){
chanceStack.shuffleCards();
}
public void setShuffle(boolean cardShuffle){
chanceStack.setShuffle(cardShuffle);
}
public Card getCurrentCard() throws GameException{
return chanceStack.getCurrentCard();
}
public Card chanceDrawCard() throws GameException{
return chanceStack.drawCard();
}
public void forceNextChanceCard(int cardID) throws GameException{
if(cardID == 11 && prisonChanceDrew){
throw new GameException("This card is already possessed by a player");
}else {
chanceStack.forceNextCard(cardID);
}
}
public void printCards(){
chanceStack.printCards();
}
public void resetChanceStack() {
instance = null;
}
public void setPrisonChanceDrew(boolean prisonChanceDrew) {
this.prisonChanceDrew = prisonChanceDrew;
}
}
|
package com.commercetools.pspadapter.payone.util;
import io.sphere.sdk.payments.Payment;
import io.sphere.sdk.payments.Transaction;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import static com.commercetools.pspadapter.payone.util.PaymentUtil.getTransactionById;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class PaymentUtilTest {
@Mock
private Payment payment;
@Mock
private Transaction transaction;
@Test
public void getTransactionById_emptyCases() {
assertThat(getTransactionById(null, null)).isEmpty();
assertThat(getTransactionById(null, "blah")).isEmpty();
assertThat(getTransactionById(payment, null)).isEmpty();
when(payment.getTransactions()).thenReturn(singletonList(transaction));
when(transaction.getId()).thenReturn("transaction-id");
assertThat(getTransactionById(payment, "blah")).isEmpty();
assertThat(getTransactionById(payment, null)).isEmpty();
assertThat(getTransactionById(payment, "")).isEmpty();
}
@Test
public void getTransactionById_normalCases() {
when(payment.getTransactions()).thenReturn(singletonList(transaction));
when(transaction.getId()).thenReturn("transaction-id");
assertThat(getTransactionById(payment, "transaction-id")).contains(transaction);
Transaction transaction2 = mock(Transaction.class);
when(transaction2.getId()).thenReturn("another-transaction-id");
when(payment.getTransactions()).thenReturn(asList(transaction2, transaction));
assertThat(getTransactionById(payment, "transaction-id")).contains(transaction);
assertThat(getTransactionById(payment, "another-transaction-id")).contains(transaction2);
when(payment.getTransactions()).thenReturn(asList(transaction, transaction2));
assertThat(getTransactionById(payment, "transaction-id")).contains(transaction);
assertThat(getTransactionById(payment, "another-transaction-id")).contains(transaction2);
assertThat(getTransactionById(payment, "blah")).isEmpty();
}
}
|
package com.stackroute.lambdaexpressions;
import java.util.ArrayList;
import java.util.List;
public class StreamDemo {
public static void main(String[] args) {
List<Place> places=new ArrayList<>();
places.add(new Place("Nepal","Kathmandu"));
places.add(new Place("Nepal","Pokhara"));
places.add(new Place("Sri Lanka","Colombo"));
places.add(new Place("India","Mumbai"));
places.add(new Place("Pakistan","Karachi"));
places.stream()
.filter(place -> place.getCountry().equals("Nepal"))
.forEach(p->System.out.println(p.getCity()));
}
}
class Place
{
private String country;
private String city;
public Place(String country, String city) {
this.country = country;
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
@Override
public String toString() {
return "Place{" +
"country='" + country + '\'' +
", city='" + city + '\'' +
'}';
}
}
|
package org.sero.cash.superzk.util;
public class Base58 {
public static String encode(byte[] bytes) {
return io.github.novacrypto.base58.Base58.base58Encode(bytes);
}
public static byte[] decode(String base58) {
return io.github.novacrypto.base58.Base58.base58Decode(base58);
}
}
|
package com.passing.hibernate.beans;
/**
* Jpwordremark generated by MyEclipse Persistence Tools
*/
public class Jpwordremark extends AbstractJpwordremark implements
java.io.Serializable {
// Constructors
/** default constructor */
public Jpwordremark() {
}
/** full constructor */
public Jpwordremark(Jpword jpword, String remark) {
super(jpword, remark);
}
}
|
package com.onlythinking.commons.config;
import com.onlythinking.commons.config.annotation.ApiRest;
import org.springframework.boot.autoconfigure.web.WebMvcRegistrationsAdapter;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import java.lang.reflect.Method;
/**
* <p> The describe </p>
*
* @author Li Xingping
*/
public class ApiRestWebMvcRegistrations extends WebMvcRegistrationsAdapter {
@Override
public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
return new RequestMappingHandlerMapping() {
private final static String API_BASE_PATH = "api";
@Override
protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
Class<?> beanType = method.getDeclaringClass();
ApiRest apiRest = AnnotationUtils.findAnnotation(beanType, ApiRest.class);
if (null != apiRest) {
PatternsRequestCondition apiPattern = new PatternsRequestCondition(API_BASE_PATH + "/" + apiRest.serviceId())
.combine(mapping.getPatternsCondition());
mapping = new RequestMappingInfo(mapping.getName(), apiPattern,
mapping.getMethodsCondition(), mapping.getParamsCondition(),
mapping.getHeadersCondition(), mapping.getConsumesCondition(),
mapping.getProducesCondition(), mapping.getCustomCondition());
}
super.registerHandlerMethod(handler, method, mapping);
}
@Override
protected boolean isHandler(Class<?> beanType) {
return super.isHandler(beanType) && null == AnnotationUtils.findAnnotation(beanType, FeignClient.class);
}
};
}
}
|
/**
*/
package org.ecsoya.yamail.model;
/**
* <!-- begin-user-doc --> A representation of the model object '
* <em><b>Outgoing Server</b></em>'. <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.ecsoya.yamail.model.OutgoingServer#isUseTSL <em>Use TSL</em>}</li>
* <li>{@link org.ecsoya.yamail.model.OutgoingServer#getFromAddress <em>From Address</em>}</li>
* <li>{@link org.ecsoya.yamail.model.OutgoingServer#getEmailPrefix <em>Email Prefix</em>}</li>
* </ul>
* </p>
*
* @see org.ecsoya.yamail.model.YamailPackage#getOutgoingServer()
* @model
* @generated
*/
public interface OutgoingServer extends YamailServer {
/**
* Returns the value of the '<em><b>Use TSL</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Use TSL</em>' attribute isn't clear, there
* really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Use TSL</em>' attribute.
* @see #setUseTSL(boolean)
* @see org.ecsoya.yamail.model.YamailPackage#getOutgoingServer_UseTSL()
* @model
* @generated
*/
boolean isUseTSL();
/**
* Sets the value of the '{@link org.ecsoya.yamail.model.OutgoingServer#isUseTSL <em>Use TSL</em>}' attribute.
* <!-- begin-user-doc --> <!-- end-user-doc -->
* @param value the new value of the '<em>Use TSL</em>' attribute.
* @see #isUseTSL()
* @generated
*/
void setUseTSL(boolean value);
/**
* Returns the value of the '<em><b>From Address</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>From Address</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>From Address</em>' attribute.
* @see #setFromAddress(String)
* @see org.ecsoya.yamail.model.YamailPackage#getOutgoingServer_FromAddress()
* @model
* @generated
*/
String getFromAddress();
/**
* Sets the value of the '{@link org.ecsoya.yamail.model.OutgoingServer#getFromAddress <em>From Address</em>}' attribute.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @param value the new value of the '<em>From Address</em>' attribute.
* @see #getFromAddress()
* @generated
*/
void setFromAddress(String value);
/**
* Returns the value of the '<em><b>Email Prefix</b></em>' attribute. <!--
* begin-user-doc -->
* <p>
* If the meaning of the '<em>Email Prefix</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
*
* @return the value of the '<em>Email Prefix</em>' attribute.
* @see #setEmailPrefix(String)
* @see org.ecsoya.yamail.model.YamailPackage#getOutgoingServer_EmailPrefix()
* @model
* @generated
*/
String getEmailPrefix();
/**
* Sets the value of the '{@link org.ecsoya.yamail.model.OutgoingServer#getEmailPrefix <em>Email Prefix</em>}' attribute.
* <!-- begin-user-doc --> <!--
* end-user-doc -->
* @param value the new value of the '<em>Email Prefix</em>' attribute.
* @see #getEmailPrefix()
* @generated
*/
void setEmailPrefix(String value);
} // OutgoingServer
|
package com.FCI.SWE.Models;
import java.util.ArrayList;
import javax.persistence.criteria.CriteriaBuilder.In;
import org.glassfish.jersey.server.JSONP;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import sun.org.mozilla.javascript.internal.ast.TryStatement;
import sun.org.mozilla.javascript.internal.json.JsonParser;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.datanucleus.annotations.Owned;
/**
*
* @author sabry , Ahmed , Osama
*
*/
public class Post {
public static int postId ;
public static String ownerEmail;
public static String feeling ;
public static String privacy ;
public static String content;
public static int nLike;
public static String sharedFromEmail ;
/**
* Default contractor
*/
public Post() {
postId = 0;
ownerEmail = "";
feeling = "non";
privacy = "";
content = "";
nLike = 0;
sharedFromEmail = "";
}
/**
*
* @param postId
* @param ownerEmail
* @param feeling
* @param privacy
* @param content
* @param nLike
*/
public Post(int postId , String ownerEmail ,String feeling , String privacy , String content ,
int nLike , String sharedFromEmail){
this.postId = postId;
this.ownerEmail = ownerEmail;
this.feeling = feeling;
this.privacy = privacy;
this.content = content;
this.nLike = nLike;
this.sharedFromEmail = sharedFromEmail ;
}
/**
*
* @return
*/
public static int getPostId() {
return postId;
}
/**
*
* @param postId
*/
public static void setPostId(int postId) {
postId = postId;
}
/**
*
* @return
*/
public static String getOwnerEmail() {
return ownerEmail;
}
/**
*
* @param ownerEmail
*/
public static void setOwnerEmail(String ownerEmail) {
ownerEmail = ownerEmail;
}
/**
*
* @return
*/
public static String getFeeling() {
return feeling;
}
/**
*
* @param feeling
*/
public static void setFeeling(String feeling) {
feeling = feeling;
}
/**
*
* @return
*/
public static String getPrivacy() {
return privacy;
}
/**
*
* @param privacy
*/
public static void setPrivacy(String privacy) {
privacy = privacy;
}
/**
*
* @return
*/
public static String getContent() {
return content;
}
/**
*
* @param content
*/
public static void setContent(String content) {
content = content;
}
/**
*
* @return
*/
public static int getnLike() {
return nLike;
}
/**
*
* @param nLike
*/
public static void setnLike(int nLike) {
nLike = nLike;
}
/**
*
* @return
*/
public static String getSharedFromEmail() {
return sharedFromEmail;
}
/**
*
* @param sharedFromEmail
*/
public static void setSharedFromEmail(String sharedFromEmail) {
sharedFromEmail = sharedFromEmail;
}
/**
*
* @return
*/
public static boolean savePost(){
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Query gaeQuery = new Query("posts");
PreparedQuery pq = datastore.prepare(gaeQuery);
postId = DatabaseOperations.getLastId("posts" ,"postId" ) + 1 ;
Entity post = new Entity("posts", postId);
post.setProperty("postId", postId);
post.setProperty("ownerEmail", ownerEmail);
post.setProperty("feeling", feeling);
post.setProperty("privacy", privacy);
post.setProperty("content", content);
post.setProperty("nLike", nLike);
post.setProperty("sharedFromEmail" , sharedFromEmail);
datastore.put(post);
return true;
}
/**
*
* @param _postId
* @return
*/
public static Post getPost(int _postId) {
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Query gaeQuery = new Query("posts");
PreparedQuery pq = datastore.prepare(gaeQuery);
//iterat over all posts
for (Entity entity : pq.asIterable()) {
if (entity.getProperty("postId").toString().equals(_postId) ){
String _ownerEmail = entity.getProperty("ownerEmail").toString();
String _feeling = entity.getProperty("feeling").toString();
String _privacy = entity.getProperty("privacy").toString();
String _content = entity.getProperty("content").toString();
int _nLike = Integer.parseInt(entity.getProperty("nLike").toString() );
String _sharedFromEmail = entity.getProperty("sharedFromEmail").toString();
Post post = new Post(_postId , _ownerEmail , _feeling , _privacy , _content , _nLike , _sharedFromEmail);
return post;
}
}
return null;
}
/**
*
* @param ownerEmail
* @return
*/
public static ArrayList<Post> getAllPosts(String ownerEmail){
ArrayList<Post> allPosts = new ArrayList<Post> ();
DatastoreService datastore = DatastoreServiceFactory
.getDatastoreService();
Query gaeQuery = new Query("posts");
PreparedQuery pq = datastore.prepare(gaeQuery);
//iterat over all posts
for (Entity entity : pq.asIterable()) {
if (entity.getProperty("ownerEmail").toString().equals(ownerEmail) ){
int _postId = Integer.parseInt(entity.getProperty("postId").toString() );
String _ownerEmail = entity.getProperty("ownerEmail").toString();
String _feeling = entity.getProperty("feeling").toString();
String _privacy = entity.getProperty("privacy").toString();
String _content = entity.getProperty("content").toString();
int _nLike = Integer.parseInt(entity.getProperty("nLike").toString() );
String _sharedFromEmail = entity.getProperty("sharedFromEmail").toString();
Post post = new Post(_postId , _ownerEmail , _feeling , _privacy ,
_content , _nLike , _sharedFromEmail);
allPosts.add(post);
}
}
return allPosts;
}
/**
*
* @param json
* @return
*/
public static Post parsePostInfo(String json){
JSONParser parser = new JSONParser();
try {
JSONObject obj = (JSONObject) parser.parse(json);
Post post = new Post();
post.setPostId(Integer.parseInt(obj.get("postId").toString()));
post.setnLike(Integer.parseInt(obj.get("nLike").toString()));
post.setFeeling(obj.get("feeling").toString());
post.setContent( obj.get("content").toString());
post.setOwnerEmail( obj.get("ownerEmail").toString());
post.setOwnerEmail( obj.get("ownerEmail").toString());
post.setPrivacy( obj.get("privacy").toString());
post.setSharedFromEmail( obj.get("sharedFromEmail").toString());
return post ;
} catch (Exception e) {
System.out.println("something goes wrong in function parsePost check that ");
}
return null;
}
}
|
package com.e.jobkwetu.Model;
public class History_Model {
private String name, description ,cost,date,thumbnailUrl;
private float ratting;
public History_Model() {
}
public History_Model(String name, String description, String cost, String date, String thumbnailUrl,float ratting) {
this.name = name;
this.description = description;
this.cost = cost;
this.date = date;
this.thumbnailUrl = thumbnailUrl;
this.ratting = ratting;
}
public float getRatting() {
return ratting;
}
public void setRatting(float ratting) {
this.ratting = ratting;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
}
|
package com.emrekoca.recipe.recipeapp.controllers;
import com.emrekoca.recipe.recipeapp.Services.RecipeServiceImpl;
import com.emrekoca.recipe.recipeapp.model.Recipe;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MockMvcBuilder;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.ui.Model;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
public class IndexControllerTest {
IndexController indexController;
@Mock
RecipeServiceImpl recipeService;
@Mock
Model model;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
indexController = new IndexController(recipeService);
}
@Test
public void testMockMVC() throws Exception{
MockMvc mockMvc = MockMvcBuilders.standaloneSetup(indexController).build();
mockMvc.perform(get("/"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name("index"));
}
@Test
public void getIndexPage() throws Exception {
Set<Recipe> recipes = setUpRecipeData();
when(recipeService.getRecipes()).thenReturn(recipes);
final String index = indexController.getIndexPage(model);
assertEquals("index", index);
verify(recipeService, times(1)).getRecipes();
// any set
verify(model, times(1)).addAttribute(eq("recipes"), anySet());
// set that we setup above
verify(model, times(1)).addAttribute("recipes", recipes);
}
@Test
public void getIndexPageWithArgumentCapture() throws Exception {
Set<Recipe> recipes = setUpRecipeData();
when(recipeService.getRecipes()).thenReturn(recipes);
ArgumentCaptor<Set<Recipe>> argumentCaptor = ArgumentCaptor.forClass(Set.class);
final String index = indexController.getIndexPage(model);
assertEquals("index", index);
verify(recipeService, times(1)).getRecipes();
// any set
verify(model, times(1)).addAttribute(eq("recipes"), anySet());
// set that we setup above
verify(model, times(1)).addAttribute(eq("recipes"), argumentCaptor.capture());
assertEquals(recipes.size(), argumentCaptor.getValue().size());
}
private Set<Recipe> setUpRecipeData() {
Set<Recipe> recipes = new HashSet<>();
recipes.add(new Recipe());
recipes.add(new Recipe());
recipes.add(new Recipe());
assertEquals(1, recipes.size());
return recipes;
}
}
|
package it.uniclam.rilevamento_presenze.JDBCDataAccessObject;
import it.uniclam.rilevamento_presenze.ConnectionDB;
import it.uniclam.rilevamento_presenze.BeanClass.UtenteBean;
import java.sql.*;
import java.util.GregorianCalendar;
public class UtenteJDBCDAO {
Connection connection = null;
PreparedStatement ptmt,ptmt2 = null;
ResultSet resultSet = null;
public UtenteJDBCDAO() {
}
private Connection getConnection() throws SQLException {
Connection conn;
conn = ConnectionDB.getInstance().getConnection();
return conn;
}
public void add(UtenteBean UtenteBean) {
try {
String queryString ="INSERT INTO amici(Cognome, Nome, Telefono) VALUES(?,?,?)";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, UtenteBean.getID_User());
ptmt.setString(2, UtenteBean.getCognome());
ptmt.setString(3, UtenteBean.getNome());
//ptmt.setString(4, UtenteBean.getTelefono());
//ptmt.setString(5, UtenteBean.getEmail());
ptmt.executeUpdate();
System.out.println("Dati Inseriti Correttamente");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void add1(UtenteBean UtenteBean) {
try {
String queryString = "INSERT INTO amici(Cognome, Nome, Telefono) VALUES(?,?,?)";
String queryString2 = "INSERT INTO prestiti(idPrestiti, idAmico, idLibro, DataPrestito, DataRestituzione) VALUES(?,?,?,?,?)";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt2 = connection.prepareStatement(queryString2);
ptmt.setString(1, UtenteBean.getCognome());
ptmt.setString(2, UtenteBean.getNome());
ptmt.setString(3, UtenteBean.getTelefono());
ptmt2.setString(3,"SETptm2");
// ptmt.setString(4, UtenteBean.getEmail());
ptmt.executeUpdate();
ptmt2.executeUpdate();
System.out.println("Dati Inseriti Correttamente");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void update(UtenteBean UtenteBean) {
try {
String queryString = "UPDATE amici SET Cognome=? WHERE Telefono=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, UtenteBean.getCognome());
ptmt.setString(2, UtenteBean.getTelefono());
ptmt.executeUpdate();
System.out.println("Aggiornamento OK");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void delete(int rollNo) {
try {
String queryString = "DELETE FROM amici WHERE RollNo=?";
connection = getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setInt(1, rollNo);
ptmt.executeUpdate();
System.out.println("Eliminato con SUCCESSO");
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void findAll() {
//JOptionPane.showMessageDialog("Ricerca Query Fallita",this);
try {
String queryString = "SELECT * FROM user";
connection = getConnection();
System.out.println("Prepare statement OK");
Statement st = connection.createStatement();
ResultSet res = st.executeQuery(queryString);
while (res.next()) {
int id=res.getInt("ID_User");
String nome = res.getString("Nome");
String cognome = res.getString("Cognome");
String telefono=res.getString("Telefono");
System.out.println(id + "\t" + nome + "\t" + cognome+ "\t" + telefono);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null)
resultSet.close();
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public int SELECT_NameSurname(String name,String surname,String id_user) {
int state=0;
try {
String queryString = "SELECT * FROM user WHERE Cognome='"+surname+"'AND Nome='"+name+"' OR ID_User='"+id_user+"' ";
connection = getConnection();
System.out.println("Prepare statemòent OK");
Statement st = connection.createStatement();
ResultSet res = st.executeQuery(queryString);
/* if (res.next()!=false){
System.out.println("ACCESSO VALIDO");
*/
while (res.next()==true) {
int id=res.getInt("ID_User");
String nome = res.getString("Nome");
String cognome = res.getString("Cognome");
String telefono=res.getString("Telefono");
System.out.println(id + "\t" + nome + "\t" + cognome+ "\t" + telefono);
state=id;}
//if(res.next()==false) { System.out.println("ACCESSO NEGATO:Badge non valido");}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null)
resultSet.close();
if (ptmt != null)
ptmt.close();
if (connection != null)
connection.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return state;
}
}
|
package de.madjosz.adventofcode.y2015;
import static org.junit.jupiter.api.Assertions.assertEquals;
import de.madjosz.adventofcode.AdventOfCodeUtil;
import java.util.List;
import org.junit.jupiter.api.Test;
class Day24Test {
@Test
void day24() {
List<String> lines = AdventOfCodeUtil.readLines(2015, 24);
Day24 day24 = new Day24(lines);
assertEquals(10723906903L, day24.a1());
assertEquals(74850409, day24.a2());
}
@Test
void day24_exampleinput() {
List<String> lines = AdventOfCodeUtil.readLines(2015, 24, "test");
Day24 day24 = new Day24(lines);
assertEquals(99, day24.a1());
assertEquals(44, day24.a2());
}
}
|
package leetcode.SQL;
/**
* Created by yang on 17-6-26.
*/
/*
Write a SQL query to get the second highest salary from the Employee table.
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
For example, given the above Employee table, the query should return 200 as the second highest
salary. If there is no second highest salary, then the query should return null.
+---------------------+
| SecondHighestSalary |
+---------------------+
| 200 |
+---------------------+
*/
public class SecondHighestSalary176 {
String sql1 = "Select MAX(Salary) AS SecondHighestSalary from Employee where Salary < (Select MAX(Salary) from Employee)";
String sql2 = " select distinct Salary from Employee order by Salary Desc limit 1 offset 1";
}
|
package com.lucasgr7.hexagontest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import com.google.common.base.Predicates;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import static springfox.documentation.builders.PathSelectors.regex;
@Profile("dev")
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket postsApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("com.luizalabs.cfgdepara")
.apiInfo(apiInfo()).select().paths(regex("/.*")).apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("API da prova Hexagon")
.description("Cadastro de Vehicle e Vehicle Type")
.contact("Lucas Ribeiro - lucasgr7@gmail.com")
.version("0.0.5").build();
}
}
|
package compiler;
import java.util.HashMap;
public class Division extends Expression {
private final Expression e1, e2;
public Division(Expression e1, Expression e2) {
this.e1 = e1;
this.e2 = e2;
}
@Override
public int eval(HashMap<String, Integer> map) throws Exception {
if (e2.eval(map) == 0)
throw new Exception("Division by 0");
else {
return e1.eval(map) / e2.eval(map);
}
}
}
|
package arrays;
/**
* @author Francisco Jesus Latorre Garcia <franlatorregarcia@gmail.com>
* Crea, dentro del paquete arrays, una clase llamada Triangulo con sus tres
* vértices como atributos y con la visibilidad adecuada. Haz un commit. Crea un
* constructor para esta clase que acepte como parámetros los vértices del
* triángulo y los asigne a los atributos. Haz un commit. Crea los métodos get
* para los diferentes atributos con su visibilidad adecuada. Haz un commit.
* Crea un método llamado toString que devolverá un String que será la
* representación de dicho triángulo: A(x, y) B(x, y) C(x, y). Haz un commit.
* Crea un método llamado perímetro que devolverá el perímetro del triángulo. El
* perímetro de un triángulo se halla sumando sus lados. Por lo que deberás
* hallar los tres lados (AB, AC, BC) y sumarlo. Para hallar cada lado puedes
* recurrir a la distancia entre un punto y otro implementada en la clase Punto.
* Haz un commit.
*/
public class Triangulo {
private Punto verticeA;
private Punto verticeB;
private Punto verticeC;
public Triangulo(Punto verticeA, Punto verticeB, Punto verticeC) {
this.verticeA = verticeA;
this.verticeB = verticeB;
this.verticeC = verticeC;
}
private Punto getVerticeA() {
return verticeA;
}
private Punto getVerticeB() {
return verticeB;
}
private Punto getVerticeC() {
return verticeC;
}
public String toString() {
return "A(" + verticeA + "), B(" + verticeB + "), C(" + verticeC + ")";
}
public double perimetro() {
double distanciaAB = verticeA.distancia(verticeB);
double distanciaAC = verticeA.distancia(verticeC);
double distanciaBC = verticeB.distancia(verticeC);
double perimetro = distanciaAB + distanciaAC + distanciaBC;
return perimetro;
}
}
|
package net.coderbee.mybatis.batch;
import java.util.ArrayList;
import java.util.List;
/**
* 封装要批量操作的参数,插件判断 Mapper 的 parameterType 是此类的实例时才走批量插入, 否则按 MyBatis 的默认方式处理。
*
* @param <T>
* 要插入记录的实体类型
*
* @author <a href="http://coderbee.net">coderbee</a>
*
*/
public class BatchParameter<T> {
private static final int DEFAULT_BATCH_SIZE = 1000;
private final List<T> data;
private final int batchSize;
private final List<Integer> affectedRowCounts;
private BatchParameter(List<T> data, int batchSize) {
this.data = data;
this.batchSize = batchSize;
affectedRowCounts = new ArrayList<Integer>(data.size());
}
public List<T> getData() {
return data;
}
public int getBatchSize() {
return batchSize;
}
public int getAffectedRowCount() {
int count = 0;
for (Integer i : affectedRowCounts) {
if (i > 0) {
count += i;
}
}
return count;
}
public void addRowCounts(int[] counts) {
for (int i : counts) {
affectedRowCounts.add(i);
}
}
public static <T> BatchParameter<T> wrap(List<T> data) {
return wrap(data, DEFAULT_BATCH_SIZE);
}
public static <T> BatchParameter<T> wrap(List<T> data, int batchSize) {
if (data == null || data.isEmpty()) {
throw new IllegalArgumentException("数据为空");
}
if (batchSize < 1) {
throw new IllegalArgumentException("batchSize < 1");
}
return new BatchParameter<T>(data, batchSize);
}
}
|
package org.acme;
public interface Printer {
boolean print(String doc);
}
|
package com.hxsb.model.BUY_ERP_ORDER_CREATE;
public class IntentionTemporary {
private Long Biz_Unit;
private Long Biz_Area;
private Long Biz_Shop;
private String Title;
private Long OperatorID;
private Long Creator;
private Long BILLID;
private String NO;
public Long getBiz_Unit() {
return Biz_Unit;
}
public void setBiz_Unit(Long biz_Unit) {
Biz_Unit = biz_Unit;
}
public Long getBiz_Area() {
return Biz_Area;
}
public void setBiz_Area(Long biz_Area) {
Biz_Area = biz_Area;
}
public Long getBiz_Shop() {
return Biz_Shop;
}
public void setBiz_Shop(Long biz_Shop) {
Biz_Shop = biz_Shop;
}
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public Long getOperatorID() {
return OperatorID;
}
public void setOperatorID(Long operatorID) {
OperatorID = operatorID;
}
public Long getCreator() {
return Creator;
}
public void setCreator(Long creator) {
Creator = creator;
}
public Long getBILLID() {
return BILLID;
}
public void setBILLID(Long bILLID) {
BILLID = bILLID;
}
public String getNO() {
return NO;
}
public void setNO(String nO) {
NO = nO;
}
@Override
public String toString() {
return "IntentionTemporary [Biz_Unit=" + Biz_Unit + ", Biz_Area=" + Biz_Area + ", Biz_Shop=" + Biz_Shop
+ ", Title=" + Title + ", OperatorID=" + OperatorID + ", Creator=" + Creator + ", BILLID=" + BILLID
+ ", NO=" + NO + "]";
}
}
|
/**
* Cassandra specific configuration.
*/
package com.africa.gateway.config.cassandra;
|
package pl.ark.chr.buginator.service.impl;
import org.springframework.data.repository.CrudRepository;
import pl.ark.chr.buginator.domain.BaseEntity;
import pl.ark.chr.buginator.service.CrudService;
import pl.ark.chr.buginator.util.HibernateLazyInitiator;
import java.util.List;
/**
* Created by Arek on 2016-09-29.
*/
public abstract class CrudServiceImpl<T extends BaseEntity> implements CrudService<T> {
protected abstract CrudRepository<T, Long> getRepository();
@Override
public T save(T entity) {
entity = getRepository().save(entity);
return entity;
}
@Override
public T get(Long id) {
T entity = getRepository().findById(id).get();
HibernateLazyInitiator.init(entity);
return entity;
}
@Override
public List<T> getAll() {
List<T> entities = (List<T>) getRepository().findAll();
HibernateLazyInitiator.initList(entities);
return entities;
}
@Override
public void delete(Long id) {
getRepository().deleteById(id);
}
}
|
package com.tencent.mm.ui.contact;
import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.ak.a.a.c;
import com.tencent.mm.ak.o;
import com.tencent.mm.kernel.g;
import com.tencent.mm.openim.a.b;
import com.tencent.mm.openim.a.b.a;
import com.tencent.mm.ui.base.MaskLayout;
public final class v extends LinearLayout {
private Context context;
private String uld;
public v(Context context, String str) {
super(context);
this.context = context;
this.uld = str;
View inflate = View.inflate(getContext(), R.i.openim_item_in_addressui_header, this);
View findViewById = findViewById(R.h.enterprise_biz_item_ll);
inflate.setOnClickListener(new 1(this));
findViewById.setOnTouchListener(new 2(this));
MaskLayout maskLayout = (MaskLayout) findViewById.findViewById(R.h.biz_contact_entrance_avatar_iv);
String h = ((b) g.l(b.class)).h(this.uld, "openim_acct_type_icon", a.euj);
if (h != null) {
ImageView imageView = (ImageView) maskLayout.getContentView();
c.a aVar = new c.a();
aVar.dXy = true;
StringBuilder stringBuilder = new StringBuilder();
g.Ek();
aVar.dXA = stringBuilder.append(g.Ei().dqp).append("openim/").append(com.tencent.mm.a.g.u(h.getBytes())).toString();
o.Pj().a(h, imageView, aVar.Pt(), null, null);
}
((TextView) findViewById(R.h.enterprise_biz_title)).setText(((b) g.l(b.class)).h(this.uld, "openim_acct_type_title", a.eui));
}
}
|
package swm11.jdk.jobtreaming.back.utils;
import com.google.common.primitives.Longs;
import lombok.extern.log4j.Log4j2;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
@Log4j2
public final class LectureUtils {
private static final String secretKey = "ThisIsA_SecretKeyForLivExpert_SW11_JDK!@";
public static boolean enableJoin(String origin, Long lectureId) throws NoSuchAlgorithmException, InvalidKeyException {
String generated = generatePassword(lectureId);
return origin.equals(generated);
}
public static String generatePassword(Long lectureId) throws NoSuchAlgorithmException, InvalidKeyException {
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secret_key = new SecretKeySpec(Longs.toByteArray(lectureId), secretKey);
sha256_HMAC.init(secret_key);
return new String(sha256_HMAC.doFinal(), StandardCharsets.UTF_8);
}
}
|
package de.ybroeker.assertions.json;
import java.util.*;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import org.assertj.core.api.AbstractCharSequenceAssert;
import org.assertj.core.util.CheckReturnValue;
/**
* @author ybroeker
*/
public class JsonAssert extends AbstractCharSequenceAssert<JsonAssert, String> {
private final DocumentContext documentContext;
@CheckReturnValue
public JsonAssert(final String contentAsString) {
super(contentAsString, JsonAssert.class);
documentContext = JsonPath.parse(actual);
}
@CheckReturnValue
public static JsonAssert assertThat(String json) {
return new JsonAssert(json);
}
@CheckReturnValue
public JsonStringAssert jsonPathAsString(String path) {
return new JsonStringAssert(this, documentContext.read(path, String.class));
}
@CheckReturnValue
public <KEY, VALUE> JsonMapAssert<KEY, VALUE> jsonPathAsMap(String path) {
return new JsonMapAssert<KEY,VALUE>(this, documentContext.read(path, Map.class));
}
@CheckReturnValue
public JsonLongAssert jsonPathAsInteger(String path) {
return new JsonLongAssert(this, documentContext.read(path, Long.class));
}
@CheckReturnValue
public JsonDoubleAssert jsonPathAsDouble(String path) {
return new JsonDoubleAssert(this, documentContext.read(path, Double.class));
}
@CheckReturnValue
public JsonBooleanAssert jsonPathAsBoolean(String path) {
return new JsonBooleanAssert(this, documentContext.read(path, Boolean.class));
}
}
|
package com.tencent.mm.plugin.game.gamewebview.ui;
class d$24 implements Runnable {
final /* synthetic */ d jJO;
public d$24(d dVar) {
this.jJO = dVar;
}
public final void run() {
if (d.h(this.jJO) != null) {
d.h(this.jJO).jY(true);
}
}
}
|
package com.nastenkapusechka.validation.analyzers;
import com.nastenkapusechka.validation.annotaions.Email;
import com.nastenkapusechka.validation.util.AnnotationName;
import com.nastenkapusechka.validation.util.exceptions.EmailException;
import java.lang.reflect.Field;
/**
* this analyzer will check email validity.
* Email should be string
*
* @see Email
*/
@AnnotationName(Email.class)
public class EmailAnalyzer implements AnnotationAnalyzer{
private static int countIndex;
// regex to validate email addresses
// according to the official standard RFC 2822
static String regex = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`" +
"{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\" +
"x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:" +
"(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" +
"|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4]" +
"[0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e" +
"-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)])";
/**
*
* @param field annotated field
* @param obj the object of the class that this field belongs to
* @return true if the field is valid, otherwise exception
*
* @see AnnotationAnalyzer#validate(Field, Object)
* @throws EmailException if email does not matches the annotation @Email
* @throws NullPointerException if field contents are null
*/
@Override
public boolean validate(Field field, Object obj) throws EmailException {
countIndex = 1;
if (field == null || obj == null) return false;
field.setAccessible(true);
String email;
String msg = printPlace(field, obj) + "Doesn't match annotation @Email";
try {
if (field.get(obj) == null) throw new NullPointerException();
Email annotation = field.getAnnotation(Email.class);
Object[] objects = convert(field, obj, annotation.mapTarget());
if (objects != null) {
recursive(objects, field.getName());
} else {
email = (String) field.get(obj);
if (!email.matches(regex)) throw new EmailException(msg);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return true;
}
/**
*
* @param array an array of objects to be checked recursively
* according to the annotation (for example, array, list, set, or map)
* @param name the name of the field required to enter information
* about it and the number of its element in the exception message in case of failure.
* @throws EmailException if email does not matches the annotation @Email
* @throws NullPointerException if field contents are null
*/
@Override
public void recursive(Object[] array, String name) throws EmailException {
String place = "Field: " + name + " element #" + countIndex + " ";
String msg = "is not email";
boolean res = false;
if (array.length == 0) return;
String email;
if (array[0] instanceof String) {
email = (String) array[0];
res = email.matches(regex);
} else if (array[0] == null) throw new NullPointerException();
if (!res) throw new EmailException(place + msg);
countIndex++;
Object[] temp = new Object[array.length - 1];
System.arraycopy(array, 1, temp, 0, temp.length);
recursive(temp, name);
}
}
|
package com.espendwise.manta.util;
public enum DistributorPropertyExtraCode implements PropertyExtraCode {
DISTRIBUTOR_TYPE(RefCodeNames.DISTRIBUTOR_TYPE);
private String nameExtraCode;
DistributorPropertyExtraCode(String NameExtraCode) {
this.nameExtraCode = NameExtraCode;
}
public String getNameExtraCode() {
return nameExtraCode;
}
}
|
package Learn;
public class temp {
void print(){
System.out.println("hello this tempo");
}
}
|
package com.ceair.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author lvpeng
* @description
* @date 2020/10/15-13:47
*/
@RestController
@CrossOrigin
public class TestController {
@RequestMapping("test")
public String test(){
return "health";
}
}
|
package com.kaldin.common.db;
import java.sql.ResultSet;
import com.kaldin.common.log.Loger;
import com.kaldin.group.dto.GroupListDTO;
import com.kaldin.user.register.dto.CandidateDTO;
import com.kaldin.user.register.dto.RegisterDTO;
public class PeopleMasterDao {
public RegisterDTO getUserName(String gpn) {
String userName = null;
ToolQueryHelper qh = new ToolQueryHelper();
RegisterDTO registerdto =null;
try {
String query = "select EMAIL_ID,USERNAME from PEOPLE_MASTER where GPN = ?";
qh.addParam(gpn);
ResultSet rs = qh.runQueryStreamResults(query);
while (rs.next())
{
registerdto = new RegisterDTO();
registerdto.setEmail(rs.getString("EMAIL_ID"));
registerdto.setUserName(rs.getString("USERNAME"));
}
} catch (Exception e) {
Loger.log(2, e);
}
finally
{
qh.releaseConnection();
}
return registerdto ;
}
public CandidateDTO getCandidate(String gpn) {
String userName = null;
ToolQueryHelper qh = new ToolQueryHelper();
CandidateDTO candidateDTO =null;
try {
String query = "select EMAIL_ID,USERNAME from PEOPLE_MASTER where GPN = ?";
qh.addParam(gpn);
ResultSet rs = qh.runQueryStreamResults(query);
while (rs.next())
{
candidateDTO = new CandidateDTO();
candidateDTO.setEmail(rs.getString("EMAIL_ID"));
candidateDTO.setUsername(rs.getString("USERNAME"));
}
} catch (Exception e) {
Loger.log(2, e);
}
finally
{
qh.releaseConnection();
}
return candidateDTO ;
}
}
|
/*
* 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 uptc.softMin.gui.old;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.IOException;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import uptc.softMin.gui.MainWindow;
/**
*
* @author Alejandro y Sergio
*/
public class ClDeere extends JDialog implements ActionListener, KeyListener {
private MainWindow mainWin;
private Font font;
private JLabel lbInformation;
private JLabel lbEquation1;
private JLabel lbEquation2;
private JLabel lbEquation3;
private JLabel lbInput1;
private JLabel lbInput2;
private JLabel lbResult;
private ButtonGroup btnGroup;
private JRadioButton rbEquation1;
private JRadioButton rbEquation2;
private JRadioButton rbEquation3;
private JButton btnCalculate;
private JButton btnHelpDeere;
private JTextField txInput1;
private JTextField txInput2;
public ClDeere(MainWindow mainWin) {
this.mainWin = mainWin;
setTitle("Clasificación Deere (RQD)");
setResizable(false);
setModal(true);
setResizable(false);
setLayout(null);
setSize(600, 400);
setLocationRelativeTo(null);
ImageIcon ImageIcon = new ImageIcon("resours/images/icMineria.png");
Image image = ImageIcon.getImage();
this.setIconImage(image);
beginComponents();
addComponents();
}
public void beginComponents() {
font = new Font("Comic Sans MS", Font.BOLD, 15);
lbInformation = new JLabel("Elija la formula con la que desea realizar el cálculo");
lbInformation.setBounds(20, 20, 300, 25);
lbEquation1 = new JLabel(new ImageIcon("resours/images/Equation1.png"));
lbEquation1.setBounds(35, 60, 400, 50);
lbEquation2 = new JLabel(new ImageIcon("resours/images/Equation2.png"));
lbEquation2.setBounds(37, 108, 180, 50);
lbEquation3 = new JLabel(new ImageIcon("resours/images/Equation3.png"));
lbEquation3.setBounds(32, 140, 150, 50);
rbEquation1 = new JRadioButton();
rbEquation1.setBounds(15, 75, 20, 20);
rbEquation1.addActionListener(this);
rbEquation2 = new JRadioButton();
rbEquation2.setBounds(15, 120, 20, 20);
rbEquation2.addActionListener(this);
rbEquation3 = new JRadioButton();
rbEquation3.setBounds(15, 154, 20, 20);
rbEquation3.addActionListener(this);
btnGroup = new ButtonGroup();
btnGroup.add(rbEquation1);
btnGroup.add(rbEquation2);
btnGroup.add(rbEquation3);
lbInput1 = new JLabel();
lbInput1.setBounds(15, 200, 350, 25);
txInput1 = new JTextField();
txInput1.setBounds(25, 225, 70, 25);
txInput1.setEnabled(false);
lbInput2 = new JLabel();
lbInput2.setBounds(15, 250, 350, 25);
txInput2 = new JTextField();
txInput2.setBounds(25, 275, 70, 25);
txInput2.setEnabled(false);
lbResult = new JLabel("RQD: ");
lbResult.setBounds(350, 240, 200, 30);
lbResult.setFont(font);
btnCalculate = new JButton("Calcular");
btnCalculate.setBounds(25, 325, 120, 30);
btnCalculate.addActionListener(this);
btnHelpDeere = new JButton("Ayuda");
btnHelpDeere.setBounds(150, 325, 120, 30);
btnHelpDeere.addActionListener(this);
}
public void addComponents() {
add(lbInformation);
add(lbEquation1);
add(lbEquation2);
add(lbEquation3);
add(rbEquation1);
add(rbEquation2);
add(rbEquation3);
add(lbInput1);
add(lbInput2);
add(txInput1);
add(txInput2);
add(lbResult);
add(btnCalculate);
add(btnHelpDeere);
}
public JLabel getLbResult() {
return lbResult;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == rbEquation1) {
lbInput1.setText("Ingrese el valor del numerador:");
txInput1.setEnabled(true);
txInput1.setText("");
txInput1.addKeyListener(this);
lbInput2.setText("Ingrese el valor del denominador:");
txInput2.setText("");
txInput2.setEnabled(true);
txInput2.addKeyListener(this);
}
if (e.getSource() == rbEquation2) {
lbInput1.setText("Ingrese la frecuencia de discontinuidad:");
txInput1.setEnabled(true);
lbInput2.setText("");
txInput1.setText("");
txInput1.addKeyListener(this);
txInput2.setText("");
txInput2.setEnabled(false);
}
if (e.getSource() == rbEquation3) {
lbInput1.setText("Ingrese el total de discontinuidades por metro cúbico:");
txInput1.setEnabled(true);
txInput1.addKeyListener(this);
lbInput2.setText("");
txInput2.setEnabled(false);
txInput1.setText("");
txInput2.setText("");
}
if (e.getSource() == btnCalculate) {
lbResult.setText("RQD: ");
if (rbEquation1.isSelected()) {
if (txInput1.getText().length() > 0 && txInput2.getText().length() > 0) {
lbResult.setText(lbResult.getText() + String.valueOf(
mainWin.getManagementOld().calculateEquation1(
Double.parseDouble(txInput1.getText()),
Double.parseDouble(txInput2.getText()))));
} else {
JOptionPane.showMessageDialog(null, "Hay campos vacíos", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if (rbEquation2.isSelected()) {
if (txInput1.getText().length() > 0) {
lbResult.setText(lbResult.getText() + String.valueOf(
mainWin.getManagementOld().calculateEquation2(
Double.parseDouble(txInput1.getText()))));
} else {
JOptionPane.showMessageDialog(null, "Hay campos vacíos", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
if (rbEquation3.isSelected()) {
if (txInput1.getText().length() > 0) {
lbResult.setText(lbResult.getText() + String.valueOf(
mainWin.getManagementOld().calculateEquation3(
Double.parseDouble(txInput1.getText()))));
} else {
JOptionPane.showMessageDialog(null, "Hay campos vacíos", "ERROR", JOptionPane.ERROR_MESSAGE);
}
}
}
if(e.getSource() == btnHelpDeere){
helpPDFDeere();
}
}
//Metodo que abre el pdf
private void helpPDFDeere() {
try{
File path = new File("resours/Files/ayudaRQD.pdf");
Desktop.getDesktop().open(path);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cleanFields() {
txInput1.setText("");
txInput1.setEnabled(false);
txInput2.setText("");
txInput2.setEnabled(false);
lbInput1.setText("");
lbInput2.setText("");
lbResult.setText("RQD: ");
rbEquation1.setSelected(false);
rbEquation2.setSelected(false);
rbEquation3.setSelected(false);
}
@Override
public void keyTyped(KeyEvent e) {
char va = e.getKeyChar();
if (e.getSource() == txInput1) {
if (((va < '0') || (va > '9')) && (va != KeyEvent.VK_BACK_SPACE) && (va != '.' || txInput1.getText().contains("."))) {
getToolkit().beep();
e.consume();
}
} else if (e.getSource() == txInput2) {
if (((va < '0') || (va > '9')) && (va != KeyEvent.VK_BACK_SPACE) && (va != '.' || txInput1.getText().contains("."))) {
getToolkit().beep();
e.consume();
}
}
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
}
|
// ============================================================================
// Floxp.com : Java Enum Source File
// ============================================================================
//
// Enum: ExecutionState
// Package: FloXP Utilites (org.fuusio.api.util)
//
// Author: Marko Salmela
//
// Copyright (C) Marko Salmela, 2000-2011. All Rights Reserved.
//
// This software is the proprietary information of Marko Salmela.
// Use is subject to license terms. This software is protected by
// copyright and distributed under licenses restricting its use,
// copying, distribution, and decompilation. No part of this software
// or associated documentation may be reproduced in any form by any
// means without prior written authorization of Marko Salmela.
//
// Disclaimer:
// -----------
//
// This software is provided by the author '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 author 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 org.fuusio.api.util;
public enum ExecutionState {
DORMANT("Dormant"), //
INITIALIZED("Initialized"), //
ACTIVE("Active"), //
SUSPENDED("Suspended"), //
STOPPED("Stopped"), //
ILLEGAL_STATE("Illegal State");
private final String mLabel;
ExecutionState(final String label) {
mLabel = label;
}
public String getLabel() {
return mLabel;
}
public final boolean isActive() {
return (this == ACTIVE);
}
public final boolean isDormant() {
return (this == DORMANT);
}
public final boolean isInitialized() {
return (this == INITIALIZED);
}
public final boolean isStopped() {
return (this == STOPPED);
}
public final boolean isSuspended() {
return (this == SUSPENDED);
}
}
|
package tolteco.sigma.model.entidades;
/**
* Identifica a situacao de uma ginanca ou servico
* @author Juliano Felipe
*/
public enum Situacao {
PENDENTE(0, "Pendente"), //Pendente é 0,
SERVICOPAGO(1, "Quitado"), //ZERO tem mais "prioridade".
FINANCAPAGA(2, "Quitada");
private final int value;
private final String descricao;
private Situacao (int value, String descricao){
this.value = value;
this.descricao = descricao;
}
/**
* Dado um inteiro, retorna o
* tipo de Situacao relacionado.
* @param codigo do tipo inteiro.
* @return Access correspondente.
* @throws IllegalArgumentException Caso seja fora do limite.
*/
public static Situacao porCodigo (int codigo){
for (Situacao op : Situacao.values())
if (codigo == op.value) return op;
throw new IllegalArgumentException ("Código inválido. Limite excedido.");
}
public int getCodigo() {
return value;
}
public String getDescricao(){
return descricao;
}
}
|
package com.tencent.mm.protocal.c;
import com.tencent.mm.bk.a;
import java.util.LinkedList;
public final class aqq extends a {
public String bHD;
public int hcE;
public String lCG;
public float lCH;
public int lCI;
public LinkedList<Integer> lCJ = new LinkedList();
public int lCK;
public LinkedList<bhz> lCL = new LinkedList();
public float lCM;
public String lCN;
public bhy lCO;
public String rTm;
public bhy rTn;
public int rTo;
public int rTp;
protected final int a(int i, Object... objArr) {
int h;
byte[] bArr;
if (i == 0) {
f.a.a.c.a aVar = (f.a.a.c.a) objArr[0];
if (this.lCG != null) {
aVar.g(1, this.lCG);
}
if (this.bHD != null) {
aVar.g(2, this.bHD);
}
aVar.l(3, this.lCH);
aVar.fT(4, this.lCI);
aVar.c(5, this.lCJ);
aVar.fT(6, this.lCK);
aVar.d(7, 8, this.lCL);
aVar.l(8, this.lCM);
if (this.lCN != null) {
aVar.g(9, this.lCN);
}
aVar.fT(10, this.hcE);
if (this.lCO != null) {
aVar.fV(11, this.lCO.boi());
this.lCO.a(aVar);
}
if (this.rTm != null) {
aVar.g(12, this.rTm);
}
if (this.rTn != null) {
aVar.fV(13, this.rTn.boi());
this.rTn.a(aVar);
}
aVar.fT(14, this.rTo);
aVar.fT(15, this.rTp);
return 0;
} else if (i == 1) {
if (this.lCG != null) {
h = f.a.a.b.b.a.h(1, this.lCG) + 0;
} else {
h = 0;
}
if (this.bHD != null) {
h += f.a.a.b.b.a.h(2, this.bHD);
}
h = (((((h + (f.a.a.b.b.a.ec(3) + 4)) + f.a.a.a.fQ(4, this.lCI)) + f.a.a.a.b(5, this.lCJ)) + f.a.a.a.fQ(6, this.lCK)) + f.a.a.a.c(7, 8, this.lCL)) + (f.a.a.b.b.a.ec(8) + 4);
if (this.lCN != null) {
h += f.a.a.b.b.a.h(9, this.lCN);
}
h += f.a.a.a.fQ(10, this.hcE);
if (this.lCO != null) {
h += f.a.a.a.fS(11, this.lCO.boi());
}
if (this.rTm != null) {
h += f.a.a.b.b.a.h(12, this.rTm);
}
if (this.rTn != null) {
h += f.a.a.a.fS(13, this.rTn.boi());
}
return (h + f.a.a.a.fQ(14, this.rTo)) + f.a.a.a.fQ(15, this.rTp);
} else if (i == 2) {
bArr = (byte[]) objArr[0];
this.lCJ.clear();
this.lCL.clear();
f.a.a.a.a aVar2 = new f.a.a.a.a(bArr, unknownTagHandler);
for (h = a.a(aVar2); h > 0; h = a.a(aVar2)) {
if (!super.a(aVar2, this, h)) {
aVar2.cJS();
}
}
return 0;
} else if (i != 3) {
return -1;
} else {
f.a.a.a.a aVar3 = (f.a.a.a.a) objArr[0];
aqq aqq = (aqq) objArr[1];
int intValue = ((Integer) objArr[2]).intValue();
LinkedList IC;
int size;
f.a.a.a.a aVar4;
boolean z;
bhy bhy;
switch (intValue) {
case 1:
aqq.lCG = aVar3.vHC.readString();
return 0;
case 2:
aqq.bHD = aVar3.vHC.readString();
return 0;
case 3:
aqq.lCH = aVar3.vHC.readFloat();
return 0;
case 4:
aqq.lCI = aVar3.vHC.rY();
return 0;
case 5:
aqq.lCJ = new f.a.a.a.a(aVar3.cJR().lR, unknownTagHandler).cJO();
return 0;
case 6:
aqq.lCK = aVar3.vHC.rY();
return 0;
case 7:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhz bhz = new bhz();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhz.a(aVar4, bhz, a.a(aVar4))) {
}
aqq.lCL.add(bhz);
}
return 0;
case 8:
aqq.lCM = aVar3.vHC.readFloat();
return 0;
case 9:
aqq.lCN = aVar3.vHC.readString();
return 0;
case 10:
aqq.hcE = aVar3.vHC.rY();
return 0;
case 11:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, a.a(aVar4))) {
}
aqq.lCO = bhy;
}
return 0;
case 12:
aqq.rTm = aVar3.vHC.readString();
return 0;
case 13:
IC = aVar3.IC(intValue);
size = IC.size();
for (intValue = 0; intValue < size; intValue++) {
bArr = (byte[]) IC.get(intValue);
bhy = new bhy();
aVar4 = new f.a.a.a.a(bArr, unknownTagHandler);
for (z = true; z; z = bhy.a(aVar4, bhy, a.a(aVar4))) {
}
aqq.rTn = bhy;
}
return 0;
case 14:
aqq.rTo = aVar3.vHC.rY();
return 0;
case 15:
aqq.rTp = aVar3.vHC.rY();
return 0;
default:
return -1;
}
}
}
}
|
package com.yanan.framework.boot.web;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* 定义一个WebContext
* @author yanan
*
*/
@Retention(RUNTIME)
@Target({ TYPE })
@Repeatable(WebContextGroups.class)
public @interface WebContext {
/**
* WebApp请求上下文
* @return
*/
String contextPath();
/**
* WebApp的资源路径
* @return
*/
String docBase();
}
|
package com.hendriksen.fragments;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.androidplot.xy.XYPlot;
import com.hendriksen.model.Game;
import com.hendriksen.model.GameBarPlot;
import com.hendriksen.squashtracker.R;
/**
* This fragment shows the user the selected Game information.
* This includes graphs and shot statistics.
*/
public class GameFragment extends Fragment {
//Class Tag.
private static final String TAG = GameFragment.class.getName();
//Current game being shown.
private Game game;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game,
container, false);
//Get the game object from the parcelable extra.
Bundle bundle = this.getArguments();
if (bundle != null) {
game = bundle.getParcelable(Game.TAG);
}
if (game != null) {
//Get hold of the score view and set the score.
TextView tvScore = (TextView) view.findViewById(R.id.tvScore);
tvScore.setText("" + game.getYourScore() + " - " + game.getOpponentsScore());
//Set the score box colour depending on the highest score.
if (game.getYourScore() > game.getOpponentsScore()) {
//Win.
tvScore.setBackgroundColor(getActivity().getResources().getColor(R.color.green_end));
} else if (game.getYourScore() < game.getOpponentsScore()) {
//Loss.
tvScore.setBackgroundColor(getActivity().getResources().getColor(R.color.red_end));
} else {
//Draw.
tvScore.setBackgroundColor(getActivity().getResources().getColor(R.color.yellow_end));
}
//Populate the swing breakdown information.
TextView tvMostSuccessfulShotValue = (TextView) view.findViewById(R.id.tvMostSuccessfulShotValue);
TextView tvLeastSuccessfulShotValue = (TextView) view.findViewById(R.id.tvLeastSuccessfulShotValue);
TextView tvTotalNumberOfShotsValue = (TextView) view.findViewById(R.id.tvTotalNumberOfShotsValue);
tvMostSuccessfulShotValue.setText((game.getMostSuccessfulShotType().isEmpty() ? "-" : game.getMostSuccessfulShotType()));
tvLeastSuccessfulShotValue.setText(game.getLeastSuccessfulShotType().isEmpty() ? "-" : game.getLeastSuccessfulShotType());
tvTotalNumberOfShotsValue.setText("" + (game.getForehandSwings() + game.getBackhandSwings()));
//Get the swing values.
int[] swingValues = new int[8];
swingValues[0] = game.getForehandDrives();
swingValues[1] = game.getBackhandDrives();
swingValues[2] = game.getForehandDrops();
swingValues[3] = game.getBackhandDrops();
swingValues[4] = game.getForehandLobs();
swingValues[5] = game.getBackhandLobs();
swingValues[6] = game.getForehandVolleys();
swingValues[7] = game.getBackhandVolleys();
//Populate the Bar chart.
XYPlot xypBarChart = (XYPlot) view.findViewById(R.id.xypBarChart);
//Initialise the bar plot.
GameBarPlot gameBarPlot = new GameBarPlot(getActivity(), xypBarChart);
//Update the plot.
gameBarPlot.updatePlot(game);
} else {
Log.e(TAG, "Game is null!");
}
return view;
}
}
|
/**
*/
package Forms;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Password Field</b></em>'.
* <!-- end-user-doc -->
*
*
* @see Forms.FormsPackage#getPasswordField()
* @model
* @generated
*/
public interface PasswordField extends InputElement {
} // PasswordField
|
package com.sy.sa;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.WaitStrategy;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.BasicExecutor;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
/**
*
* @data 2019年5月5日 上午10:43:56
* @author ztq
**/
public class test {
public static void main(String[] args) {
//step_4 定义用于事件处理的线程池
BasicExecutor executor = new BasicExecutor(new DefaultThreadFactory());
//指定等待策略
WaitStrategy BLOCKING_WAIT = new BlockingWaitStrategy();
//step_5 启动Disruptor
//预先调用所有事件以填充RingBuffer
EventFactory<LongEvent> eventFactory = new LongEventFactory();
// ExecutorService executor1 = Executors.newSingleThreadExecutor();
// RingBuffer大小,必须是2的N次方
int ringBufferSize = 1024*1024;
//step_6 消费事件
Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(eventFactory,ringBufferSize,executor,ProducerType.SINGLE,new YieldingWaitStrategy());
EventHandler<LongEvent> eventHandler = new LongEventHandler();
disruptor.handleEventsWith(eventHandler);
disruptor.start();
// step_7 发布事件;
RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
long sequence = ringBuffer.next();//请求下一个事件序号;
try {
LongEvent event = ringBuffer.get(sequence);//获取该序号对应的事件对象;
long data = getEventData();//获取要通过事件传递的业务数据;
event.set(data);
} finally{
ringBuffer.publish(sequence);//发布事件;
}
}
private static long getEventData() {
return 999;
}
public static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);//原子类,线程池编号
private final ThreadGroup group;//线程组
private final AtomicInteger threadNumber = new AtomicInteger(1);//线程数目
private final String namePrefix;//为每个创建的线程添加的前缀
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();//取得线程组
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);//真正创建线程的地方,设置了线程的线程组及线程名
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)//默认是正常优先级
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
//step_3:定义事件处理的具体实现
public static class LongEventHandler implements EventHandler<LongEvent>{
@Override
public void onEvent(LongEvent event, long sequence, boolean endOfBatch) throws Exception {
System.out.println("Event" + event.value);
}
}
// step_2: 定义事件工厂
public static class LongEventFactory implements EventFactory<LongEvent>{
@Override
public LongEvent newInstance() {
return new LongEvent();
}
}
//step_1:定义事件
public static class LongEvent{
private long value;
public void set(long value) {
this.value = value;
}
}
}
|
package com.link.shop.common;
import com.jfinal.config.*;
import com.jfinal.ext.handler.ContextPathHandler;
import com.jfinal.template.Engine;
import com.link.shop.controller.IndexController;
/**
* Created by linkzz on 2017-06-01.
*/
public class ShopConfig extends JFinalConfig{
@Override
public void configConstant(Constants constants) {
}
@Override
public void configRoute(Routes routes) {
routes.add("/", IndexController.class);
}
@Override
public void configEngine(Engine engine) {
}
@Override
public void configPlugin(Plugins plugins) {
}
@Override
public void configInterceptor(Interceptors interceptors) {
}
@Override
public void configHandler(Handlers handlers) {
handlers.add(new ContextPathHandler("ctx"));
}
}
|
package popcol.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import popcol.model.Event;
import popcol.service.EventService;
import popcol.service.PagingPgm;
@Controller
public class EventController {
@Autowired
private EventService es;
@RequestMapping("eventList")
public String eventList(String pageNum, Event event, Model model) {
final int ROW_PER_PAGE = 10;
if(pageNum == null || pageNum.equals("")) {
pageNum = "1";
}
int currentPage = Integer.parseInt(pageNum);
int total = es.getTotal(event);
int startRow = (currentPage - 1) * ROW_PER_PAGE + 1;
int endRow = startRow + ROW_PER_PAGE - 1;
event.setStartRow(startRow);
event.setEndRow(endRow);
List<Event> list = es.eventList(event);
PagingPgm pp = new PagingPgm(total, ROW_PER_PAGE, currentPage);
int no = total - startRow + 1;
model.addAttribute("eventList", list);
model.addAttribute("no", no);
model.addAttribute("pageNum", pageNum);
model.addAttribute("pp", pp);
model.addAttribute("search", event.getSearch());
model.addAttribute("keyword", event.getKeyword());
return "eventList";
}
@RequestMapping("eventView")
public String eventView(int eid, String pageNum, Model model) {
Event event = es.selectEvent(eid);
model.addAttribute("event", event);
model.addAttribute("pageNum", pageNum);
return "eventView";
}
}
|
package _2mapperProxy;
/**
* Created by acey on 17-3-19.
*/
public interface StudentMapper {
void insertStu(Student student);
Student findById(int id);
void updateStu(Student student);
void deleteById(int id);
}
|
package com.tencent.mm.plugin.gallery.view;
import com.tencent.mm.plugin.gallery.view.MultiGestureImageView.i;
class MultiGestureImageView$i$1 implements Runnable {
final /* synthetic */ i jFq;
MultiGestureImageView$i$1(i iVar) {
this.jFq = iVar;
}
public final void run() {
this.jFq.jFl.getImageMatrix().getValues(this.jFq.jFk);
float f = this.jFq.jFk[5];
float scale = this.jFq.jFl.getScale() * ((float) this.jFq.jFl.getImageHeight());
if (scale < ((float) MultiGestureImageView.i(this.jFq.jFj))) {
scale = (((float) MultiGestureImageView.i(this.jFq.jFj)) / 2.0f) - (scale / 2.0f);
} else {
scale = 0.0f;
}
scale -= f;
if (scale >= 0.0f) {
this.jFq.bwt = true;
} else if (Math.abs(scale) <= 5.0f) {
this.jFq.bwt = true;
} else {
scale = (-((float) (((double) Math.abs(scale)) - Math.pow(Math.sqrt((double) Math.abs(scale)) - 1.0d, 2.0d)))) * 2.0f;
}
this.jFq.jFl.V(0.0f, scale);
}
}
|
package org.Graphics;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.util.texture.Texture;
import org.Resource.ImageResource;
public class Graphics {
//Color vals
private static float red=1,green=1,blue=1,alpha=1;
//Rotation
private static float rotation=0;
public static void fillRect(float x, float y, float width, float height){
GL2 gl= Renderer.gl;
gl.glTranslatef(x,y,0);
gl.glRotatef(-rotation,0,0,1);
gl.glColor4f(red,green,blue,alpha);
gl.glBegin(GL2.GL_QUADS);
gl.glVertex2f(-width/2,-height/2);
gl.glVertex2f(width/2,-height/2);
gl.glVertex2f(width/2,height/2);
gl.glVertex2f(-width/2,height/2);
gl.glEnd();
gl.glFlush();
gl.glRotatef(rotation,0,0,1);//Set rot to 0
gl.glTranslatef(-x,-y,0);//Do negative to put back
}
public static void drawImage(ImageResource image, float x, float y, float width, float height){
GL2 gl= Renderer.gl;
Texture tex=image.getTexture();
//Check if visible
if(x-width/2-Renderer.cameraX>Renderer.unitsWide/2||
x+width/2-Renderer.cameraX<-Renderer.unitsWide/2||
y-height/2-Renderer.cameraY>Renderer.unitsTall/2||
y+height/2-Renderer.cameraY<-Renderer.unitsTall/2){
return;
}
//Bind the texture
if (tex != null) {
gl.glBindTexture(GL2.GL_TEXTURE_2D,tex.getTextureObject());
}
gl.glTranslatef(x,y,0);
gl.glRotatef(-rotation,0,0,1);
gl.glColor4f(red,green,blue,alpha);
gl.glBegin(GL2.GL_QUADS);
gl.glTexCoord2f(0,1);
gl.glVertex2f(-width/2,-height/2);
gl.glTexCoord2f(1,1);
gl.glVertex2f(width/2,-height/2);
gl.glTexCoord2f(1,0);
gl.glVertex2f(width/2,height/2);
gl.glTexCoord2f(0,0);
gl.glVertex2f(-width/2,height/2);
gl.glEnd();
gl.glFlush();
gl.glBindTexture(GL2.GL_TEXTURE_2D,0);//Unbind texture
gl.glRotatef(rotation,0,0,1);//Set rot to 0
gl.glTranslatef(-x,-y,0);//Do negative to put back
}
public static void setColor(float r, float g, float b, float a){
red=Math.max(0,Math.min(1,r));
green=Math.max(0,Math.min(1,g));
blue=Math.max(0,Math.min(1,b));
alpha=Math.max(0,Math.min(1,a));
}
public static void setRotation(float r){
rotation=r;
}
}
|
package hudson.plugins.buckminster.callables;
import hudson.Functions;
import hudson.remoting.Callable;
import java.io.IOException;
public class GetDirectorExecutable implements Callable<String, IOException>{
/**
*
*/
private static final long serialVersionUID = -15952856176147985L;
public String call() throws IOException {
if(Functions.isWindows())
return "director.bat";
return "director";
}
}
|
package com.yhy.dataservices.service.Impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yhy.dataservices.dao.UserDAO;
import com.yhy.dataservices.dto.UserAccessDTO;
import com.yhy.dataservices.dto.UserDTO;
import com.yhy.dataservices.dto.UserStateDTO;
import com.yhy.dataservices.entity.User;
import com.yhy.dataservices.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Transactional
@Slf4j
public class UserServiceImpl implements UserService {
@Autowired
UserDAO userDAO;
@Override
public Boolean userLogin( HttpSession session,String userName,String passWord) {
UserDTO userDTO = null;
try {
userDTO = userDAO.UserLogin(userName);
} catch (Exception e) {
log.error("{} 登录时,查询用户信息出现异常 {}",getClass(),e.getMessage());
e.printStackTrace();
}
if(userDTO!=null&&passWord.equals(userDTO.getPassWord())){
session.setAttribute("id",userDTO.getId());
session.setAttribute("password",userDTO.getPassWord());
session.setAttribute("loginUser",userDTO.getUserName());
session.setAttribute("role",userDTO.getRole());
return true;
}
return false;
}
@Override
public Boolean changePassWord(Integer id, String passWord) {
boolean flag;
try{
flag=userDAO.changePassWord(id, passWord);
} catch (Exception e) {
log.error("{} 修改密码失败 ",getClass(),e);
throw e;
}
return flag;
}
@Override
public PageInfo<User> getUserList(Integer pageNum, Integer pageSize, String userName) {
List<User> resultList;
//定义初始化的pageSize,pageNum
int pageNum1 = 1;
if(pageNum!=null){ //如果不为空的话改变当前页号
pageNum1 = pageNum;
}
int pageSize1 = 4;
if(pageSize!=null){ //如果不为空的话改变当前页大小
pageSize1 =pageSize ;
}
//开始分页
PageHelper.startPage(pageNum1, pageSize1);
try{
resultList=userDAO.getUserList(userName);
} catch (Exception e) {
log.error("{} 分页查询出现异常 {}",getClass(),e.getMessage());
throw e;
}
PageInfo<User> pageInfo=new PageInfo<>(resultList);
return pageInfo;
}
@Override
public Boolean updateUserState(UserStateDTO userStateDTO) {
boolean flag;
try{
flag=userDAO.updateUserState(userStateDTO.getId(), userStateDTO.getIsAble());
} catch (Exception e) {
log.error("{} 更新用户状态,失败 ",getClass(),e);
throw e;
}
return flag;
}
@Override
public Map<String, Object> addUser(User user) {
Map<String,Object> resultMap=new HashMap<>();
int count=0;
//默认用户状态为可用 1
user.setIsAble(1);
try{
count=userDAO.checkUserName(user.getUsername());
} catch (Exception e) {
log.error("{} 查询用户名,失败 ",getClass(),e);
throw e;
}
//判断用户名是否已使用
if(count>0){
resultMap.put("code",400);
resultMap.put("msg","用户名已使用,请重新填写");
return resultMap;
}
try{
userDAO.addUser(user);
} catch (Exception e) {
log.error("{} 新增用户失败 ",getClass(),e);
throw e;
}
resultMap.put("code",200);
resultMap.put("msg","操作成功");
return resultMap;
}
}
|
package ru.otus.gwt.client.widget;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.uibinder.client.UiTemplate;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import ru.otus.gwt.client.service.LoginServiceAsync;
import ru.otus.gwt.shared.User;
import ru.otus.gwt.shared.exception.WrongCredentialException;
import ru.otus.gwt.shared.validation.ValidationRule;
import javax.validation.ConstraintViolation;
import java.util.Set;
import javax.inject.Inject;
import static ru.otus.gwt.client.gin.ApplicationInjector.INSTANCE;
public class LoginView extends Composite implements IsWidget
{
@UiTemplate("LoginView.ui.xml")
public interface LoginViewUiBinder extends UiBinder<VerticalPanel, LoginView> {
}
@UiField
TextBox loginTextField;
@UiField
PasswordTextBox passwordTextField;
@UiField
HorizontalPanel loginPanel;
@UiField
HorizontalPanel passwordPanel;
private LoginServiceAsync service;
private Image loginInvalidFieldImage, passwordInvalidFieldImage;
@Override
public Widget asWidget()
{
return getWidget();
}
@UiHandler("submit")
void clickHandler(ClickEvent evt)
{
User user = new User(loginTextField.getValue(), passwordTextField.getValue());
Set<ConstraintViolation<User>> errors = ValidationRule.getErrors(user);
clearErrors();
if (errors.isEmpty()) {
service.authorize(user, new AsyncCallback<Void>() {
@Override
public void onFailure(Throwable caught) {
if (caught instanceof WrongCredentialException) {
Window.alert(caught.getLocalizedMessage());
}
}
@Override
public void onSuccess(Void result) {
// UrlBuilder builder = Window.Location.createUrlBuilder().setParameter(queryParam, value);
Window.Location.replace("inside.jsp");
// Window.alert("Вход успешен!");
}
});
}
else {
errors.stream().forEach(e -> {
String propertyName = e.getPropertyPath().toString();
if (propertyName.equals(User.LOGIN)) {
loginInvalidFieldImage = showError(loginTextField, loginPanel, e.getMessage());
}
else if (propertyName.equals(User.PASSWORD)) {
passwordInvalidFieldImage = showError(passwordTextField, passwordPanel, e.getMessage());
}
});
}
}
private static LoginViewUiBinder ourUiBinder = INSTANCE.getLoginViewUiBinder();
@Inject
public LoginView(LoginServiceAsync service) {
initWidget(ourUiBinder.createAndBindUi(this));
this.service = service;
}
public Image showError(TextBox textBox, Panel panel, String error) {
textBox.getElement().getStyle().setBorderColor("red");
final Image fieldInvalidImage = new Image(INSTANCE.getImages().field_invalid());
Style style = fieldInvalidImage.getElement().getStyle();
style.setCursor(Style.Cursor.POINTER);
style.setMargin(6, Style.Unit.PX);
fieldInvalidImage.setTitle(error);
panel.add(fieldInvalidImage);
return fieldInvalidImage;
}
public void clearErrors(){
loginTextField.getElement().getStyle().clearBorderColor();
if (loginInvalidFieldImage != null){
loginInvalidFieldImage.removeFromParent();
}
passwordTextField.getElement().getStyle().clearBorderColor();
if (passwordInvalidFieldImage != null){
passwordInvalidFieldImage.removeFromParent();
}
}
}
|
package com.bakingstreet.ui;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.bakingstreet.R;
import com.bakingstreet.data.Recipe;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
public class IngredientsRecycleViewAdapter extends RecyclerView.Adapter<IngredientsRecycleViewAdapter.IngredientViewHolder> {
private Context mContext;
private List<Recipe.Ingredient> mIngredients;
public IngredientsRecycleViewAdapter(Context context, List<Recipe.Ingredient> ingredients) {
this.mContext = context;
this.mIngredients = ingredients;
}
@NonNull
@Override
public IngredientViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.list_item_ingredients, parent, false);
view.setFocusable(true);
return new IngredientViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull IngredientViewHolder holder, int position) {
updateIngredient(holder, position);
}
private void updateIngredient(IngredientViewHolder holder, int position) {
holder.ingredientInRecycleView.setText(mIngredients.get(position).getIngredient());
holder.quantityInRecycleView.setText(mIngredients.get(position).getQuantity());
holder.measureInRecycleView.setText(mIngredients.get(position).getMeasure());
}
@Override
public int getItemCount() {
if (mIngredients == null) return 0;
else return mIngredients.size();
}
public void setContents(List<Recipe.Ingredient> ingredients) {
if (ingredients != null) mIngredients = ingredients;
if (mIngredients != null) this.notifyDataSetChanged();
}
class IngredientViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.ingredient) TextView ingredientInRecycleView;
@BindView(R.id.quantity) TextView quantityInRecycleView;
@BindView(R.id.measure) TextView measureInRecycleView;
@BindView(R.id.ingredients_recyclerView_item_layout) ConstraintLayout container;
IngredientViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
|
package com.guli.getway.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter(){
CorsConfiguration config=new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOrigin("*");
config.addExposedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**",config);
return new CorsWebFilter(source);
}
}
|
package com.vilio.plms.service.query;
import com.vilio.plms.dao.QueryDao;
import com.vilio.plms.exception.ErrorException;
import com.vilio.plms.glob.Fields;
import com.vilio.plms.service.base.BaseService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
/**
* 类名: Plms100056<br>
* 功能:还款到账详情查询<br>
* 版本: 1.0<br>
* 日期: 2017年8月14日<br>
* 作者: liuzhu.feng<br>
* 版权:vilio<br>
* 说明:<br>
*/
@Service
public class Plms100056 extends BaseService {
private static final Logger logger = Logger.getLogger(Plms100056.class);
@Resource
QueryDao queryDao;
/**
* 参数验证
*
* @param body
*/
public void checkParam(Map<String, Object> body) throws ErrorException {
}
/**
* 主业务流程空实现
*
* @param head
* @param body
*/
@Transactional(propagation = Propagation.REQUIRED,
isolation = Isolation.READ_COMMITTED,
rollbackFor = Exception.class)
public void busiService(Map<String, Object> head, Map<String, Object> body, Map<String, Object> resultMap) throws ErrorException, Exception {
String userNo = body.get(Fields.PARAM_USER_NO) == null ? "" : body.get(Fields.PARAM_USER_NO).toString();
Map receiptsRecord = queryDao.queryReceiptsRecordByReceiptsCode(body);
if(receiptsRecord != null){
String receiptsCode = (String)receiptsRecord.get("receiptsRecordCode");
List fileList = queryDao.queryFileListByReceiptsRecordCode(receiptsCode);
receiptsRecord.put("fileList",fileList);
resultMap.putAll(receiptsRecord);
}
}
}
|
package com.example.demo.service;
import java.util.List;
import com.example.demo.model.Incredient;
public interface IncredientService {
public List<Incredient> findAll();
public Incredient findById(Long theId);
public void save(Incredient theIncredient);
public void deleteById(Long theId);
}
|
package ehb.cp2.bonivert_ludovic.booklibrary;
import ehb.cp2.bonivert_ludovic.books.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
public class LibraryApp {
public static void main(String[] args){
/**
* Start FileStream
*/
try {
//loading the input file(f1) and write to the same file(f2)
File f1 = new File("library.txt");
System.out.println(f1.exists());
File f2 = new File("library2.txt");
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte [] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
//Closing input and output streams
in.close();
out.close();
System.out.println("File is copied");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* **** End of FileStream ***** */
// initialize of the mode field.
// Mode is used to switch between the menu's
char mode = ' ';
// initialize of bookList.
//bookList is used to add and show the list of books in the library
List<Book> bookList = new ArrayList<Book>();
// As long as (do) mode isn't a number between 1 and 3, show menu
do {
System.out.println("*********************");
System.out.println("Choose an action: ");
System.out.println("1. Add a book");
System.out.println("2. Show library");
System.out.println("3. Close application");
System.out.println("*********************");
/**
* The scanner is used to recover the user answer
*/
Scanner sc = new Scanner(System.in);
mode = sc.nextLine().charAt(0);
if (mode != '1' && mode != '2' && mode != '3') {
System.out.println("Please select a number from the menu");
}
if (mode == '1') {
System.out
.println("U have choosen option 1 : Add a book");
System.out
.println("To add a book too the library I need several informations.");
System.out.println("What is the name of the book ?");
String bookName = sc.nextLine();
System.out.println("What is the author of the book ?");
String bookAuthor = sc.nextLine();
System.out.println("What is the email of the author ?");
String bookEmailAuthor = sc.nextLine();
char bookGenderAuthor;
// As long as the user don't enter m(en) or w(oman) ask the user again
do {
System.out
.println("What is the gender of the author ? (m/w)");
bookGenderAuthor = sc.nextLine().charAt(0);
if (bookGenderAuthor != 'm' && bookGenderAuthor != 'w') {
System.out
.println("Please enter m or w");
}
} while (bookGenderAuthor != 'm' && bookGenderAuthor != 'v');
Author author = new Author(bookAuthor, bookEmailAuthor,
bookGenderAuthor);
System.out.println("What is the price of the book ? ");
int bookprice = sc.nextInt();
System.out.println("Are there any in stock ?");
int bookStock = sc.nextInt();
Book book = new Book(bookName, author, bookprice, bookStock);
bookList.add(book);
// make mode empty to return to the menu selection
mode = ' ';
} else if (mode == '2') {
System.out
.println("U have choosen option 2 : Show library");
int size = bookList.size();
for (int i = 0; i < size; i++) {
System.out.println((i + 1) + ". " + bookList.get(i));
}
int bookNumber;
do {
System.out
.println("Please enter the number of the book or 0 to go back to the menu");
bookNumber = sc.nextInt();
if (bookNumber > bookList.size()) {
System.out.println("The number you wrote ( "
+ bookNumber + " ) is not an possible option.");
} else if (bookNumber == 0) {
mode = ' ';
} else {
bookNumber--;
System.out.println("Author: "
+ bookList.get(bookNumber).getAuthor());
System.out.println("Price: ??? "
+ bookList.get(bookNumber).getPrice());
System.out.println("Stock: "
+ bookList.get(bookNumber)
.getNumberInStock());
}
} while (bookNumber >= bookList.size());
// make mode empty to return to the menu selection
mode = ' ';
} else if (mode == '3') {
System.out.println("U have choosen option 3 : Close application");
System.out.println("The application is closing. Good bye !");
}
} while (mode != '1' && mode != '2' && mode != '3');
}
}
|
package com.example.springsecurityjwtdemo.viewmodels;
import java.util.List;
public class UserRegisterViewModel {
private String username;
private String firstName;
private String lastName;
private String employeeId;
private String designation;
private String department;
private String email;
private String phoneNumber;
private String remarks;
private String password;
private List<String> roles;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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 getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
}
|
package org.lvzr.fast.java.patten.create.factoryMethod.mutiltion;
import org.lvzr.fast.java.patten.create.factoryMethod.MailSender;
import org.lvzr.fast.java.patten.create.factoryMethod.Sender;
import org.lvzr.fast.java.patten.create.factoryMethod.SmsSender;
public class SendFactory {
public Sender produceMail() {
return new MailSender();
}
public Sender produceSms() {
return new SmsSender();
}
}
|
/*
* 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 temp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author rafi-iut
*/
public class add_new_teacher extends javax.swing.JFrame {
/**
* Creates new form add_new_teacher
*/
public add_new_teacher() {
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();
tid_f = new javax.swing.JTextField();
tname_f = new javax.swing.JTextField();
tpass_f = new javax.swing.JPasswordField();
repass_f = new javax.swing.JPasswordField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jLabel6 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel1.setText("ADD NEW TEACHER");
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel2.setText("Teacher Id");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel3.setText("Name");
jLabel4.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel4.setText("Password");
jLabel5.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
jLabel5.setText("Retype Password");
tid_f.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
tname_f.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
tpass_f.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
repass_f.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
repass_f.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
repass_fActionPerformed(evt);
}
});
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText("Back");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/temp/teacher7.jpg"))); // NOI18N
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel1)
.addGap(75, 75, 75))
.addGroup(layout.createSequentialGroup()
.addGap(68, 68, 68)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4))
.addGap(53, 53, 53)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(tname_f, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tpass_f, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tid_f, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(repass_f))
.addGroup(layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(102, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(77, 77, 77)
.addComponent(jLabel1)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tid_f, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tname_f, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(tpass_f, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(repass_f, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap(40, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
// TODO add your handling code here:
dispose();
new admin_view().setVisible(true);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
// TODO add your handling code here:
String id,name,pass,re;
id = tid_f.getText();
name = tname_f.getText();
pass = tpass_f.getText();
re = repass_f.getText();
try{
if(id.charAt(0)==' ')id="";
if(name.charAt(0)==' ')name="";
if(pass.charAt(0)==' ')pass="";
if("".equals(id)||"".equals(name)||"".equals(pass))
{
JOptionPane.showMessageDialog(this,"Please enter all required values");
tid_f.setText("");
tname_f.setText("");
tpass_f.setText("");
repass_f.setText("");
}
else {
if(!pass.equals(re)) JOptionPane.showMessageDialog(this,"Password Error");
else{
try
{
Class.forName("oracle.jdbc.OracleDriver");
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","124422");
Statement state = con.createStatement();
String query= String.format("Select teacherid from teacher where teacherid='%s'",id);
ResultSet result=state.executeQuery(query);
int f = 1;
while(result.next())
{
f = 0;
JOptionPane.showMessageDialog(this,"Id already registered");
tid_f.setText("");
tname_f.setText("");
tpass_f.setText("");
repass_f.setText("");
}
result.close();
if(f==1)
{
try{
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","124422");
query= String.format("insert into teacher values('%s','%s','%s')",id,name,pass);
result=state.executeQuery(query);
JOptionPane.showMessageDialog(this,String.format("Id %s is added", id));
tid_f.setText("");
tname_f.setText("");
tpass_f.setText("");
repass_f.setText("");
result.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(this,"error connect in query");
e.printStackTrace();
}
}
}
catch (SQLException e)
{
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(this,"error connect in query");
e.printStackTrace();
}
}
catch(ClassNotFoundException e)
{
JOptionPane.showMessageDialog(this,"error ");
}
}
}
}
catch(StringIndexOutOfBoundsException a)
{
JOptionPane.showMessageDialog(this,"Please enter all required values");
}
}//GEN-LAST:event_jButton1ActionPerformed
private void repass_fActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_repass_fActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_repass_fActionPerformed
/**
* @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(add_new_teacher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(add_new_teacher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(add_new_teacher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(add_new_teacher.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 add_new_teacher().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
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.JPasswordField repass_f;
private javax.swing.JTextField tid_f;
private javax.swing.JTextField tname_f;
private javax.swing.JPasswordField tpass_f;
// End of variables declaration//GEN-END:variables
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.