text
stringlengths
10
2.72M
package com.wy.test.service.impl; import com.wy.test.entity.SysRoleMenu; import com.wy.test.mapper.SysRoleMenuMapper; import com.wy.test.service.SysRoleMenuService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 角色与权限关系表 服务实现类 * </p> * * @author wenyang * @since 2019-12-29 */ @Service public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements SysRoleMenuService { }
package realtime.vo; public class BaiduStockVO { private String name; private String code; private String date; private String time; private Double OpenningPrice; private Double closingPrice; private Double currentPrice; private Double hPrice; private Double lPrice; private Double competitivePrice; private Double auctionPrice; private Double totalNumber; private Double turnover; private Double increase; private Double buyOne; private Double buyOnePrice; private Double buyTwo; private Double buyTwoPrice; private Double buyThree; private Double buyThreePrice; private Double buyFour; private Double buyFourPrice; private Double buyFive; private Double buyFivePrice; private Double sellOne; private Double sellOnePrice; private Double sellTwo; private Double sellTwoPrice; private Double sellThree; private Double sellThreePrice; private Double sellFour; private Double sellFourPrice; private Double sellFive; private Double sellFivePrice; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public Double getOpenningPrice() { return OpenningPrice; } public void setOpenningPrice(Double openningPrice) { OpenningPrice = openningPrice; } public Double getClosingPrice() { return closingPrice; } public void setClosingPrice(Double closingPrice) { this.closingPrice = closingPrice; } public Double getCurrentPrice() { return currentPrice; } public void setCurrentPrice(Double currentPrice) { this.currentPrice = currentPrice; } public Double gethPrice() { return hPrice; } public void sethPrice(Double hPrice) { this.hPrice = hPrice; } public Double getlPrice() { return lPrice; } public void setlPrice(Double lPrice) { this.lPrice = lPrice; } public Double getCompetitivePrice() { return competitivePrice; } public void setCompetitivePrice(Double competitivePrice) { this.competitivePrice = competitivePrice; } public Double getAuctionPrice() { return auctionPrice; } public void setAuctionPrice(Double auctionPrice) { this.auctionPrice = auctionPrice; } public Double getTotalNumber() { return totalNumber; } public void setTotalNumber(Double totalNumber) { this.totalNumber = totalNumber; } public Double getTurnover() { return turnover; } public void setTurnover(Double turnover) { this.turnover = turnover; } public Double getIncrease() { return increase; } public void setIncrease(Double increase) { this.increase = increase; } public Double getBuyOne() { return buyOne; } public void setBuyOne(Double buyOne) { this.buyOne = buyOne; } public Double getBuyOnePrice() { return buyOnePrice; } public void setBuyOnePrice(Double buyOnePrice) { this.buyOnePrice = buyOnePrice; } public Double getBuyTwo() { return buyTwo; } public void setBuyTwo(Double buyTwo) { this.buyTwo = buyTwo; } public Double getBuyTwoPrice() { return buyTwoPrice; } public void setBuyTwoPrice(Double buyTwoPrice) { this.buyTwoPrice = buyTwoPrice; } public Double getBuyThree() { return buyThree; } public void setBuyThree(Double buyThree) { this.buyThree = buyThree; } public Double getBuyThreePrice() { return buyThreePrice; } public void setBuyThreePrice(Double buyThreePrice) { this.buyThreePrice = buyThreePrice; } public Double getBuyFour() { return buyFour; } public void setBuyFour(Double buyFour) { this.buyFour = buyFour; } public Double getBuyFourPrice() { return buyFourPrice; } public void setBuyFourPrice(Double buyFourPrice) { this.buyFourPrice = buyFourPrice; } public Double getBuyFive() { return buyFive; } public void setBuyFive(Double buyFive) { this.buyFive = buyFive; } public Double getBuyFivePrice() { return buyFivePrice; } public void setBuyFivePrice(Double buyFivePrice) { this.buyFivePrice = buyFivePrice; } public Double getSellOne() { return sellOne; } public void setSellOne(Double sellOne) { this.sellOne = sellOne; } public Double getSellOnePrice() { return sellOnePrice; } public void setSellOnePrice(Double sellOnePrice) { this.sellOnePrice = sellOnePrice; } public Double getSellTwo() { return sellTwo; } public void setSellTwo(Double sellTwo) { this.sellTwo = sellTwo; } public Double getSellTwoPrice() { return sellTwoPrice; } public void setSellTwoPrice(Double sellTwoPrice) { this.sellTwoPrice = sellTwoPrice; } public Double getSellThree() { return sellThree; } public void setSellThree(Double sellThree) { this.sellThree = sellThree; } public Double getSellThreePrice() { return sellThreePrice; } public void setSellThreePrice(Double sellThreePrice) { this.sellThreePrice = sellThreePrice; } public Double getSellFour() { return sellFour; } public void setSellFour(Double sellFour) { this.sellFour = sellFour; } public Double getSellFourPrice() { return sellFourPrice; } public void setSellFourPrice(Double sellFourPrice) { this.sellFourPrice = sellFourPrice; } public Double getSellFive() { return sellFive; } public void setSellFive(Double sellFive) { this.sellFive = sellFive; } public Double getSellFivePrice() { return sellFivePrice; } public void setSellFivePrice(Double sellFivePrice) { this.sellFivePrice = sellFivePrice; } }
package Vorlesung05; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; //<T> Funktioniert für Objekte vom Typen T public class SerializationHelper<T> { private String path; public SerializationHelper(String path) { this.path = path; } public void Save(T o) throws IOException { FileOutputStream fos = new FileOutputStream(this.path); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(o); oos.flush(); oos.close(); fos.close(); } public T Load() throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream(this.path); ObjectInputStream ois = new ObjectInputStream(fis); T result = (T) ois.readObject(); ois.close(); fis.close(); return result; } }
package br.assembleia.service.impl; import br.assembleia.dao.EmprestimoDAO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import br.assembleia.entidades.Emprestimo; import br.assembleia.service.EmprestimoService; import java.util.List; @Service @Transactional public class EmprestimoServiceImpl implements EmprestimoService { @Autowired private EmprestimoDAO dao; @Override public void salvar(Emprestimo emprestimo) throws IllegalArgumentException { dao.salvar(emprestimo); } @Override public List<Emprestimo> listarTodos() { return dao.listarTodos(); } @Override public void editar(Emprestimo emprestimo) { dao.editar(emprestimo); } @Override public void deletar(Emprestimo emprestimo) { dao.deletar(emprestimo); } @Override public Emprestimo getById(Long id) { return dao.getById(id); } }
package edu.oleg088097.arkanoid.util; import android.graphics.Color; import java.util.ArrayList; import java.util.Random; public class Utils { static private final Random rand = new Random(); static public ArrayList<Integer> generateColors(){ ArrayList<Integer> colors = new ArrayList<>(125); int baseR = 255; int baseG = 255; int baseB = 255; int divisor = (int)Math.cbrt(30) + 1; int stepR = (baseR) / divisor; int stepG = (baseG) / divisor; int stepB = (baseB) / divisor; for(int r = 0; r <= baseR ; r += stepR) { for(int g = 0; g <= baseG ; g += stepG) { for(int b = 0; b <= baseB ; b += stepB) { colors.add(Color.argb(255,r,g,b)); } } } return colors; } static public int random(int bound){ return rand.nextInt(bound); } public interface ArithmeticInterface { float operation(float a, float b); } static public class Plus implements ArithmeticInterface { @Override public float operation(float a, float b) { return a+b; } } static public class Minus implements ArithmeticInterface { @Override public float operation(float a, float b) { return a-b; } } }
package org.shazhi.businessEnglishMicroCourse.controller; import org.shazhi.businessEnglishMicroCourse.entity.ContactsEntity; import org.shazhi.businessEnglishMicroCourse.entity.MessageEntity; import org.shazhi.businessEnglishMicroCourse.service.MessageService; import org.shazhi.businessEnglishMicroCourse.util.Result; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("message") public class MessageController { final MessageService messageService; public MessageController(MessageService messageService) { this.messageService = messageService; } @RequestMapping("load") public List<MessageEntity> loadMessage(@RequestBody MessageEntity message){ return messageService.load(message); } @RequestMapping("history") public List<MessageEntity> history(@RequestBody MessageEntity history){ return messageService.loadHistory(history); } @RequestMapping("last") public MessageEntity last(@RequestBody MessageEntity last){ return messageService.loadLastMessage(last); } @RequestMapping("send") public Result sendMessage(@RequestBody MessageEntity messageEntity){ return messageService.sendMessage(messageEntity); } @RequestMapping("markRead") public Result markRead(@RequestBody MessageEntity mess){ return messageService.markRead(mess); } @RequestMapping("contactors") public List<ContactsEntity> loadContactors(@RequestBody ContactsEntity con){ return messageService.loadContactors(con); } @RequestMapping("contactors/{operate}") public Result updateContactor(@RequestBody ContactsEntity contactsEntity,@PathVariable String operate){ return messageService.updateContactor(contactsEntity,operate); } }
package com.bfwg.repository; import com.bfwg.model.Account; import com.bfwg.model.Transaction; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional public interface TransactionRepo extends PagingAndSortingRepository<Transaction, Long>, JpaSpecificationExecutor<Transaction> { List<Transaction> findByAccountAndAccountUserUsername(Account account, String username, Pageable pageRequest); int countByAccount(Account account); }
package com.jushu.video.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import java.io.Serializable; import java.time.LocalDate; /** * <p> * * </p> * * @author chen * @since 2020-01-08 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class MovieSearch implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 演员列表,多个用|隔开 */ private String actors; /** * 国家 */ private String country; /** * 导演,多个用|隔开 */ private String director; /** * 封面图 */ @TableField("imgUrl") private String imgUrl; /** * 是否完结 */ @TableField("isOver") private Boolean isOver; /** * 影片来源 */ @TableField("movieSource") private String movieSource; /** * 影片类型 */ @TableField("movieType") private String movieType; /** * 影片名称 */ private String name; /** * 爬数据时候用的不用管 */ @TableField("pageId") private String pageId; /** * 详情页 */ @TableField("pageUrl") private String pageUrl; /** * 描述 */ private String reviews; /** * 评分 */ private String score; /** * 更新状态描述 */ @TableField("statusText") private String statusText; /** * 标签,多个用|隔开 */ private String tags; /** * 年份 */ private String year; /** * 爬数据时候用的不用管 */ @TableField("lastRefreshDate") private LocalDate lastRefreshDate; }
package com.example.i_donate.DataModels; import java.util.Date; public class RequestDataModel { private String details; private Date date; private String phone; RequestDataModel(){} public RequestDataModel(String details,Date date, String phone) { this.details = details; this.date = date; this.phone = phone; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } }
/* * 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.controller; import com.entity.Cliente; import com.entity.CodigoSesion; import com.entity.Comentario; import com.entity.Mora; import com.entity.Tienda; import com.services.ClienteServices; import com.services.CodigoServices; import com.services.ComentarioServices; import com.services.MoraServices; import java.io.Serializable; import java.util.ArrayList; import java.util.Properties; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import net.bootsfaces.utils.FacesMessages; import org.apache.commons.lang.StringEscapeUtils; import org.primefaces.push.EventBus; import org.primefaces.push.EventBusFactory; /** * * @author DAC-PC */ @ManagedBean @SessionScoped public class ClienteBean implements Serializable{ private Cliente cliente= new Cliente(); private ArrayList<Cliente> listacliente=new ArrayList<>(); private ArrayList<Comentario> listacomentario = new ArrayList<>(); private Comentario comentario= new Comentario(); ClienteServices clienteserv= new ClienteServices(); CodigoServices codservicesv = new CodigoServices(); ComentarioServices comentarioserv = new ComentarioServices(); private CodigoSesion codsesion = new CodigoSesion(); TiendaBean tb = new TiendaBean(); private boolean tabla = true; private boolean row = false; private boolean text = false; private boolean textcodigo= false; private boolean btnop=true; private int numero =0; private boolean vermensaje = false; private boolean vercomentarios = true; private String enviarcomentario; private boolean mostrarcatalogo = true; private boolean mostrardetalle_catalogo = false; private Cliente Clienteregistrar = new Cliente(); private boolean clienteregistrado =false; public TiendaBean getTb() { return tb; } public void setTb(TiendaBean tb) { this.tb = tb; } public ClienteBean() { listar(); listarcomentarios(); } public static void send(String to, String sub,String msg) { FacesMessage ms; final String user="tiendaspa2015@hotmail.com"; final String pass="Proyectodeaula12345"; Properties props = new Properties(); //gmail: smtp.gmail.com //hotmail props.put("mail.smtp.host", "smtp.live.com"); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); Session session = Session.getDefaultInstance(props,new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pass); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(user)); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); message.setSubject(sub); message.setText(msg); Transport.send(message); FacesMessages.info("Mensaje enviado"); } catch (MessagingException e) { FacesMessages.error("No se ha podido enviar Mensaje"); throw new RuntimeException(e); } } public void habilitarcodigo(){ setText(true); setTextcodigo(true); setBtnop(false); } public String style(){ String estilo; if(getListacomentario().size() > 0){ estilo= "background-color: red"; }else{ estilo= "background-color: green"; } return estilo; } public void leerIDcomentario(Long id){ setComentario(comentarioserv.vercomentario(id)); setVermensaje(true); setVercomentarios(false); } public void registrar(){ if(getClienteregistrar().getNombre().trim().equals("") || getClienteregistrar().getApellido().trim().equals("") || getClienteregistrar().getCedula().trim().equals("") || getClienteregistrar().getDireccion().trim().equals("") || getClienteregistrar().getCorreo().trim().equals("") ){ FacesMessages.error("Por favor rellene todos los campos"); setClienteregistrar(new Cliente()); }else{ MoraServices moraserv = new MoraServices(); Boolean moroso = false; ArrayList<Mora> listamorosos = (ArrayList<Mora>) moraserv.consultarTodo(Mora.class); for(int i =0; i < listamorosos.size(); i++){ if(listamorosos.get(i).getCliente().getCedula().equals(getClienteregistrar().getCedula())){ moroso = true; FacesMessages.fatal("El cliente que intenta registrar se encuentra en la lista de morosos!"); } } if(moroso == false){ try { Thread.sleep(2000); } catch (Exception e) { } getClienteregistrar().setTienda(Obtenertienda()); getClienteregistrar().setEstado(true); clienteserv.crear(getClienteregistrar()); setClienteregistrado(true); FacesMessages.info("Registro exitoso!"); listar(); setClienteregistrar(new Cliente()); } setClienteregistrar(new Cliente()); } } public void ocultarpanel(){ setClienteregistrado(false); } public void notificarPUSH() { String summary = "Nuevo Elemento"; String detail = "Se agrego a la lista"; String CHANNEL = "/notify"; EventBus eventBus = EventBusFactory.getDefault().eventBus(); eventBus.publish(CHANNEL, new FacesMessage(StringEscapeUtils.escapeHtml(summary), StringEscapeUtils.escapeHtml(detail))); } public void respondercliente(){ Tienda t = Obtenertienda(); send(getComentario().getCliente().getCorreo(), t.getNombretienda(), getEnviarcomentario()); setVermensaje(false); setVercomentarios(true); comentarioserv.eliminar(getComentario()); setEnviarcomentario(""); listarcomentarios(); } public Tienda Obtenertienda(){ Tienda p= (Tienda) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("tienda"); return p; } public void listar(){ setListacliente((ArrayList<Cliente>) clienteserv.listarcliente(Obtenertienda())); } public void listarcomentarios(){ setListacomentario((ArrayList<Comentario>) comentarioserv.listarcomentario(Obtenertienda()) ); setNumero(listacomentario.size()); } public void resetcoment(){ setNumero(0); } public void leerID(Long id){ setCliente(clienteserv.vercliente(id)); FacesMessages.info(getCliente().getNombre()); } public void refresh(){ setListacomentario((ArrayList<Comentario>) comentarioserv.listarcomentario(Obtenertienda()) ); setNumero(listacomentario.size()); } public void limpiar(){ setCliente(new Cliente()); } public void ocultartabla(){ setTabla(false); setRow(true); } public void mostrartabla(){ setCliente(new Cliente()); setTabla(true); setRow(false); setText(false); setTextcodigo(false); setBtnop(true); } public void modificar(){ clienteserv.modificar(getCliente()); setRow(false); setTabla(true); setListacliente((ArrayList<Cliente>) clienteserv.listarcliente(Obtenertienda())); setCliente(new Cliente()); } public void eliminar(){ getCliente().setEstado(false); clienteserv.modificar(getCliente()); setRow(false); setTabla(true); setListacliente((ArrayList<Cliente>) clienteserv.listarcliente(Obtenertienda())); setCliente(new Cliente()); } public void guardarCodigo(){ getCodsesion().setCliente(getCliente()); codservicesv.crear(getCodsesion()); send(getCodsesion().getCliente().getCorreo(), "CODIGO REGISTRO", getCodsesion().getCod()); setText(false); setTextcodigo(false); setBtnop(true); } public void eliminarcomentario(){ comentarioserv.eliminar(getComentario()); listarcomentarios(); } /** * @return the cliente */ public Cliente getCliente() { return cliente; } /** * @param cliente the cliente to set */ public void setCliente(Cliente cliente) { this.cliente = cliente; } /** * @return the listacliente */ public ArrayList<Cliente> getListacliente() { return listacliente; } /** * @param listacliente the listacliente to set */ public void setListacliente(ArrayList<Cliente> listacliente) { this.listacliente = listacliente; } public boolean isTabla() { return tabla; } public void setTabla(boolean tabla) { this.tabla = tabla; } public boolean isRow() { return row; } public void setRow(boolean row) { this.row = row; } public boolean isText() { return text; } public void setText(boolean text) { this.text = text; } public boolean isTextcodigo() { return textcodigo; } public void setTextcodigo(boolean textcodigo) { this.textcodigo = textcodigo; } public boolean isBtnop() { return btnop; } public void setBtnop(boolean btnop) { this.btnop = btnop; } public CodigoSesion getCodsesion() { return codsesion; } public void setCodsesion(CodigoSesion codsesion) { this.codsesion = codsesion; } public ArrayList<Comentario> getListacomentario() { return listacomentario; } public void setListacomentario(ArrayList<Comentario> listacomentario) { this.listacomentario = listacomentario; } public Comentario getComentario() { return comentario; } public void setComentario(Comentario comentario) { this.comentario = comentario; } public int getNumero() { return numero; } public void setNumero(int numero) { this.numero = numero; } public boolean isVermensaje() { return vermensaje; } public void setVermensaje(boolean vermensaje) { this.vermensaje = vermensaje; } public boolean isVercomentarios() { return vercomentarios; } public void setVercomentarios(boolean vercomentarios) { this.vercomentarios = vercomentarios; } public String getEnviarcomentario() { return enviarcomentario; } public void setEnviarcomentario(String enviarcomentario) { this.enviarcomentario = enviarcomentario; } public Cliente getClienteregistrar() { return Clienteregistrar; } public void setClienteregistrar(Cliente Clienteregistrar) { this.Clienteregistrar = Clienteregistrar; } public boolean isClienteregistrado() { return clienteregistrado; } public void setClienteregistrado(boolean clienteregistrado) { this.clienteregistrado = clienteregistrado; } }
package menu; import java.awt.Color; import java.awt.Font; import java.awt.Point; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.table.DefaultTableModel; import listener.CalibrationListener; import util.CurveFitter; import util.DataManager; import util.Enums.CalibrationType; import util.Enums.ColorMode; import calibration.EfficiencyCalibration; import calibration.EnergyCalibration; import filter.effFilter; import filter.nrgFilter; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Joachim */ public class EfficiencyCalibrationMenu extends SubMenu { /** * */ private static final long serialVersionUID = 1L; private ArrayList<CalibrationListener> calibrationListeners = new ArrayList<CalibrationListener>(); private DataState dataState; private JFileChooser fileChooser = new JFileChooser(); private boolean calibrated = false; private boolean exported = false; /** * Creates new form EnergyCalibrationMenu */ public EfficiencyCalibrationMenu() { initComponents(); efficiencyCalibrationSpectrum.addLayer(); channelInputField.setPreferredSize(channelInputField.getSize()); channelInputField.setText(""); efficiencyInputField.setPreferredSize(efficiencyInputField.getSize()); efficiencyInputField.setText(""); polyFitOrderInput.setPreferredSize(polyFitOrderInput.getSize()); polyFitOrderInput.setText(""); statusLabel.setText(""); setResizable(false); setTitle("Efficiency Calibration Menu"); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); dataState = new DataState(); efficiencyCalibrationSpectrum.setXLabel("Channel"); efficiencyCalibrationSpectrum.setYLabel("Efficiency [%]"); // Sets the current directory to the calibration-files/background folder // in the root directory fileChooser.setCurrentDirectory(new File("./calibration-files/efficiency")); } public void restore(EfficiencyCalibration calib, String path, int order) { if (!path.equals("")) { ArrayList<StringPair> tableData = DataManager.readEffFile(path); if (tableData == null) { return; } setTableData(tableData); dataState.path_cur = path; dataState.path_act = path; dataState.path_def = path; defaultCheckBox.setSelected(true); polyFitOrderInput.setText("" + order); calibrateButtonActionPerformed(null); exported = true; statusLabel.setForeground(getColor(ColorMode.GREEN)); statusLabel.setText("Calibration Active."); String calibrationEquation = "E = "; for (int i = 0; i < calib.coefficients.size() - 1; i++) { calibrationEquation += calib.coefficients.get(i) + " * ch" + " ^ " + i + " + "; } calibrationEquation += calib.coefficients.get(calib.coefficients.size() - 1) + " * ch" + " ^ " + (calib.coefficients.size() - 1); calibrationEquationTextPane.setText(calibrationEquation); dataState.order_cur = "" + order; dataState.order_act = "" + order; okButtonActionPerformed(null); } } /** * 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"> private void initComponents() { jFormattedTextField1 = new javax.swing.JFormattedTextField(); addButton = new javax.swing.JButton(); deleteButton = new javax.swing.JButton(); changeButton = new javax.swing.JButton(); clearButton = new javax.swing.JButton(); calibrateButton = new javax.swing.JButton(); cancelButton = new javax.swing.JButton(); polyFitOrderInput = new javax.swing.JTextField(); polyFitOrderLabel = new javax.swing.JLabel(); statusLabel = new javax.swing.JLabel(); efficiencyCalibrationSpectrum = new PlotWindow(); calibEquationLabel = new javax.swing.JLabel(); jScrollPane2 = new javax.swing.JScrollPane(); calibrationEquationTextPane = new javax.swing.JTextPane(); jScrollPane3 = new javax.swing.JScrollPane(); calibrationTable = new javax.swing.JTable(); channelInputField = new javax.swing.JTextField(); channelInputLabel = new javax.swing.JLabel(); efficiencyInputLabel = new javax.swing.JLabel(); efficiencyInputField = new javax.swing.JTextField(); defaultCheckBox = new javax.swing.JCheckBox(); okButton = new javax.swing.JButton(); jSeparator3 = new javax.swing.JSeparator(); jSeparator4 = new javax.swing.JSeparator(); importButton = new javax.swing.JButton(); importLabel = new javax.swing.JLabel(); exportButton = new javax.swing.JButton(); exportLabel = new javax.swing.JLabel(); jSeparator2 = new javax.swing.JSeparator(); jSeparator1 = new javax.swing.JSeparator(); jFormattedTextField1.setText("jFormattedTextField1"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addButton.setText("Add"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); deleteButton.setText("Delete"); deleteButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { deleteButtonActionPerformed(evt); } }); changeButton.setText("Change"); changeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { changeButtonActionPerformed(evt); } }); clearButton.setText("Clear"); clearButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearButtonActionPerformed(evt); } }); calibrateButton.setText("Calibrate"); calibrateButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { calibrateButtonActionPerformed(evt); } }); cancelButton.setText("Cancel"); cancelButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cancelButtonActionPerformed(evt); } }); polyFitOrderInput.setText("jTextField3"); polyFitOrderLabel.setText("Polynomial Fit Order:"); statusLabel.setText("jLabel6"); javax.swing.GroupLayout energyCalibrationSpectrumLayout = new javax.swing.GroupLayout(efficiencyCalibrationSpectrum); efficiencyCalibrationSpectrum.setLayout(energyCalibrationSpectrumLayout); energyCalibrationSpectrumLayout.setHorizontalGroup(energyCalibrationSpectrumLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 640, Short.MAX_VALUE)); energyCalibrationSpectrumLayout.setVerticalGroup(energyCalibrationSpectrumLayout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 360, Short.MAX_VALUE)); calibEquationLabel.setText("Calibration equation:"); jScrollPane2.setViewportView(calibrationEquationTextPane); calibrationTable.getTableHeader().setFont(new Font("SansSerif", Font.PLAIN, 11)); calibrationTable.setModel(new javax.swing.table.DefaultTableModel(new Object[][] { }, new String[] { "Channel", "Efficiency [%]" }) { Class[] types = new Class[] { java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean[] { false, false }; public Class getColumnClass(int columnIndex) { return types[columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); jScrollPane3.setViewportView(calibrationTable); if (calibrationTable.getColumnModel().getColumnCount() > 0) { calibrationTable.getColumnModel().getColumn(0).setResizable(false); calibrationTable.getColumnModel().getColumn(1).setResizable(false); } channelInputField.setText("jTextField1"); channelInputLabel.setText("Channel:"); efficiencyInputLabel.setText("Efficiency [%]:"); efficiencyInputField.setText("jTextField2"); defaultCheckBox.setText("Use As Default Calibration"); defaultCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { defaultCheckBoxActionPerformed(evt); } }); okButton.setText("Ok"); okButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { okButtonActionPerformed(evt); } }); importButton.setText("Import..."); importButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { importButtonActionPerformed(evt); } }); importLabel.setText("Import Calibration"); exportButton.setText("Export..."); exportButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportButtonActionPerformed(evt); } }); exportLabel.setText("Export Calibration"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addContainerGap() .addGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup( layout.createSequentialGroup().addComponent(calibEquationLabel) .addGap(18, 18, 18).addComponent(statusLabel)) .addGroup( layout.createSequentialGroup().addComponent(okButton) .addGap(18, 18, 18).addComponent(cancelButton)) .addGroup( layout.createSequentialGroup() .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 163, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup( layout.createSequentialGroup() .addComponent( polyFitOrderLabel) .addGap(10, 10, 10) .addComponent( polyFitOrderInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent( deleteButton, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( clearButton, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( changeButton) .addComponent( addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( efficiencyInputLabel, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent( channelInputLabel, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( channelInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( efficiencyInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent( jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( importLabel) .addComponent( importButton)) .addGap(60, 60, 60) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( exportButton) .addComponent( exportLabel))) .addComponent( jSeparator4, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSeparator2) .addComponent(defaultCheckBox) .addComponent(calibrateButton) .addComponent(jSeparator1)) .addGap(18, 18, 18) .addComponent(efficiencyCalibrationSpectrum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane2)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); layout.setVerticalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addContainerGap() .addGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addGroup( layout.createSequentialGroup() .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addComponent( importLabel) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( importButton)) .addGroup( layout.createSequentialGroup() .addComponent( exportLabel) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( exportButton))) .addGap(18, 18, 18) .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addComponent(addButton) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( changeButton)) .addGroup( layout.createSequentialGroup() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent( channelInputLabel) .addComponent( channelInputField, 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( efficiencyInputLabel) .addComponent( efficiencyInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(deleteButton) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(clearButton) .addGap(18, 18, 18) .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(polyFitOrderLabel) .addComponent( polyFitOrderInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(defaultCheckBox) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(calibrateButton)) .addComponent(efficiencyCalibrationSpectrum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(calibEquationLabel).addComponent(statusLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(okButton).addComponent(cancelButton)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); pack(); }// </editor-fold> private void setTableData(ArrayList<StringPair> data) { DefaultTableModel model = (DefaultTableModel) calibrationTable.getModel(); model.setRowCount(0); for (int i = 0; i < data.size(); i++) { model.addRow(new String[] { data.get(i).string1, data.get(i).string2 }); } dataState.tablebData_cur = data; } private void addButtonActionPerformed(java.awt.event.ActionEvent evt) { statusLabel.setText(""); String channel = channelInputField.getText(); String energy = efficiencyInputField.getText(); if (checkValidInput(channel, energy)) { if (!checkDuplicateInput(channel, energy)) { DefaultTableModel model = (DefaultTableModel) calibrationTable.getModel(); model.addRow(new String[] { channel, energy }); dataState.tablebData_cur.add(new StringPair(channel, energy)); channelInputField.setText(""); efficiencyInputField.setText(""); } } calibrationEquationTextPane.setText(""); sortTableData(); calibrated = false; } private void sortTableData() { int length = calibrationTable.getRowCount(); ArrayList<StringPair> tableData = new ArrayList<StringPair>(); for (int i = 0; i < length; i++) { tableData.add(new StringPair((String) calibrationTable.getValueAt(i, 0), (String) calibrationTable .getValueAt(i, 1))); } Collections.sort(tableData, new Comparator<StringPair>() { public int compare(StringPair o1, StringPair o2) { return Integer.compare(Integer.parseInt(o1.string1), Integer.parseInt(o2.string1)); } }); setTableData(tableData); } private boolean checkDuplicateInput(String channel, String energy) { DefaultTableModel model = (DefaultTableModel) calibrationTable.getModel(); for (int i = 0; i < model.getRowCount(); i++) { if (calibrationTable.getValueAt(i, 0).equals(channel)) { statusLabel.setForeground(Color.RED); statusLabel.setText("Channel value already used!"); return true; } } for (int i = 0; i < model.getRowCount(); i++) { if (calibrationTable.getValueAt(i, 1).equals(energy)) { statusLabel.setForeground(Color.RED); statusLabel.setText("Energy value already used!"); return true; } } return false; } private boolean checkValidInput(String channel, String energy) { try { Integer.parseInt(channel); } catch (Exception e) { statusLabel.setForeground(Color.RED); statusLabel.setText("Enter a valid channel"); return false; } try { Double.parseDouble(energy); } catch (Exception e) { statusLabel.setForeground(Color.RED); statusLabel.setText("Enter a valid energy [keV]"); return false; } if (Integer.parseInt(channel) < 0) { statusLabel.setForeground(Color.RED); statusLabel.setText("Enter a channel > 0"); return false; } if (Double.parseDouble(energy) < 0) { statusLabel.setForeground(Color.RED); statusLabel.setText("Enter an energy > 0"); return false; } return true; } private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) { statusLabel.setText(""); if (calibrationTable.getSelectedRow() < 0) { statusLabel.setForeground(Color.RED); statusLabel.setText("Select a row before deleting"); } else { DefaultTableModel model = (DefaultTableModel) calibrationTable.getModel(); String channel = (String) model.getValueAt(calibrationTable.getSelectedRow(), 0); String energy = (String) model.getValueAt(calibrationTable.getSelectedRow(), 1); model.removeRow(calibrationTable.getSelectedRow()); dataState.tablebData_act.remove(new Point(Integer.parseInt(channel), Integer.parseInt(energy))); } calibrationEquationTextPane.setText(""); calibrated = false; } private void changeButtonActionPerformed(java.awt.event.ActionEvent evt) { statusLabel.setText(""); if (calibrationTable.getSelectedRow() < 0) { statusLabel.setForeground(Color.RED); statusLabel.setText("Select a row before changing"); return; } String channel = channelInputField.getText(); String energy = efficiencyInputField.getText(); if (checkValidInput(channel, energy)) { DefaultTableModel model = (DefaultTableModel) calibrationTable.getModel(); model.setValueAt(-1, calibrationTable.getSelectedRow(), 0); model.setValueAt(-1, calibrationTable.getSelectedRow(), 1); if (!checkDuplicateInput(channel, energy)) { model.setValueAt(channel, calibrationTable.getSelectedRow(), 0); model.setValueAt(energy, calibrationTable.getSelectedRow(), 1); dataState.tablebData_cur.set(calibrationTable.getSelectedRow(), new StringPair(channel, energy)); channelInputField.setText(""); efficiencyInputField.setText(""); } } calibrationEquationTextPane.setText(""); calibrated = false; } private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) { calibrationEquationTextPane.setText(""); dataState.tablebData_cur = new ArrayList<StringPair>(); setTableData(dataState.tablebData_cur); calibrated = false; } private void calibrateButtonActionPerformed(java.awt.event.ActionEvent evt) { statusLabel.setText(""); try { Integer.parseInt(polyFitOrderInput.getText()); } catch (Exception e) { statusLabel.setForeground(Color.RED); statusLabel.setText("Enter a valid polynomial fit order"); return; } if (calibrationTable.getRowCount() < 2) { statusLabel.setForeground(Color.RED); statusLabel.setText("Enter at least two calibration points"); return; } ArrayList<Double> dataX = new ArrayList<Double>(); ArrayList<Double> dataY = new ArrayList<Double>(); DefaultTableModel model = (DefaultTableModel) calibrationTable.getModel(); for (int i = 0; i < model.getRowCount(); i++) { dataX.add((double) Integer.parseInt((String) calibrationTable.getValueAt(i, 0))); } for (int i = 0; i < model.getRowCount(); i++) { dataY.add(Double.parseDouble((String) calibrationTable.getValueAt(i, 1))); } int order = Integer.parseInt(polyFitOrderInput.getText()); ArrayList<Double> coeff = CurveFitter.curveFit(dataX, dataY, order); dataState.calibration_cur = new EfficiencyCalibration(coeff, order); drawCalibration(true); String calibrationEquation = "E = "; for (int i = 0; i < coeff.size() - 1; i++) { calibrationEquation += coeff.get(i) + " * ch" + " ^ " + i + " + "; } calibrationEquation += coeff.get(coeff.size() - 1) + " * ch" + " ^ " + (coeff.size() - 1); calibrationEquationTextPane.setText(calibrationEquation); dataState.calibEquation_cur = calibrationEquation; if (exported) { statusLabel.setForeground(getColor(ColorMode.GREEN)); statusLabel.setText("Calibration Complete. Press Ok To Active Calibration"); } else { statusLabel.setText("Calibration Complete. Export The Calibration To Continue."); } calibrated = true; } private Color getColor(ColorMode colorMode) { switch (colorMode) { case RED: return Color.red; case BLACK: return Color.black; case WHITE: return Color.white; case YELLOW: return Color.yellow; case GREEN: return new Color(0, 100, 0); case MAGENTA: return Color.magenta; case CYAN: return Color.cyan; case BLUE: return Color.blue; default: return Color.yellow; } } private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) { setVisible(false); restoreState(); } private void defaultCheckBoxActionPerformed(java.awt.event.ActionEvent evt) { } private void importButtonActionPerformed(java.awt.event.ActionEvent evt) { fileChooser.setFileFilter(new effFilter()); statusLabel.setText(""); int returnVal = fileChooser.showOpenDialog(this); String chosenPath = null; if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) { chosenPath = fileChooser.getSelectedFile().getAbsolutePath(); } ArrayList<StringPair> tableData = DataManager.readNrgFile(chosenPath); if (tableData == null) { return; } setTableData(tableData); dataState.path_cur = chosenPath; calibrationEquationTextPane.setText(""); calibrated = false; exported = true; } private void exportButtonActionPerformed(java.awt.event.ActionEvent evt) { if (!calibrated) { statusLabel.setForeground(getColor(ColorMode.RED)); statusLabel.setText("Use The \"Calibrate\" Button Before Exporting"); return; } fileChooser.setFileFilter(new effFilter()); int returnVal = fileChooser.showSaveDialog(this); String path = null; if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) { path = fileChooser.getSelectedFile().getAbsolutePath(); } else { System.out.println("File access cancelled by user."); } DataManager.exportNrgFile(path, dataState.tablebData_cur); dataState.path_cur = path; exported = true; statusLabel.setForeground(getColor(ColorMode.GREEN)); statusLabel.setText("Calibration Exported. Press Ok To Active Calibration"); } private void okButtonActionPerformed(java.awt.event.ActionEvent evt) { if (calibrated) { if (!exported) { statusLabel.setForeground(getColor(ColorMode.RED)); statusLabel.setText("Use The \"Export\" Button Before Saving"); return; } setVisible(false); saveState(); if (defaultCheckBox.isSelected()) { notifyCalibrationListeners(dataState.calibration_act, dataState.path_act, true); } else { notifyCalibrationListeners(dataState.calibration_act, dataState.path_act, false); } } else { statusLabel.setForeground(getColor(ColorMode.RED)); statusLabel.setText("Use The \"Calibrate\" Button Before Saving"); } } @Override protected void restoreState() { if (dataState.tablebData_act != null) { setTableData(dataState.tablebData_act); dataState.tablebData_cur = dataState.tablebData_act; calibrationEquationTextPane.setText(dataState.calibEquation_act); dataState.calibEquation_cur = dataState.calibEquation_act; statusLabel.setText(""); if (dataState.defautCalib) { defaultCheckBox.setSelected(true); } else { defaultCheckBox.setSelected(false); } dataState.order_cur = dataState.order_act; polyFitOrderInput.setText(dataState.order_act); drawCalibration(false); } } @Override protected void saveState() { setTableData(dataState.tablebData_cur); dataState.tablebData_act = dataState.tablebData_cur; calibrationEquationTextPane.setText(dataState.calibEquation_cur); dataState.calibEquation_act = dataState.calibEquation_cur; statusLabel.setText(""); dataState.calibration_act = dataState.calibration_cur; if (defaultCheckBox.isSelected()) { dataState.defautCalib = true; } dataState.path_act = dataState.path_cur; if (defaultCheckBox.isSelected()) { dataState.path_def = dataState.path_cur; } statusLabel.setForeground(getColor(ColorMode.GREEN)); statusLabel.setText("Calibration Active."); } private void drawCalibration(boolean current) { ArrayList<Double> coeff = null; ArrayList<StringPair> tableData = null; if (current) { coeff = dataState.calibration_cur.coefficients; tableData = dataState.tablebData_cur; } else { try { coeff = dataState.calibration_act.coefficients; tableData = dataState.tablebData_act; } catch (Exception e) { efficiencyCalibrationSpectrum.clear(); return; } } ArrayList<Double> calibY = new ArrayList<Double>(); ArrayList<Double> calibX = new ArrayList<Double>(); for (int i = 0; i < 4096; i++) { double y = 0; for (int j = 0; j < coeff.size(); j++) { y += coeff.get(j) * Math.pow(i, j); } calibX.add((double) i); calibY.add(y); } ArrayList<Double> dataX = new ArrayList<Double>(); ArrayList<Double> dataY = new ArrayList<Double>(); for (int i = 0; i < tableData.size(); i++) { dataX.add(Double.parseDouble(tableData.get(i).string1)); dataY.add(Double.parseDouble(tableData.get(i).string2)); } efficiencyCalibrationSpectrum.setScaleByData(calibX, calibY); efficiencyCalibrationSpectrum.drawOnLayer(calibX, calibY, 0, ColorMode.RED, 1, 1); efficiencyCalibrationSpectrum.drawOnLayer(dataX, dataY, 1, ColorMode.CYAN, 3, 3); } public void addCalibrationListener(CalibrationListener listener) { calibrationListeners.add(listener); } private void notifyCalibrationListeners(EfficiencyCalibration calib, String path, boolean defaultCalibration) { for (CalibrationListener listener : calibrationListeners) { listener.calibrationEvent(calib, CalibrationType.EFFICIENCY, path, defaultCalibration); } } // Variables declaration - do not modify private javax.swing.JButton addButton; private javax.swing.JLabel calibEquationLabel; private javax.swing.JButton calibrateButton; private javax.swing.JTextPane calibrationEquationTextPane; private javax.swing.JTable calibrationTable; private javax.swing.JButton cancelButton; private javax.swing.JButton changeButton; private javax.swing.JTextField channelInputField; private javax.swing.JLabel channelInputLabel; private javax.swing.JButton clearButton; private javax.swing.JCheckBox defaultCheckBox; private javax.swing.JButton deleteButton; private PlotWindow efficiencyCalibrationSpectrum; private javax.swing.JTextField efficiencyInputField; private javax.swing.JLabel efficiencyInputLabel; private javax.swing.JButton exportButton; private javax.swing.JLabel exportLabel; private javax.swing.JButton importButton; private javax.swing.JLabel importLabel; private javax.swing.JFormattedTextField jFormattedTextField1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JSeparator jSeparator1; private javax.swing.JSeparator jSeparator2; private javax.swing.JSeparator jSeparator3; private javax.swing.JSeparator jSeparator4; private javax.swing.JButton okButton; private javax.swing.JTextField polyFitOrderInput; private javax.swing.JLabel polyFitOrderLabel; private javax.swing.JLabel statusLabel; // End of variables declaration private class DataState { public String calibEquation_act; public String calibEquation_cur; public ArrayList<StringPair> tablebData_act = new ArrayList<StringPair>(); public ArrayList<StringPair> tablebData_cur = new ArrayList<StringPair>(); public EfficiencyCalibration calibration_act; public EfficiencyCalibration calibration_cur; public boolean defautCalib = false; public String path_act; public String path_cur; public String path_def; public String order_cur; public String order_act; public DataState() { calibEquation_act = ""; calibEquation_cur = ""; path_act = ""; path_cur = ""; path_def = ""; } } }
package com.lenovohit.ssm.treat.transfer.dao; import com.alibaba.fastjson.annotation.JSONField; import com.lenovohit.core.utils.StringUtils; public class RestResponse { @JSONField(name="RESULTCODE") private String resultcode; @JSONField(name="RESULT") private String result; @JSONField(name="CONTENT") private String content; @JSONField(name="ACCESS_TOKEN") private String access_token; @JSONField(name="EXPIRES_IN") private int expires_in; public String getResultcode() { return resultcode; } public void setResultcode(String resultcode) { this.resultcode = resultcode; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public int getExpires_in() { return expires_in; } public void setExpires_in(int expires_in) { this.expires_in = expires_in; } public boolean isSuccess(){ return StringUtils.isNotBlank(resultcode) && StringUtils.equals("1", resultcode); } }
package net.aphotix.conversion; import java.util.Map; /** * Encapsulates currency rates received from a restful json api * * @author Veil (nathan@aphotix.net). */ class CurrencyRates { private String base; private String date; private Map<String, Double> rates; /** * Get the base currency all the rates returned are measured against * * @return {@link String} The base currency code */ public String getBase() { return base; } /** * Get the date that base currency rate was updated * * @return {@link String} The date last updated */ public String getDate() { return date; } /** * Get all the rates that were returned as part of the restful request * * @return {@link Map} A map of currency rates returned */ public Map<String, Double> getRates() { return rates; } }
package xtrus.ex.tcs.test; import org.apache.commons.io.IOUtils; import org.apache.log4j.PropertyConfigurator; import org.junit.Before; import org.junit.Test; import com.esum.framework.cache.CacheFactory; import com.esum.framework.common.sql.Record; import xtrus.ex.tcs.channel.client.TcsClient; import xtrus.ex.tcs.message.TcsMessage; import xtrus.ex.tcs.table.TcsInfoRecord; public class TcsClientTest { @Before public void init() throws Exception { System.setProperty("xtrus.home", "D:/test/xtrus-4.3"); CacheFactory.getInstance().initCache(); } @Test public void sendSingle() throws Exception { PropertyConfigurator.configure("conf/log4j.properties"); Record record = new Record(7); record.put("CLIENT_USE_FLAG", "Y"); record.put("CLIENT_HOST", "127.0.0.1"); record.put("CLIENT_PORT", "5555"); record.put("CLIENT_CONN_TIMEOUT", "60"); record.put("CLIENT_IDLE_TIMEOUT", "60"); record.put("CLIENT_READ_TIMEOUT", "60"); record.put("USE_CLIENT_COMPRESS", "Y"); record.put("CLIENT_COMPRESS_TYPE", "A"); record.put("CLIENT_PACING_SIZE", "3"); TcsInfoRecord infoRecord = new TcsInfoRecord(record); // String fileName = "simple.txt"; // byte[] fileBytes = IOUtils.toByteArray(getClass().getResourceAsStream("/data/simple.txt")); String fileName = "simple_large"; byte[] fileBytes = IOUtils.toByteArray(getClass().getResourceAsStream("/data/simple_large")); TcsClient client = new TcsClient(infoRecord); TcsMessage response = client.process(fileName, fileBytes); System.out.println(response.toString()); client.shutdown(); } }
package com.ipfsoftwares.mangi360.customer; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import com.google.android.gms.appinvite.AppInviteInvitation; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.ConnectionResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import android.widget.*; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class MainActivity extends AppCompatActivity implements ConfirmPaymentDialogFragment.ConfirmPaymentListener, GoogleApiClient.OnConnectionFailedListener { private static final String TAG = "MainActivity"; public static final String MESSAGES_CHILD = "messages"; private static final int REQUEST_INVITE = 1; private static final int REQUEST_IMAGE = 2; private static final String LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif"; public static final int DEFAULT_MSG_LENGTH_LIMIT = 10; public static final String ANONYMOUS = "anonymous"; private static final String MESSAGE_SENT_EVENT = "message_sent"; private String mDisplayName; private String mPhoneNumber; private String mPhotoUrl; private SharedPreferences mSharedPreferences; private GoogleApiClient mGoogleApiClient; private static final String MESSAGE_URL = "http://friendlychat.firebase.google.com/message/"; private Button mMakePaymentButton; private LinearLayoutManager mLinearLayoutManager; // Firebase instance variables private FirebaseAuth mFirebaseAuth; private FirebaseUser mFirebaseUser; private DatabaseReference mFirebaseReference; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // Set default username is anonymous. mDisplayName = ANONYMOUS; mFirebaseAuth = FirebaseAuth.getInstance(); mFirebaseUser = mFirebaseAuth.getCurrentUser(); if (mFirebaseUser == null) { startActivity(new Intent(this, SignInActivity.class)); finish(); return; } else { mDisplayName = mFirebaseUser.getDisplayName(); if(mFirebaseUser.getPhotoUrl() != null) { mPhotoUrl = mFirebaseUser.getPhotoUrl().toString(); } } mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API) .build(); mMakePaymentButton = (Button) findViewById(R.id.makePaymentButton); mMakePaymentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new IntentIntegrator(MainActivity.this).initiateScan(); // `this` is the current Activity } }); } @Override public void onStart() { super.onStart(); // Check if user is signed in. // TODO: Add code to check if user is signed in. } @Override public void onPause() { super.onPause(); } @Override public void onResume() { super.onResume(); } @Override public void onDestroy() { super.onDestroy(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.invite_menu: sendInvitation(); return true; case R.id.user_profile_menu: showUserProfile(); return true; case R.id.sign_out_menu: mFirebaseAuth.signOut(); Auth.GoogleSignInApi.signOut(mGoogleApiClient); mDisplayName = ANONYMOUS; startActivity(new Intent(this, SignInActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } private void showUserProfile() { Intent intent = new Intent(this, ProfileActivity.class); intent.putExtra("displayName", mDisplayName); intent.putExtra("phoneNumber", mPhoneNumber); intent.putExtra("photoUrl", mPhotoUrl); startActivity(intent); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { // An unresolvable error has occurred and Google APIs (including Sign-In) will not // be available. Log.d(TAG, "onConnectionFailed:" + connectionResult); Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if(result != null) { if(result.getContents() == null) { Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show(); } else { JSONTokener tokener = new JSONTokener(result.getContents()); JSONObject root = null; try { root = new JSONObject(tokener); } catch (JSONException e) { e.printStackTrace(); } String grandTotal = null; try { grandTotal = root.getString("total"); } catch (JSONException e) { e.printStackTrace(); } JSONObject merchantObject = null; try { merchantObject = new JSONObject(root.getString("merchant")); } catch (JSONException e) { e.printStackTrace(); } String merchantName = null; try { merchantName = merchantObject.getString("name"); } catch (JSONException e) { e.printStackTrace(); } String merchantNumber = null; try { merchantNumber = merchantObject.getString("phoneNumber"); } catch (JSONException e) { e.printStackTrace(); } Toast.makeText(this, "Scanned: " + merchantName + " " + merchantNumber + " " + grandTotal, Toast.LENGTH_LONG).show(); showConfirmPaymentDialog(); } } else { super.onActivityResult(requestCode, resultCode, data); } } private void sendInvitation() { Intent intent = new AppInviteInvitation.IntentBuilder(getString(R.string.invitation_title)) .setMessage(getString(R.string.invitation_message)) .setCallToActionText(getString(R.string.invitation_cta)) .build(); startActivityForResult(intent, REQUEST_INVITE); } private void showConfirmPaymentDialog() { DialogFragment newFragment = new ConfirmPaymentDialogFragment(); newFragment.show(getSupportFragmentManager(), "Confirm Payment"); } @Override public void onDialogPositiveClick(DialogFragment dialog) { EditText confirmPaymentEditText = (EditText) dialog.getDialog().findViewById(R.id.confirm_payment_edit_text); String pinCode = String.valueOf(confirmPaymentEditText.getText()); Toast.makeText(this, "Payment confirmed with code " + pinCode, Toast.LENGTH_LONG).show(); } @Override public void onDialogNegativeClick(DialogFragment dialog) { Toast.makeText(this, "Payment cancelled!", Toast.LENGTH_LONG).show(); } }
public class Solution{ //this method takes O(b) time(b is the length of bit sequence) and O(1) space. public static int flipBitToWin(int num){ int SEQUENCE_LENGTH = 32; if(num==-1){return SEQUENCE_LENGTH;} boolean used = false; int max = 0; int before = 0; int after = 0; for(int i=0;i<SEQUENCE_LENGTH;i++){ if(getBit(num,i)){ if(used){after++;} else{before++;} }else{ if(used){ max = Math.max(max,before+after+1); before = after; after = 0; }else{ used = true; } } } max = Math.max(max,before+after+1); return max; } //helper function checks certain bit in given number, 1 returns true, 0 return false. private static boolean getBit(int num,int index){ return (num&(1<<index))!=0; } }
package Builder.Difficult; import Builder.Computer; public class BuilderAbsTest { public static void main(String[] args) { Director director = new Director(); director.setBuilder(new OfficeComputerBuilder()); Computer computer = director.buildComputer(); System.out.println(computer); } }
package com.github.timm.cucumber.generate; import com.github.timm.cucumber.generate.name.ClassNamingScheme; import org.apache.maven.plugin.MojoExecutionException; public class CucumberITGeneratorFactory { private final OverriddenCucumberOptionsParameters overriddenParameters; private final ClassNamingScheme classNamingScheme; private final FileGeneratorConfig config; /** * @param config generator config. * @param overriddenParameters cucumber options params * @param classNamingScheme the class naming scheme to use */ public CucumberITGeneratorFactory(final FileGeneratorConfig config, final OverriddenCucumberOptionsParameters overriddenParameters, final ClassNamingScheme classNamingScheme) { this.overriddenParameters = overriddenParameters; this.classNamingScheme = classNamingScheme; this.config = config; } /** * Create a CucumberITGenerator based on the given parallel scheme. * @param parallelScheme The scheme to use * @return * @throws MojoExecutionException */ public CucumberITGenerator create(final ParallelScheme parallelScheme) throws MojoExecutionException { if (ParallelScheme.FEATURE.equals(parallelScheme)) { return createFileGeneratorByFeature(); } else { return createFileGeneratorByScenario(); } } @SuppressWarnings("deprecation") private CucumberITGenerator createFileGeneratorByFeature() throws MojoExecutionException { return new CucumberITGeneratorByFeature(config, overriddenParameters, classNamingScheme); } private CucumberITGenerator createFileGeneratorByScenario() throws MojoExecutionException { return new CucumberITGeneratorByScenario(config, overriddenParameters, classNamingScheme); } }
/* * 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 common; import java.util.Calendar; import java.util.Date; /** * * @author Kray */ public class MessageRecu extends Message { int hourReceived; int minuteReceived; int secondsReceived; String timeReceived ; public MessageRecu(MsgType type, String content, String sender) { super(type, content, sender); hourReceived = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); minuteReceived = Calendar.getInstance().get(Calendar.MINUTE); secondsReceived = Calendar.getInstance().get(Calendar.SECOND); timeReceived=hourReceived+":"+minuteReceived+":"+secondsReceived ; } @Override public String toString() { return timeReceived + " >> " + this.getSender() + " : " + this.getContent(); } }
package com.alibaba.druid.bvt.pool.exception; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import junit.framework.TestCase; import com.alibaba.druid.mock.MockConnection; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.pool.DruidPooledConnection; import com.alibaba.druid.pool.vendor.OracleExceptionSorter; import com.alibaba.druid.stat.JdbcStatManager; import com.alibaba.druid.test.util.OracleMockDriver; import com.alibaba.druid.util.JdbcUtils; public class OracleExceptionSorterTest_commit extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { assertEquals(0, JdbcStatManager.getInstance().getSqlList().size()); dataSource = new DruidDataSource(); dataSource.setExceptionSorter(new OracleExceptionSorter()); dataSource.setDriver(new OracleMockDriver()); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setPoolPreparedStatements(true); dataSource.setMaxOpenPreparedStatements(100); } @Override protected void tearDown() throws Exception { JdbcUtils.close(dataSource); } public void test_connect() throws Exception { String sql = "SELECT 1"; { DruidPooledConnection conn = dataSource.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.execute(); pstmt.close(); conn.close(); assertEquals(0, dataSource.getActiveCount()); assertEquals(1, dataSource.getPoolingCount()); assertEquals(1, dataSource.getCreateCount()); } DruidPooledConnection conn = dataSource.getConnection(); MockConnection mockConn = conn.unwrap(MockConnection.class); assertNotNull(mockConn); conn.setAutoCommit(false); conn.prepareStatement(sql); SQLException exception = new SQLException("xx", "xxx", 28); mockConn.setError(exception); Exception commitError = null; try { conn.commit(); } catch (Exception ex) { commitError = ex; } assertNotNull(commitError); conn.close(); { Connection conn2 = dataSource.getConnection(); conn2.close(); } assertEquals(0, dataSource.getActiveCount()); assertTrue(dataSource.getPoolingCount() >= 1); assertTrue(dataSource.getCreateCount() >= 2); } }
package com.brainacad.oop.diplom; import java.util.ArrayList; /** * Created by Администратор on 31.01.2016. */ public class Trainer { private Integer idTrainer; private String firstNameTrainer; private String secondNameTrainer; private ArrayList<Integer> listTrainerCourse; }
package it.unibo.bd1819.job2.reducers; import it.unibo.bd1819.job2.utils.Utility; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; import java.io.IOException; public class CountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { /** * Reducer for count how many book are listed for each groups * @param key the book_id * @param values List of bookmarks * @param context */ public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int count = 0; for(IntWritable mark : values){ count ++; } context.write(key, new IntWritable(count)); } }
package com.sys2017.android_app_test; import android.content.Intent; import android.support.design.widget.BaseTransientBottomBar; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.error.VolleyError; import com.android.volley.request.SimpleMultiPartRequest; import com.android.volley.toolbox.Volley; import com.bumptech.glide.Glide; import com.mikhaellopez.circularimageview.CircularImageView; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Timer; import java.util.TimerTask; public class SecondActivity extends AppCompatActivity { CircularImageView circularImageView; TextView textView_memo; TextView textView_date; EditTextLetter editTextLetter; FloatingActionButton floatingActionButton; Boolean click = false; String serverUrl = "http://imgenius0136.dothome.co.kr/FALLING/diarySaveDB.php"; String id; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); circularImageView = (CircularImageView) findViewById(R.id.circular_imageView); textView_memo = ( TextView ) findViewById(R.id.textView_memo); textView_date = ( TextView ) findViewById(R.id.textView_date); editTextLetter = ( EditTextLetter ) findViewById(R.id.editTextLetter_diary); floatingActionButton = ( FloatingActionButton ) findViewById(R.id.floating_save); Intent intent = getIntent(); if ( intent != null ){ id = intent.getStringExtra("id"); String imgUrl = intent.getStringExtra("pic"); String memo = intent.getStringExtra("memo"); String date = intent.getStringExtra("date"); Log.e("아이디",id.toString()); Glide.with(this).load(imgUrl).into(circularImageView); textView_memo.setText(memo); textView_date.setText(date); } floatingActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(SecondActivity.this, "저장했어요.", Toast.LENGTH_SHORT).show(); insertDiary(); } }); } public void clickBackground(View v){ if ( click == false ){ getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); click = true; } } void insertDiary(){ RequestQueue requestQueue = Volley.newRequestQueue(SecondActivity.this); SimpleMultiPartRequest simpleMultiPartRequest = new SimpleMultiPartRequest(Request.Method.POST, serverUrl, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("데이터베이스",response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("실패!!!","실패!!!"); } }); simpleMultiPartRequest.addStringParam("id",id.toString()); simpleMultiPartRequest.addStringParam("diary",editTextLetter.getText().toString()); requestQueue.add(simpleMultiPartRequest); } }
package com.joy.concurrent.threadpool; import java.util.Date; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Created by SongLiang on 2019-10-09 */ public class ThreadPoolShedule { public static void main(String[] args) { ScheduledExecutorService exec = Executors.newScheduledThreadPool(10); exec.schedule(new Runnable() { @Override public void run() { System.out.println("schedule run"); } }, 3, TimeUnit.SECONDS); exec.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("delay schedule run"); } }, 1, 3, TimeUnit.SECONDS); exec.shutdown(); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("timer run"); } }, new Date(), 5 * 1000); } }
package net.gupt.ebuy.admin.service; import java.util.List; import net.gupt.ebuy.admin.dao.PaymentDao; import net.gupt.ebuy.admin.dao.PaymentDaoImpl; import net.gupt.ebuy.pojo.Payment; /** * 支付方式后台管理业务接口实现类 * @author glf * */ public class PaymentServiceImpl implements PaymentService{ private PaymentDao paymentDao = new PaymentDaoImpl(); public List<Payment> queryPayments(int currentPage, int pageSize) { List<Payment> payments = paymentDao.query(currentPage, pageSize); return payments; } public Payment findPayment(String id) { Payment payment = paymentDao.findById(id); return payment; } public void updatePayment(Payment payment) { paymentDao.update(payment); } public void deletePayment(Payment payment) { paymentDao.delete(payment); } public void addPayment(Payment payment) { paymentDao.save(payment); } }
/** * search.java * binary search function to search an element e in an array A * all the elements in array A are useful elements, and the values in A are ordered in ascending order. * @since 21 NOV 2019 * @author Huiying Chen */ package cs463lab13_Heap; public class search { /** * @param A - an ascending ordered array to be searched * @param e - the target element * @return the index of the target element, if not found, return -1 */ public static int binarySearch (int[] A, int e) { //call the function int resultPos = binarySearch(A, 0, A.length-1, e); return resultPos; } /** * @param array - an array to be searched * @param idxs - start index * @param idxe - end index * @param e - the target element * @return index of the target element, return -1 if not found */ private static int binarySearch (int[]array, int idxs, int idxe, int e){ //base case, if not found, return -1 if(idxe < idxs) return -1; //get the middle index int idx_middle = (idxe+idxs)/2; //base case, if found, return the index if(array[idx_middle] == e) { return idx_middle; //if e is less than the middle value, set end index to middle-1 and recursive call }else if(e < array[idx_middle]) { return binarySearch(array, idxs, idx_middle-1, e); //if e is greater than the middle value, set start index to middle+1 and recursive call }else { return binarySearch(array, idx_middle+1, idxe, e); } } /** * main */ public static void main(String[] args) { System.out.println("Binary search test: "); int[] A = {2, 5, 8, 20, 34, 61, 93, 100}; System.out.print("Array: "); for (int i : A) {System.out.printf(i + " ");} System.out.println(); //test cases System.out.printf("The index of 20 in the array is: " + binarySearch (A, 20) + "\n"); System.out.printf("The index of 2 in the array is: " + binarySearch (A, 2) + "\n"); System.out.printf("The index of 100 in the array is: " + binarySearch (A, 100) + "\n"); //test non-exist element System.out.printf("The index of 77(non-exists) in the array is: " + binarySearch (A, 77) + "\n"); } }
package cn.Object; //此时设置的T在Point定义上只表示一个标记,在使用的时候需要为其设置具体的类型 class Point<T>{ //定义坐标,Type = T private T x; //此事的类型不知道,由Point类使用时动态决定 private T y; public T getX() { return x; } public void setX(T x) { this.x = x; } public T getY() { return y; } public void setY(T y) { this.y = y; } } public class TestDemo2 { public static void main(String[] args) { //第一步,设置数据 Point p = new Point(); p.setX(10); p.setY(20); //第二部,取出数据 int x = (Integer) p.getX(); int y = (Integer) p.getY(); System.out.println("x坐标:"+x+" Y坐标:"+y); //第一步,设置数据 p.setX("东经100度"); p.setY("西经20度"); //第二部,取出数据 String sx = (String) p.getX(); String sy = (String) p.getY(); System.out.println("x坐标:"+sx+" Y坐标:"+sy); //第一步,设置数据 Point<String> sp = new Point<String>(); sp.setX("东经100度"); sp.setY("西经20度"); //第二部,取出数据 String ssx = sp.getX(); //不需要强制转换 String ssy = sp.getY(); System.out.println("x坐标:"+ssx+" Y坐标:"+ssy); } }
package com.online.spring.core.property; public class Properties { String model; String color; String make; int yofm; public Properties() { } public Properties(String model, String color, String make, int yofm) { this.model = model; this.color = color; this.make = make; this.yofm = yofm; } public void setModel(String model) { this.model = model; } public void setColor(String color) { this.color = color; } public void setMake(String make) { this.make = make; } public void setYofm(int yofm) { this.yofm = yofm; } public void printpropety() { System.out.println("Model :" + model); System.out.println("Color :" + color); System.out.println("Make :" + make); System.out.println("Year :" + yofm); } }
package com.dongh.sample.http; import com.dongh.baselibs.http.RetrofitManager; import com.dongh.sample.http.api.Api; import com.dongh.sample.http.cache.CacheProvider; import com.dongh.sample.http.cache.WeatherCacheProvider; import com.dongh.sample.http.service.RetrofitService; import com.dongh.sample.http.service.WeatherService; /** * @author chenxz * @date 2018/8/31 * @desc RetrofitHelper:主要用来创建不同 host 的 RetrofitService 和 CacheService */ public class RetrofitHelper { /** * 获取 RetrofitService */ public static RetrofitService getRetrofitService() { return RetrofitManager.getInstance().obtainRetrofitService(Api.WAN_ANDROID_HOST, RetrofitService.class); } /** * 获取 CacheService */ public static CacheProvider getCacheService() { return RetrofitManager.getInstance().obtainCacheService(CacheProvider.class); } public static WeatherService getWeatherService() { return RetrofitManager.getInstance().obtainRetrofitService(Api.WEATHER_HOST, WeatherService.class); } public static WeatherCacheProvider getWeatherCacheService() { return RetrofitManager.getInstance().obtainCacheService(WeatherCacheProvider.class); } }
package co.edu.campusucc.sd.modelo; // Generated 23/05/2020 02:30:18 PM by Hibernate Tools 5.4.7.Final import java.util.HashSet; import java.util.Set; /** * Banco generated by hbm2java */ public class Banco implements java.io.Serializable { private String idBanco; private String nombreBanco; private String direccion; private String email; private Set clientes = new HashSet(0); public Banco() { } public Banco(String idBanco, String nombreBanco, String direccion, String email) { this.idBanco = idBanco; this.nombreBanco = nombreBanco; this.direccion = direccion; this.email = email; } public Banco(String idBanco, String nombreBanco, String direccion, String email, Set clientes) { this.idBanco = idBanco; this.nombreBanco = nombreBanco; this.direccion = direccion; this.email = email; this.clientes = clientes; } public String getIdBanco() { return this.idBanco; } public void setIdBanco(String idBanco) { this.idBanco = idBanco; } public String getNombreBanco() { return this.nombreBanco; } public void setNombreBanco(String nombreBanco) { this.nombreBanco = nombreBanco; } public String getDireccion() { return this.direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public Set getClientes() { return this.clientes; } public void setClientes(Set clientes) { this.clientes = clientes; } }
package com.trl.consumerautomaticoffsetcommitting.constants; public final class Constants { public Constants() { } public static final String LOG_HEADER = ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> "; }
package dev.liambloom.softwareEngineering.chapter11.polygonComparable; public class IsoscelesTrapezoid extends Trapezoid { // Constructors public IsoscelesTrapezoid() { super(); } public IsoscelesTrapezoid(double base1, double base2, double height) { super(base1, base2, height); } // Inherited @Override public String toString() { return "Isosceles Trapezoid and I am also a " + super.toString(); } }
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; import org.springframework.cloud.netflix.hystrix.EnableHystrix; /** * 服务消费者 * @EnableEurekaClient 只支持Eureka注册中心,@EnableDiscoveryClient还支持更多其他的注册中心 * @EnableCircuitBreaker 当使用ribbon+restTemplate方式进行服务间调用时,为实现服务降级 * @EnableFeignClients 使用Feign进行服务间调用并实现了服务降级 * @EnableHystrix 开启断路器,实现熔断降级服务?不知哪里用到,不加也没什么影响! * @EnableHystrixDashboard 开启Hystrix断路器监控 * * @author zhoubc */ @SpringBootApplication @EnableEurekaClient @EnableCircuitBreaker @EnableFeignClients @EnableHystrix @EnableHystrixDashboard public class SpringCloudConsumersDemoApplication { /** * http://localhost:8100/ * */ public static void main(String[] args) { SpringApplication.run(SpringCloudConsumersDemoApplication.class, args); System.out.println("consumers服务启动成功"); } }
package com.auro.scholr.payment.data.model.request; public class PaytmWithdrawalByUPIReqModel { String mobileNo; String upiaddress; String disbursementMonth; String disbursement; String purpose; public String getMobileNo() { return mobileNo; } public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } public String getUpiaddress() { return upiaddress; } public void setUpiaddress(String upiaddress) { this.upiaddress = upiaddress; } public String getDisbursementMonth() { return disbursementMonth; } public void setDisbursementMonth(String disbursementMonth) { this.disbursementMonth = disbursementMonth; } public String getDisbursement() { return disbursement; } public void setDisbursement(String disbursement) { this.disbursement = disbursement; } public String getPurpose() { return purpose; } public void setPurpose(String purpose) { this.purpose = purpose; } }
package leetcode; import java.util.ArrayList; public class ZigZagConversion6 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(convert("AB",1)); } public static String convert(String s, int numRows) { ArrayList<ArrayList<Character>> resultArray = new ArrayList<ArrayList<Character>>(); for(int i=0;i<numRows;i++) { resultArray.add(new ArrayList<Character>()); } int i =0; boolean direction = true; int level = 0; String result = ""; if(numRows>1) { while(i<s.length()) { resultArray.get(level).add(s.charAt(i++)); if(direction) { if(level<numRows-1) { level++; }else { direction = false; level--; } }else { if(level>0) { level--; }else { direction = true; level++; } } } }else { result = s; } for(i=0;i<numRows;i++) { ArrayList<Character> charArray = resultArray.get(i); for(Character c : charArray) { result = result+String.valueOf(c); } } return result; } }
package com.trump.auction.goods.api.impl; import com.alibaba.dubbo.config.annotation.Service; import com.trump.auction.goods.api.ProductInventoryLogRecordSubService; import com.trump.auction.goods.model.ProductInventoryLogRecordModel; import com.trump.auction.goods.service.ProductInventoryLogRecordService; import org.springframework.beans.factory.annotation.Autowired; /** * Created by 罗显 on 2017/12/21. */ @Service(version = "1.0.0") public class ProductInventoryLogRecordSubServiceImpl implements ProductInventoryLogRecordSubService { @Autowired private ProductInventoryLogRecordService productInventoryLogRecordService; @Override public int addStock(ProductInventoryLogRecordModel productInventoryLogRecordModel) { return productInventoryLogRecordService.addStock(productInventoryLogRecordModel); } @Override public ProductInventoryLogRecordModel validateRecord(int productId) { ProductInventoryLogRecordModel validateRecord = productInventoryLogRecordService.validateRecord(productId); if(validateRecord !=null ){ return validateRecord; }else { return null; } } @Override public int updateStock(ProductInventoryLogRecordModel productInventoryLogRecordModel) { return productInventoryLogRecordService.updateStock(productInventoryLogRecordModel); } }
package com.sevael.lgtool.dao.impl; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.bson.Document; import org.bson.conversions.Bson; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Sorts; import com.sevael.lgtool.configuration.LgtDBFactory; import com.sevael.lgtool.dao.CommonDBDao; import com.sevael.lgtool.dao.ServiceProviderDBDao; import com.sevael.lgtool.utils.AppConstants; import com.sevael.lgtool.utils.JsonUtil; import com.sevael.lgtool.utils.UtilConstants; @Repository public class ServiceProviderDBDaoImpl implements ServiceProviderDBDao, AppConstants, UtilConstants { @Autowired private CommonDBDao commonDBDao; @Autowired private CertificationDBDaoImpl certificationDBDaoImpl; @Override public String save(JsonObject servproviderDetails) { MongoClient cli = null; final String METHODNAME = "[addServiceProvider]"; JsonObject returnStatus = new JsonObject(); String SpID = ""; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd h:mm:ss a"); try { cli = LgtDBFactory.getMongoClient(); MongoDatabase db = cli.getDatabase(DATABASE_NAME); MongoCollection<Document> table = db.getCollection(COLL_NAME_SERVICEPROVIDER); Document trainingDoc = commonDBDao.getEntityWithFilter(DATABASE_NAME, COLL_NAME_SERVICEPROVIDER, Filters.or(Filters.regex("name", "^" + servproviderDetails.get("name").getAsString() + "$", "i")), null); if (trainingDoc == null) { trainingDoc = new Document(); int seq = commonDBDao.getNextSequence(db, COLL_NAME_SERVICEPROVIDER); SpID = COLL_NAME_SERVICEPROVIDER + seq; trainingDoc.put("_id", SpID); trainingDoc.put("name", servproviderDetails.get("name").getAsString()); trainingDoc.put("seq", seq); trainingDoc.put("creationdate", formatter.format(new Date())); table.insertOne(trainingDoc); returnStatus.addProperty("_id", SpID); returnStatus.addProperty(RS_MESSAGE, ADD_COMMON_SUCCESS); returnStatus.addProperty(RS_STATUS, MSG_SUCCESS); } else { returnStatus.addProperty("isexists", true); returnStatus.addProperty(RS_MESSAGE, ADD_COMMON_EXISTS); } } catch (Exception ex) { returnStatus.addProperty(RS_STATUS, MSG_FAILURE); System.out.println("ServiceProviderDBDaoImpl --> " + ex.toString()); } return returnStatus.toString(); } @Override public List<Document> list(String searchstr, int page) { final String METHODNAME = "[getAllServiceProvider]:"; List<Document> serviceProviderList = null; int pageLimit = 10; int numberOfRecordsSkipPerPage = 0; if (page > 1) { numberOfRecordsSkipPerPage = (10 * page); numberOfRecordsSkipPerPage -= 10; } try { if (searchstr != null && searchstr.length() > 0) { serviceProviderList = commonDBDao.getAllEntityWithPagination(DATABASE_NAME, COLL_NAME_SERVICEPROVIDER, Filters.regex("name", "^" + searchstr + ".*", "i"), Sorts.descending("seq"), null, numberOfRecordsSkipPerPage, pageLimit); } else { serviceProviderList = commonDBDao.getAllEntityWithPagination(DATABASE_NAME, COLL_NAME_SERVICEPROVIDER, null, Sorts.descending("seq"), null, numberOfRecordsSkipPerPage, pageLimit); } } catch (Exception ex) { // logger.error(CLASSNAME + METHODNAME + " Exception : ", ex); System.out.println("ServiceProviderDBDaoImpl --- getAllServiceProvider ---> " + ex.toString()); } return serviceProviderList; } @Override public String update(JsonObject updateServiceProvider) { MongoClient cli = null; JsonObject returnStatus = new JsonObject(); String ServiceProviderID = ""; try { cli = LgtDBFactory.getMongoClient(); MongoDatabase db = cli.getDatabase(DATABASE_NAME); MongoCollection<Document> table = db.getCollection(COLL_NAME_SERVICEPROVIDER); Document trainingDoc = commonDBDao.getEntityWithFilter(DATABASE_NAME, COLL_NAME_SERVICEPROVIDER, Filters.and(Filters.ne("_id", updateServiceProvider.get("_id").getAsString()), Filters.regex("name", "^" + updateServiceProvider.get("name").getAsString() + "$", "i")), null); if (trainingDoc == null) { ServiceProviderID = updateServiceProvider.get("_id").getAsString(); table.updateOne(Filters.eq("_id", ServiceProviderID), new Document("$set", new Document("name", updateServiceProvider.get("name").getAsString()))); returnStatus.addProperty("_id", ServiceProviderID); returnStatus.addProperty(RS_MESSAGE, ADD_UPDATECOMMON_SUCCESS); returnStatus.addProperty(RS_STATUS, MSG_SUCCESS); } else { returnStatus.addProperty("isexists", true); returnStatus.addProperty(RS_MESSAGE, ADD_COMMON_EXISTS); } } catch (Exception ex) { System.out.println("ServiceProviderDBDaoImpl --> " + ex.toString()); returnStatus.addProperty(RS_STATUS, MSG_FAILURE); } return returnStatus.toString(); } @Override public String searchServiceProvider(String searchstr, String status) { List<Document> searchLBDoc = new ArrayList<Document>(); Bson finalFilter = null; Bson searchValFilter = null; Bson statusFilter = null; try { searchValFilter = searchstr.length() <= 0 ? null : Filters.regex("servprovidername", "^" + searchstr + ".*", "i"); if (status.equalsIgnoreCase("active")) { statusFilter = Filters.eq("status", status); System.out.println("earchServiceProvider --> statusFilter---> " + statusFilter); } if (statusFilter != null) { finalFilter = Filters.and(searchValFilter, statusFilter); } else { finalFilter = Filters.and(searchValFilter); } searchLBDoc = commonDBDao.getAllEntity(DATABASE_NAME, COLL_NAME_SERVICEPROVIDER, finalFilter, null, null, 0); } catch (Exception ex) { System.out.println("ServiceProviderDBDaoImpl --> searchServiceProvider --> " + ex.toString()); } JsonArray searchLBArray = new JsonArray(); for (Document doc : searchLBDoc) { searchLBArray.add(JsonUtil.parseJSON(doc)); } return searchLBArray.toString(); } @Override public Document get(String id) { return commonDBDao.getEntityWithFilter(DATABASE_NAME, COLL_NAME_SERVICEPROVIDER, Filters.eq("_id", id), null); } @Override public String getPaginationCount(String searchstr) { final String METHODNAME = "[getAllServiceProvider]:"; List<Document> serviceProviderList = null; JsonObject returnStatus = new JsonObject(); returnStatus.addProperty(PAGE_COUNT, 0); try { if (searchstr != null && searchstr.length() > 0) { serviceProviderList = commonDBDao.getAllEntity(DATABASE_NAME, COLL_NAME_SERVICEPROVIDER, Filters.regex("name", "^" + searchstr + ".*", "i"), Sorts.descending("seq"), null, 0); } else { serviceProviderList = commonDBDao.getAllEntity(DATABASE_NAME, COLL_NAME_SERVICEPROVIDER, null, Sorts.descending("seq"), null, 0); } if (serviceProviderList.size() > 0) { returnStatus.addProperty(PAGE_COUNT, serviceProviderList.size()); } } catch (Exception ex) { // logger.error(CLASSNAME + METHODNAME + " Exception : ", ex); System.out.println("ServiceProviderDBDaoImpl --- getAllServiceProvider ---> " + ex.toString()); } return returnStatus.toString(); } }
package com.mediafire.sdk.config; import java.util.HashMap; import java.util.Map; public class DefaultCredentials implements MFCredentials { private final Map<String, String> credentials = new HashMap<String, String>(); private boolean valid; public DefaultCredentials() { } @Override public void setCredentials(Map<String, String> credentials) { this.credentials.clear(); this.credentials.putAll(credentials); } @Override public Map<String, String> getCredentials() { return credentials; } @Override public void invalidate() { valid = false; credentials.clear(); } @Override public boolean setValid() { if (credentials.isEmpty()) { valid = false; return false; } else { valid = true; return true; } } @Override public boolean isValid() { return valid; } }
/** * MIT License * <p> * Copyright (c) 2017-2018 nuls.io * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package network.nerve.converter.heterogeneouschain.ht.dbtest; import io.nuls.core.log.Log; import io.nuls.core.parse.JSONUtils; import io.nuls.core.rockdb.service.RocksDBService; import network.nerve.converter.heterogeneouschain.ht.constant.HtDBConstant; import network.nerve.converter.heterogeneouschain.ht.context.HtContext; import network.nerve.converter.heterogeneouschain.lib.context.HtgContext; import network.nerve.converter.heterogeneouschain.lib.model.HtgAccount; import network.nerve.converter.heterogeneouschain.lib.storage.impl.*; import org.junit.BeforeClass; import org.junit.Test; /** * @author: PierreLuo * @date: 2021-03-25 */ public class DbTest { static HtContext htContext = new HtContext(); @BeforeClass public static void before() { Log.info("init"); htContext.setLogger(Log.BASIC_LOGGER); RocksDBService.init("/Users/pierreluo/IdeaProjects/nerve-network/nerve/converter/converter-htn/src/test/resources/data/converter/"); } @Test public void testAccountDB() throws Exception { HtgAccountStorageServiceImpl accoutDb = new HtgAccountStorageServiceImpl(htContext, HtDBConstant.DB_HT); HtgAccount account = accoutDb.findByAddress("0xdd7cbedde731e78e8b8e4b2c212bc42fa7c09d03"); System.out.println(JSONUtils.obj2PrettyJson(account)); HtgAccount account1 = new HtgAccount(); account1.setAddress("0x123"); account1.setOrder(2); account1.setCompressedPublicKey("0xabcd"); accoutDb.save(account1); HtgAccount _account = accoutDb.findByAddress("0x123"); System.out.println(JSONUtils.obj2PrettyJson(_account)); } @Test public void testBlockDB() throws Exception { HtgBlockHeaderStorageServiceImpl blockDB = new HtgBlockHeaderStorageServiceImpl(htContext, HtDBConstant.DB_HT); System.out.println(JSONUtils.obj2PrettyJson(blockDB.findLatest())); } @Test public void testERC20DB() throws Exception { HtgERC20StorageServiceImpl _erc20DB = new HtgERC20StorageServiceImpl(htContext, HtDBConstant.DB_HT); System.out.println(_erc20DB.getMaxAssetId()); System.out.println(JSONUtils.obj2PrettyJson(_erc20DB.findByAddress("0x04f535663110a392a6504839beed34e019fdb4e0"))); } @Test public void testMultySignAddressDB() throws Exception { HtgMultiSignAddressHistoryStorageServiceImpl multyDB = new HtgMultiSignAddressHistoryStorageServiceImpl(htContext, HtDBConstant.DB_HT); System.out.println(JSONUtils.obj2PrettyJson(multyDB.findAll())); } @Test public void testTxInvokeInfoDB() throws Exception { HtgTxInvokeInfoStorageServiceImpl txInvokeInfoDB = new HtgTxInvokeInfoStorageServiceImpl(htContext, HtDBConstant.DB_HT); System.out.println(JSONUtils.obj2PrettyJson(txInvokeInfoDB.findAllWaitingTxPo())); } @Test public void testTxRelationDB() throws Exception { HtgTxRelationStorageServiceImpl txRelationDB = new HtgTxRelationStorageServiceImpl(htContext, HtDBConstant.DB_HT); System.out.println(JSONUtils.obj2PrettyJson(txRelationDB.findEthSendTxPo("0xfac20bde3a1134006504180bc76efece3924dc58b11e0d1bb491c42ce3a394da"))); } @Test public void testTxDB() throws Exception { HtgTxStorageServiceImpl txDB = new HtgTxStorageServiceImpl(htContext, HtDBConstant.DB_HT); System.out.println(JSONUtils.obj2PrettyJson(txDB.findByTxHash("0xfac20bde3a1134006504180bc76efece3924dc58b11e0d1bb491c42ce3a394da"))); } @Test public void testUnconfirmedTxDB() throws Exception { HtgUnconfirmedTxStorageServiceImpl unconfirmedTxDB = new HtgUnconfirmedTxStorageServiceImpl(htContext, HtDBConstant.DB_HT); System.out.println(JSONUtils.obj2PrettyJson(unconfirmedTxDB.findAll())); } }
package objects.android.popupmenus; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import objects.android.MainViewDR; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.ExpectedConditions; public class PopUpMenuOfStopDisplayButtonDR extends MainViewDR { private By headerStopDisplayPopMenuTextField = By.xpath("//android.widget.TextView[@text = 'Display Ride']"); private By stopDisplayPopMenuTextField = By.xpath("//android.widget.TextView[@text = 'Stop Display']"); private By areYouSurePopMenuTextField = By.xpath("//android.widget.TextView[@text = 'Are you sure?']"); private By yesButtonPopMenu = By.id("btnYes"); private By noButtonPopMenu = By.id("btnNo"); private By headerText = By.xpath("//*[@text = 'Display Ride']"); private By stopDisplayText = By.xpath("//*[@text = 'Stop Display']"); private By areYouSureText = By.xpath("//*[@text = 'Are you sure?']"); private By someButton = By.xpath("//"); public PopUpMenuOfStopDisplayButtonDR(AndroidDriver<AndroidElement> driver) { super(driver); } public void stopDisplayYesTap() { wait.until(ExpectedConditions.presenceOfElementLocated(yesButtonPopMenu)); t.tap(driver.findElement(yesButtonPopMenu)).perform(); } public void stopDisplayNoTap() { wait.until(ExpectedConditions.presenceOfElementLocated(yesButtonPopMenu)); t.tap(driver.findElement(noButtonPopMenu)).perform(); } public String displayRideHeaderText() { wait.until(ExpectedConditions.presenceOfElementLocated(headerText)); return driver.findElement(headerText).getText(); } public String stopDisplayText() { wait.until(ExpectedConditions.presenceOfElementLocated(stopDisplayText)); return driver.findElement(stopDisplayText).getText(); } public String areYouSureText() { wait.until(ExpectedConditions.presenceOfElementLocated(areYouSureText)); return driver.findElement(areYouSureText).getText(); } }
import java.util.Scanner; public class task4 { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Введите три числа: "); int x = in.nextInt(); int y = in.nextInt(); int z = in.nextInt(); int result = (x + y + z) / 3; System.out.printf("Среднее арифметическое введённых чисел: %d \n", result); if (result / 2 > 3) { System.out.print("Программа выполнена корректно"); } } }
/* * Copyright (C) 2021 Tenisheva N.I. */ package com.entrepreneurship.rest.webservices.restfulwebservices; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /* * Current class starts the program * @version 1.0 @author Tenisheva N.I. */ @SpringBootApplication public class RestfulWebServicesApplication { public static void main(String[] args) { SpringApplication.run(RestfulWebServicesApplication.class, args); } }
package idea_service.serviceimpl; import idea_dao.UsersDao; import idea_dao.impl.UserDaoImpl; import idea_entity.Users; import idea_service.UserService; import java.util.List; /** * Created by YYJ on 2017/11/3. */ public class UserServiceimpl implements UserService { @Override public List<Users> findall() { UsersDao usersDao = new UserDaoImpl(); return usersDao.findall(); } }
package com.itheima.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //判断session中是否存储有用户信息 Object login_user = request.getSession().getAttribute("login_user"); //如果login_user不为null,表明已经登录过了 if (login_user != null) { //放行 return true; } else { //还没有登陆 response.sendRedirect(request.getContextPath() + "/jsp/login.jsp"); return false; } } }
package com.quickly.module.mvp; import android.view.View; import com.quickly.module.mvp.base.MvpBaseFragment; import java.util.List; import me.drakeet.multitype.MultiTypeAdapter; public class NewsArticleFragment extends MvpBaseFragment implements NewsArticleContract.View{ private NewsArticleContract.Presenter mPresenter; private MultiTypeAdapter mAdapter; public static NewsArticleFragment newInstance(){ return new NewsArticleFragment(); } @Override protected int attachLayoutId() { return 0; } @Override protected void initView(View view) { } @Override protected void initData() { mPresenter.loadData(); } @Override public void showLoading() { } @Override public void refreshUIByData(List<?> data) { mAdapter.setItems(data); } @Override public void showError() { } @Override public void setPresenter(NewsArticleContract.Presenter presenter) { this.mPresenter = presenter; } @Override public boolean isActive() { return isAdded(); } }
package com.example.demo.service; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.entity.Employee; import com.example.demo.repo.DemoRepo; @Service public class DemoService { @Autowired private DemoRepo demoRepo; public Employee saveDate(Employee emp) { return demoRepo.save(emp); } public Optional<Employee> getDate(int id) { return demoRepo.findById(id); } }
/* * Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package main.java.fr.ericlab.sondy.algo.influenceanalysis; import java.util.Collection; import java.util.HashSet; import main.java.fr.ericlab.sondy.algo.Parameter; import main.java.fr.ericlab.sondy.core.app.AppParameters; import org.graphstream.graph.Edge; import org.graphstream.graph.Node; /** * * @author Adrien GUILLE, ERIC Lab, University of Lyon 2 * @email adrien.guille@univ-lyon2.fr */ public class SocialCapitalists extends InfluenceAnalysisMethod { double overlapThreshold = 0.74; double rankScale = 10; public SocialCapitalists(){ super(); parameters.add(new Parameter("overlapThreshold",overlapThreshold+"")); parameters.add(new Parameter("rankScale",rankScale+"")); } @Override public String getName() { return "Social Capitalists"; } @Override public String getCitation() { return "<li><b>Social Capitalists:</b> N. Dugué and A. Perez (2014) Social capitalists on Twitter: detection, evolution and behavioral analysis, Social Network Analysis and Mining, vol. 4(1) pp. 178-191</li>"; } @Override public String getDescription() { return "Identifies users who might be social capitalists based on neighborhood comparisons"; } @Override public void apply() { overlapThreshold = parameters.getParameterValue("overlapThreshold"); rankScale = parameters.getParameterValue("rankScale"); for (Node node : AppParameters.authorNetwork) { Collection<Edge> enteringEdgeSet = node.getEnteringEdgeSet(); HashSet<String> A = new HashSet<>(); for(Edge edge : enteringEdgeSet){ A.add(edge.getSourceNode().getId()); } Collection<Edge> leavingEdgeSet = node.getLeavingEdgeSet(); HashSet<String> B = new HashSet<>(); double intersection = 0; for(Edge edge : leavingEdgeSet){ B.add(edge.getTargetNode().getId()); if(A.contains(edge.getTargetNode().getId())){ intersection++; } } double overlap = intersection/Math.min(A.size(),B.size()); overlap = (overlap>overlapThreshold)?overlap *rankScale:0; rankedUsers.add(node.getId(),(int)(overlap)); } } }
package com.utils; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; /** * @文件名:ZJ_UploadUtils.java(新版) * @作用:不再依赖spring * @作者:张剑 * @创建时间:2014-9-1 * @更新时间:2014-12-25 */ public class ZJ_FileUtils { static Logger logger = Logger.getLogger(Object.class); private static String tempPath = null; // 临时文件目录 private static File tempPathFile = null; private static int sizeThreshold = 1024; private static int sizeMax = 4194304; private static HashMap<String, String> extMap = new HashMap<String, String>(); static { extMap.put("image", "gif,jpg,jpeg,png,bmp"); extMap.put("flash", "swf,flv"); extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb"); extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2"); tempPath = getTempFilePath(); tempPathFile = new File(tempPath); if (!tempPathFile.exists()) { tempPathFile.mkdirs(); } } /** * 文件随机命名 * * @return * @author 张剑 * @date 2014年12月5日 下午4:30:42 */ public static File changeFileName(File file) { if (null != file) { String fileName = file.getName(); String str = Long.toString(System.currentTimeMillis(), 36); String fileExt = ""; String newFileName = ""; if (fileName.contains(".")) { fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); newFileName = str + "_" + new Random().nextInt(1000) + "." + fileExt; } else { newFileName = str + "_" + new Random().nextInt(1000); } File newFile = new File(file.getParent() + File.separator + newFileName); file.renameTo(newFile); file = newFile; } return file; } /** * 修改文件名称为随机名称 * * @param fileName * @return * @author 张剑 * @date 2014年12月25日 下午1:12:36 */ public static String changeFileStrName(String fileName) { String fileExt = ""; String newFileName = ""; String str = Long.toString(System.currentTimeMillis(), 36) + "_" + new Random().nextInt(1000); if (fileName.contains(".")) { fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(); newFileName = str + "." + fileExt; } else { newFileName = str; } return newFileName; } /** * 获取日期 * * @return * @author 张剑 * @date 2014年9月1日 下午4:25:31 */ private static String getDateNow() { return new SimpleDateFormat("yyyyMMdd").format(new Date()); } /** * 获取相对路径 * * @param originalFName * 原文件名 * @param type * @return */ private static String getRelativeFile(String originalFName) { return getFileType(originalFName).concat(File.separator).concat(getDateNow()).concat(File.separator).concat(changeFileStrName(originalFName)); } /** * 关闭输入输出流 * * @param inputStream * @param outputStream */ private static void close(InputStream inputStream, OutputStream outputStream) { try { if (null != inputStream) { inputStream.close(); } if (null != outputStream) { outputStream.flush(); outputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } /** * 验证文件类型 * * @param fileName * @return */ private static boolean isAllowUpload(String fileName, String fileType) { if (null == fileType) { fileType = "image"; } String suffix = fileName.substring(fileName.lastIndexOf(".") + 1); if (Arrays.<String> asList(extMap.get(fileType).split(",")).contains(suffix)) { return true; } return false; } /** * 判断上传文件类型 * * @param items * @return */ private static Boolean isAllowUpload(FileItem item, String fileType) { if (!item.isFormField()) {// 如果是文件类型 String name = item.getName();// 获得文件名 包括路径啊 return isAllowUpload(name, fileType); } return false; } /** * 根据文件名获取文件类型 * * @param fileName * @return * @author 张剑 * @date 2014年9月1日 下午5:03:39 */ public static String getFileType(String fileName) { String suffix = getFileSuffix(fileName); if (null == suffix) { return "other"; } else { suffix = suffix.toLowerCase(); for (String key : extMap.keySet()) { if (Arrays.<String> asList(extMap.get(key).split(",")).contains(suffix)) { return key; } } return "other"; } } /** * 文件名是否为**后缀 * * @param fileName * @param suffix * @return * @author 张剑 * @date 2014年9月1日 下午5:45:04 */ public static boolean isSameSuffix(String fileName, String suffix) { if (null == fileName || "".equals(fileName) || null == suffix || "".equals(suffix)) { return false; } else if (fileName.trim().endsWith(suffix.trim())) { return true; } else { return false; } } /** * 获取文件后缀 * * @param fileName * @return * @author 张剑 * @date 2014年9月1日 下午3:25:27 */ public static String getFileSuffix(String fileName) { if (fileName.contains(".")) { return fileName.substring(fileName.lastIndexOf(".") + 1); } else { return ""; } } /** * 获取文件后缀 * * @param file * @return * @author 张剑 * @date 2014年9月1日 下午3:26:29 */ public static String getFileSuffix(File file) { String fileName = file.getName(); if (fileName.contains(".")) { return fileName.substring(fileName.lastIndexOf(".") + 1); } else { return ""; } } /** * 获取系统临时文件目录 * * @return * @author 张剑 * @date 2014年9月1日 下午4:10:34 */ public static String getTempFilePath() { return System.getProperty("java.io.tmpdir"); } /** * 获取结果中的第一条 * * @param uploadPathList * @return * @author 张剑 * @date 2014年9月1日 下午5:20:36 */ public static String getFirstPath(List<String> uploadPathList) { for (String string : uploadPathList) { return string; } return null; } /** * 获取url * * @param uploadURL * @param relativeFilePath * @return * @author 张剑 * @date 2014年9月1日 下午5:27:03 */ public static String getAllFileUrl(String uploadURL, String relativeFilePath) { if (uploadURL.endsWith("/")) { return uploadURL + relativeFilePath; } else { return uploadURL + "/" + relativeFilePath; } } /** * 获取path * * @param baseFilePath * @param relativeFilePath * @return * @author 张剑 * @date 2014年9月1日 下午5:27:54 */ public static String getAllFilePath(String baseFilePath, String relativeFilePath) { if (baseFilePath.endsWith("/")) { return baseFilePath + relativeFilePath; } else { return baseFilePath + File.separator + relativeFilePath; } } /** * 设置下载头,防止文件名乱码 * * @param request * @param response * @param fileName */ public static void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) { final String userAgent = request.getHeader("USER-AGENT"); logger.info(userAgent); try { String finalFileName = null; if (StringUtils.contains(userAgent, "Firefox")) {// google,火狐浏览器 finalFileName = new String(fileName.getBytes(), "ISO8859-1"); logger.info("火狐"); } else { finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器 logger.info("其他"); } response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");// 这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开 } catch (UnsupportedEncodingException e) { } } /** * 获取编码后的文件名防止乱码 * * @param request * @param response * @param fileName * @return * @author 张剑 * @date 2014年9月1日 下午5:37:16 */ public static String getFileName(HttpServletRequest request, HttpServletResponse response, String fileName) { final String userAgent = request.getHeader("USER-AGENT"); try { String finalFileName = null; if (StringUtils.contains(userAgent, "Firefox")) {// google,火狐浏览器 finalFileName = new String(fileName.getBytes(), "ISO8859-1"); } else { finalFileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器 } return finalFileName; } catch (UnsupportedEncodingException e) { return fileName; } } private static String getLocalIp() { try { String ip = InetAddress.getLocalHost().getHostAddress(); return ip; } catch (UnknownHostException e) { return "127.0.0.1"; } } private static String getLocalName() { try { String name = InetAddress.getLocalHost().getHostName(); return name; } catch (UnknownHostException e) { return ""; } } /** * 获取网站根url * * @param request * @return * @author 张剑 * @date 2014年12月3日 下午2:51:49 */ private static String getBaseUrl(HttpServletRequest request) { StringBuilder sb = new StringBuilder().append(request.getScheme()).append("://").append(request.getServerName()); if (request.getServerPort() != 80) { sb.append(":").append(request.getServerPort()); } sb.append(request.getContextPath()); sb.append("/"); String basePath = sb.toString(); return basePath; } /** * 获取网站根url(会把localhost或127.0.0.1换成真实ip) * * @param request * @return * @author 张剑 * @date 2014年12月3日 下午2:51:49 */ public static String getBaseFileUrl(HttpServletRequest request) { String baseUrl = getBaseUrl(request); String ip = getLocalIp(); if (baseUrl.contains("localhost")) { baseUrl = baseUrl.replaceFirst("localhost", ip); } else if (baseUrl.contains("127.0.0.1")) { baseUrl = baseUrl.replaceFirst("127.0.0.1", ip); } else if (baseUrl.contains(getLocalName().toLowerCase())) { baseUrl = baseUrl.replaceFirst(getLocalName().toLowerCase(), ip); } return baseUrl; } /** * 获取网站的根目录磁盘路径 * * @param request * @return * @author 张剑 * @date 2014年12月3日 下午3:23:48 */ public static String getBaseFilePath(HttpServletRequest request) { String baseFilePath = request.getSession().getServletContext().getRealPath("/"); if (!baseFilePath.endsWith(File.separator)) { baseFilePath += File.separator; } return baseFilePath; } /** * 文件上传 * * @param file * @param type * @return * @throws Exception */ public static List<String> upload(HttpServletRequest request, String filedName, String baseFilePath, String baseFileUrl) throws Exception { String fileType = request.getParameter("dir"); List<String> uploadPathList = new ArrayList<String>(); // 检查输入请求是否为multipart表单数据。 boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(sizeThreshold); // 设置缓冲区大小,这里是4kb factory.setRepository(tempPathFile);// 设置缓冲区目录 ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8");// 解决文件乱码问题 upload.setSizeMax(sizeMax);// 设置最大文件尺寸 List<FileItem> items = null; try { items = upload.parseRequest(request); } catch (Exception e) { throw new Exception("文件太大了"); } Iterator<FileItem> itr = items.iterator();// 所有的表单项 // 保存文件 while (itr.hasNext()) { FileItem item = (FileItem) itr.next();// 循环获得每个表单项 // 判断是表单字段还是file if (item.isFormField()) { continue; } String name = item.getName(); if (null != name && name.equals("")) { throw new Exception("请选择文件"); } if (isAllowUpload(item, fileType)) {// 如果允许上传 String itemFieldName = item.getFieldName(); if (name != null) { String relativeFilePath = getRelativeFile(name); if (null == filedName) { File savedFile = new File(baseFilePath + relativeFilePath); if (!savedFile.getParentFile().exists()) { savedFile.getParentFile().mkdirs(); } try { item.write(savedFile); } catch (Exception e) { throw new Exception("文件不能写入"); } uploadPathList.add(baseFileUrl + relativeFilePath.replaceAll("\\\\", "/")); } else if (filedName.equals(itemFieldName)) { File savedFile = new File(baseFilePath + relativeFilePath); if (!savedFile.getParentFile().exists()) { savedFile.getParentFile().mkdirs(); } try { item.write(savedFile); } catch (Exception e) { throw new Exception("文件不能写入"); } uploadPathList.add(baseFileUrl + relativeFilePath.replaceAll("\\\\", "/")); } } } else { throw new Exception("只允许上传" + extMap.get(fileType) + "格式的文件"); } } } else { throw new Exception("表单的enctype有误"); } return uploadPathList; } /** * 上传文件 * * @param request * @return * @author 张剑 * @throws Exception * @date 2014年9月1日 下午5:10:32 */ public static List<String> upload(HttpServletRequest request) throws Exception { return upload(request, null, getBaseFilePath(request).concat("upload").concat(File.separator), getBaseFileUrl(request).concat("upload").concat("/")); } /** * 下载网站所在服务器的文件 * * @param path * @param response * @return * @throws IOException */ public static HttpServletResponse download(String path, HttpServletRequest request, HttpServletResponse response) throws IOException { InputStream inputStream = null; OutputStream outputStream = null; try { // path是指欲下载的文件的路径。 File file = new File(path); // 取得文件名。 String filename = file.getName(); // 以流的形式下载文件。 inputStream = new FileInputStream(path); // 清空response response.reset(); // 设置response的Header setFileDownloadHeader(request, response, filename); response.addHeader("Content-Length", "" + file.length()); outputStream = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); int byteLength = 0; byte[] buffer = new byte[1024]; while ((byteLength = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, byteLength); } } finally { close(inputStream, outputStream); } return response; } /** * 下载网络文件 * * @param fileURL * @param response * @return * @throws IOException */ public static HttpServletResponse downloadNet(String fileURL, HttpServletRequest request, HttpServletResponse response) throws IOException { InputStream inputStream = null; OutputStream outputStream = null; String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1); try { URL url = new URL(fileURL); URLConnection conn = url.openConnection(); inputStream = conn.getInputStream(); // 清空response response.reset(); // 设置response的Header setFileDownloadHeader(request, response, fileName); outputStream = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); int byteLength = 0; byte[] buffer = new byte[1204]; while ((byteLength = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, byteLength); } } finally { close(inputStream, outputStream); } return response; } /** * 打开网站所在服务器的文件 * * @param filePath * @param response * @throws IOException */ public static void open(String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException { InputStream inputStream = null; OutputStream outputStream = null; try { File f = new File(filePath); if (!f.exists()) { response.sendError(404, "File not found!"); return; } inputStream = new FileInputStream(f); response.reset(); // 非常重要 URL u = new URL("file:///" + filePath); response.setContentType(u.openConnection().getContentType()); response.setHeader("Content-Disposition", "inline; filename=" + getFileName(request, response, f.getName())); // 文件名应该编码成UTF-8 byte[] buf = new byte[1024]; int byteLength = 0; outputStream = response.getOutputStream(); while ((byteLength = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, byteLength); } } finally { close(inputStream, outputStream); } } /** * 打开网络文件 * * @param fileURL * @param response * @throws IOException */ public static void openNet(String fileURL, HttpServletRequest request, HttpServletResponse response) throws IOException { String fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1); InputStream inputStream = null; OutputStream outputStream = null; try { URL url = new URL(fileURL); URLConnection conn = url.openConnection(); inputStream = conn.getInputStream(); response.reset(); // 非常重要 response.setContentType(url.openConnection().getContentType()); response.setHeader("Content-Disposition", "inline; filename=" + getFileName(request, response, fileName)); byte[] buf = new byte[1024]; int byteLength = 0; outputStream = response.getOutputStream(); while ((byteLength = inputStream.read(buf)) > 0) { outputStream.write(buf, 0, byteLength); } } finally { close(inputStream, outputStream); } } }
package com.onightperson.hearken.viewworkprinciple.toolbar; import android.app.Activity; import android.os.Bundle; import android.support.design.widget.BaseTransientBottomBar; import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.onightperson.hearken.R; /** * Created by liubaozhu on 17/3/10. */ public class CoordinatorActivity extends Activity implements View.OnClickListener { private Button mDoAnythingBtn; private Button mShowSnackBarBtn; private CoordinatorLayout mCoordinatorLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_coordinator_appbar_layout); // mCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout); // mShowSnackBarBtn = (Button) findViewById(R.id.show_snackbar); // mShowSnackBarBtn.setOnClickListener(this); // mDoAnythingBtn = (Button) findViewById(R.id.do_anything); // mDoAnythingBtn.setOnClickListener(this); } @Override public void onClick(View v) { if (v == mShowSnackBarBtn) { Snackbar.make(mCoordinatorLayout, "This is a simple Snacker", Snackbar.LENGTH_LONG) .addCallback(new BaseTransientBottomBar.BaseCallback<Snackbar>() { @Override public void onDismissed(Snackbar transientBottomBar, int event) { super.onDismissed(transientBottomBar, event); Toast.makeText(CoordinatorActivity.this, "Snackbar消失了", Toast.LENGTH_SHORT).show(); } }) .setAction("Close", new View.OnClickListener() { @Override public void onClick(View v) { //nothing } }).show(); } else if (v == mDoAnythingBtn) { Toast.makeText(this, "do nothing", Toast.LENGTH_SHORT).show(); } } }
package usantatecla.draughts.models; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; public class StateTest { private StateBuilder stateBuilder; @Before public void setUp() { this.stateBuilder = new StateBuilder(); } @Test public void shouldStartWithInitialState() { State state = stateBuilder.build(); assertEquals(StateValue.INITIAL, state.getValueState()); } @Test public void shouldReturnCorrectStateWhenNextState() { State state = stateBuilder.build(); state.next(); assertEquals(StateValue.IN_GAME, state.getValueState()); state.next(); assertEquals(StateValue.FINAL, state.getValueState()); state.next(); assertEquals(StateValue.EXIT, state.getValueState()); } @Test(expected = AssertionError.class) public void shouldFailWhenNextInExitState() { State state = stateBuilder .withStateValue(StateValue.EXIT) .build(); state.next(); } @Test public void shouldReturnToInitialWhenReset() { State state = stateBuilder .withStateValue(StateValue.IN_GAME) .build(); state.reset(); assertEquals(StateValue.INITIAL, state.getValueState()); } }
package me.gaigeshen.fastdfs.client.connection; /** * 结果数据处理器,用于处理连接返回的数据 * * @author gaigeshen */ @FunctionalInterface public interface ResultHandler { /** * 处理结果数据,然后返回是否需要继续接收新数据 * * @param result 结果数据 * @return 如果本次的结果数据只是部分数据的话,需要指明要继续处理 */ boolean handle(byte[] result); }
package com.soft1841.thread; import org.omg.PortableServer.THREAD_POLICY_ID; import javax.swing.*; import java.awt.*; import java.util.Random; /** * 线程学习 绘制彩色线段 * @author 黄敬理 * 2019.04.10 */ public class DrawLineThread implements Runnable { int x = 100; int y = 100; private JFrame frame; private Color[] colors = {Color.ORANGE,Color.ORANGE,Color.ORANGE,Color.ORANGE,Color.GREEN,Color.GREEN, Color.GREEN,Color.GREEN,Color.ORANGE,Color.RED,Color.RED,Color.RED,Color.RED,Color.RED }; public void setFrame(JFrame frame){ this.frame = frame; } @Override public void run() { Random random = new Random(); while (true){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } Graphics graphics = frame.getGraphics(); Graphics2D g2d=(Graphics2D)graphics; Stroke stroke=new BasicStroke(5.0f);//设置线宽为3.0 g2d.setStroke(stroke); graphics.setColor(colors[random.nextInt(colors.length)]); graphics.drawLine(x,x,y,500); y += 50; if (y>=1000){ break; } } } }
package People; public class Experiencer extends Candidate { protected int expYear; protected String proSkill; public Experiencer( String iD, String name, int date, String address, String phoneNumber, String email, int type, int expYear, String proSkill ) { super(iD, name, date, address, phoneNumber, email, type); this.expYear = expYear; this.proSkill = proSkill; } public void setExpYear( int expYear ) { this.expYear = expYear; } public void setProSkill( String proSkill ) { this.proSkill = proSkill; } @Override public String toString() { return iD+";"+ name+";"+date+";"+address+";"+phoneNumber+";"+email+";"+type +";"+expYear+";"+proSkill; } }
package java二.Exception; class Math{ public static int div(int x,int y)throws Exception{ int res = 0; System.out.println("*********开始除法计算****"); res = x/ y ; //当除数为0,出现异常,向上抛 System.out.println("*****除法计算结束****"); return res ; } } public class EDemo { public static void main (String[] args)throws Exception { try{ System.out.println(Math.div(10,0)); }catch (Exception e){ e.printStackTrace(); } } }
package com.eussi._08_certificate; import com.eussi._08_certificate.base.PEMCoder; import junit.framework.Assert; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.junit.Before; import org.junit.Test; import javax.crypto.Cipher; import java.security.*; /** * Created by wangxueming on 2019/6/23. */ public class _05_PemFileOpertion { /** .DER .CER,文件是二进制格式,只保存证书,不保存私钥。 .PEM,一般是文本格式,可保存证书,可保存私钥。 .CRT,可以是二进制格式,可以是文本格式,与 .DER 格式相同,不保存私钥。 .PFX .P12,二进制格式,同时包含证书和私钥,一般有密码保护。 .JKS,二进制格式,同时包含证书和私钥,一般有密码保护。 DER 该格式是二进制文件内容,Java 和 Windows 服务器偏向于使用这种编码格式。 OpenSSL 查看 openssl x509 -in certificate.der -inform der -text -noout 转换为 PEM: openssl x509 -in cert.crt -inform der -outform pem -out cert.pem PEM Privacy Enhanced Mail,一般为文本格式,以 -----BEGIN... 开头,以 -----END... 结尾。中间的内容是 BASE64 编码。这种格式可以保存证书和私钥,有时我们也把PEM 格式的私钥的后缀改为 .key 以区别证书与私钥。具体你可以看文件的内容。 这种格式常用于 Apache 和 Nginx 服务器。 OpenSSL 查看: openssl x509 -in certificate.pem -text -noout 转换为 DER: openssl x509 -in cert.crt -outform der -out cert.der CRT Certificate 的简称,有可能是 PEM 编码格式,也有可能是 DER 编码格式。如何查看请参考前两种格式。 PFX Predecessor of PKCS#12,这种格式是二进制格式,且证书和私钥存在一个 PFX 文件中。一般用于 Windows 上的 IIS 服务器。改格式的文件一般会有一个密码用于保证私钥的安全。 OpenSSL 查看: openssl pkcs12 -in for-iis.pfx 转换为 PEM: openssl pkcs12 -in for-iis.pfx -out for-iis.pem -nodes JKS Java Key Storage,很容易知道这是 JAVA 的专属格式,利用 JAVA 的一个叫 keytool 的工具可以进行格式转换。一般用于 Tomcat 服务器。 # 操作 [root@app2 TestCa]# openssl pkcs12 -in certs/ca.p12 -out certs/ca.pem -nodes Enter Import Password: MAC verified OK [root@app2 TestCa]# openssl pkcs12 -in certs/server.p12 -out certs/server.pem -nodes Enter Import Password: MAC verified OK [root@app2 TestCa]# openssl pkcs12 -in certs/client.p12 -out certs/client.pem -nodes Enter Import Password: MAC verified OK */ private String passwd = "123456"; private String pemFilePath = "src/test/resources/_08_certificate/openssl/TestCa/private/ca.key.pem"; private PublicKey publicKey; private PrivateKey privateKey; private byte[] data; @Before public void intiKeyPair() { data = "PEM".getBytes(); //若未在java.security中配置BC,添加以下代码 Security.addProvider(new BouncyCastleProvider()); KeyPair kp; try { kp = PEMCoder.readKeyPair(pemFilePath, passwd.toCharArray()); publicKey = kp.getPublic(); privateKey = kp.getPrivate(); } catch (Exception e) { e.printStackTrace(); } } /** * 公钥加密,私钥解密 */ @Test public void encryptAndDecrypt() { try { //私钥加密 Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encrypt = cipher.doFinal(data); //公钥加密 cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decrypt = cipher.doFinal(encrypt); System.out.println(new String(decrypt)); }catch(Exception e) { e.printStackTrace(); } } /** * 私钥加密,公钥解密 */ @Test public void encryptAndDecrypt2() { try { //私钥加密 Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privateKey); byte[] encrypt = cipher.doFinal(data); //公钥加密 cipher.init(Cipher.DECRYPT_MODE, publicKey); byte[] decrypt = cipher.doFinal(encrypt); System.out.println(new String(decrypt)); }catch(Exception e) { e.printStackTrace(); } } @Test public void sign() { try { Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); signature.update(data); byte[] sign = signature.sign(); //使用公钥对签名校验 signature.initVerify(publicKey); signature.update(data); //验证 boolean status = signature.verify(sign); System.out.println(status); }catch(Exception e) { e.printStackTrace(); } } }
package essenceentity; import com.google.common.base.Objects; /** * Created by max on 03/12/14. */ public abstract class AbstractEntity<I> implements Entity<I>{ @Override public final boolean identityEquals(Entity<?> other) { if(this.getId() == null){ return false; } return getId().equals(other.getId()); } @Override public final int identityHashCode() { return Objects.hashCode(this.getId()); } @Override public final boolean equals(final Object obj) { if(this == obj){ return true; } if((obj == null) || (getClass() != obj.getClass())){ return false; } return identityEquals((Entity<?>) obj); } @Override public final int hashCode(){ return identityHashCode(); } @Override public String toString(){ return getClass().getSimpleName() + ": " + this.getId(); } }
package food.codi; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.WindowManager; import android.widget.ProgressBar; import food.codi.publico.PrefUtil; /** * By: El Bryant */ public class Splash extends AppCompatActivity { ProgressBar pbSplash; Handler handler; PrefUtil prefUtil; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); pbSplash = (ProgressBar) findViewById(R.id.pbSplash); prefUtil = new PrefUtil(this); handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { if (prefUtil.getStringValue(PrefUtil.LOGIN_STATUS).equals("1")) { Intent intent = new Intent(Splash.this, CategoriaActivity.class); startActivity(intent); intent.putExtra("nombre", prefUtil.getStringValue("nombre")); finish(); } else { Intent intent = new Intent(Splash.this, AccesoActivity.class); startActivity(intent); finish(); } } }, 3000); } }
package com.example.the_season_of_the_song; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import androidx.viewpager.widget.ViewPager; import java.util.ArrayList; public class SelectMenu extends AppCompatActivity { ViewPager pager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.select_menu); pager = (ViewPager) findViewById(R.id.activity_pager); pager.setOffscreenPageLimit(2); Intent intent = getIntent(); int year = intent.getIntExtra("birthYear",0); //번들객체 생성, year값 저장 Bundle bundle = new Bundle(); bundle.putInt("birthYear", year); //fragment1로 번들 전달 FunctionPagerAdapter adapter = new FunctionPagerAdapter(getSupportFragmentManager()); FindYearFragment findYearFragment = new FindYearFragment(); adapter.addItem(findYearFragment); findYearFragment.setArguments(bundle); FindSongFragment findSongFragment = new FindSongFragment(); adapter.addItem(findSongFragment); findSongFragment.setArguments(bundle); pager.setAdapter(adapter); } class FunctionPagerAdapter extends FragmentStatePagerAdapter { ArrayList<Fragment> items; public FunctionPagerAdapter(FragmentManager fm) { super(fm); this.items = new ArrayList<Fragment>(); } public void addItem(Fragment item) { items.add(item); } @NonNull @Override public Fragment getItem(int position) { return items.get(position); } @Override public int getCount() { return items.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return "페이지 " + position; } } }
package com.github.andrelugomes.v1.model; import com.google.gson.Gson; import com.google.gson.JsonObject; public class Merchant { private JsonObject data; private String op; private String id; public Merchant(String merchantString) { Gson gson = new Gson(); Merchant merchant = gson.fromJson(merchantString, Merchant.class); this.data = merchant.data; this.op = merchant.op; this.id = merchant.id; } public String getData() { Gson gson = new Gson(); return gson.toJson(data); } public void setData(JsonObject data) { this.data = data; } public String getOp() { return op; } public void setOp(String op) { this.op = op; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
package com.fun.driven.development.fun.unified.payments.vault.service; /** * PCI Strong Cryptography definition: * Cryptography based on industry-tested and accepted algorithms, along with key lengths that provide a minimum of 112-bits of effective key * strength and proper key-management practices. Cryptography is a method to protect data and includes both encryption (which is reversible) and * hashing (which is “one way”; that is, not reversible). See Hashing. * At the time of publication, examples of industry-tested and accepted standards and algorithms include AES (128 bits and higher), TDES/TDEA * (triple-length keys), RSA (2048 bits and higher), ECC (224 bits and higher), and DSA/D-H (2048/224 bits and higher). See the current version of * NIST Special Publication 800-57 Part 1 (http://csrc.nist.gov/publications/) for more guidance on cryptographic key strengths and algorithms. */ public interface StrongCryptography { String encrypt(String unencryptedString); String decrypt(String encryptedString); }
package loecraftpack.enums; public enum LivingEventId { LIVING_FALL, LIVING_ATTACK, LIVING_HURT, LIVING_DEATH, LIVING_DEATH_PRE, ENTITY_ITEM_PICKUP, PLAYER_SLEEP_IN_BED, ENTITY_INTERACT, ATTACK_ENTITY, USE_HOE, BONEMEAL, FILL_BUCKET, PLAYER_DESTROY_ITEM, PLAYER_FLYABLE_FALL, PLAYER_DROPS, ARROW_LOOSE, ARROW_NOCK, ENDER_TELEPORT, LIVING_DROPS, LIVING_SET_ATTACK_TARGET, LIVING_SPAWN, }
package example.parser; import example.model.XmlElement; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import java.io.File; import java.io.IOException; import java.util.LinkedList; import org.xml.sax.Attributes; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class SaxParser implements Parser { @Override public XmlElement parse(File xmlFile) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); Handler handler = new Handler(); parser.parse(xmlFile, handler); return handler.root; } private class Handler extends DefaultHandler { private XmlElement root; XmlElement xmlElement; LinkedList<XmlElement> parents = new LinkedList<>(); @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { xmlElement = new XmlElement(qName); parents.add(xmlElement); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { XmlElement xmlElement = parents.pollLast(); if (parents.isEmpty()) { root = xmlElement; } else { parents.peekLast().addChild(xmlElement); } } } }
package net.tascalate.async.tools.core; import java.io.PrintWriter; import java.io.StringWriter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import org.objectweb.asm.util.TraceClassVisitor; /** * @author */ class BytecodeTraceUtil { public static String toString(byte[] clazz) { StringWriter strOut = new StringWriter(); PrintWriter out = new PrintWriter(strOut); ClassVisitor cv = new TraceClassVisitor(out); ClassReader cr = new ClassReader(clazz); cr.accept(cv, Opcodes.ASM4); strOut.flush(); return strOut.toString(); } public static String toString(ClassNode cn) { StringWriter strOut = new StringWriter(); PrintWriter out = new PrintWriter(strOut); cn.accept(new TraceClassVisitor(out)); strOut.flush(); return strOut.toString(); } public static String toString(MethodNode mn) { // StringWriter strOut = new StringWriter(); // PrintWriter out = new PrintWriter(strOut); // TraceMethodVisitor tmv = new TraceMethodVisitor(out); // // mn.accept(tmv); // // strOut.flush(); // return strOut.toString(); return mn.toString(); } public static String toString(VarInsnNode vin) { // return AbstractVisitor.OPCODES[vin.getOpcode()] + " " + vin.var; return vin.getOpcode() + " " + vin.var; } public static String toString(MethodInsnNode min) { // return AbstractVisitor.OPCODES[min.getOpcode()] + " " + min.owner + " // " + min.name + " " + min.desc; return min.getOpcode() + " " + min.owner + " " + min.name + " " + min.desc; } }
package com.example.van.baotuan.model.network; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.Request; import okhttp3.Response; /** * 拦截器,用于为网络请求添加公共参数 * Created by Van on 2016/8/8. */ public class MyInterceptor implements Interceptor{ public MyInterceptor() { } @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Request.Builder requestBuilder = originalRequest.newBuilder() .header("Accept", "application/json") .header("access-token",NetConn.getCookie()) .method(originalRequest.method(), originalRequest.body()); Request request = requestBuilder.build(); return chain.proceed(request); } }
package mb.tianxundai.com.toptoken.view; /** * @author txd_dbb * @emil 15810277571@163.com * create at 2018/10/1313:12 * description: */ public class Config { //测试 // public static String BASE_URL="http://47.52.161.84:8081/Api"; // public static String BASE_URL1="http://47.52.161.84:8081/"; //商城测试 public static String BASE_MALL_URL = "http://47.244.46.125:5002/2.0/"; //正式 public static String BASE_URL = "http://47.244.46.125/Api"; public static String BASE_URL1 = "http://47.244.46.125/"; //天津测试服务器 public static String BASE_URL12 = "http://47.52.161.84:8081/Api"; //TopTest本地测试环境 public static String BASE_URL14 = "http://47.52.161.84:8085/Api"; //toptoken 正式服务器 public static String BASE_URL13 = "https://server.toptoken.world/Api"; public static String BASE_URL_PROD = "https://server.toptoken.world/"; }
package alien4cloud.deployment; import java.util.Map; import javax.annotation.Resource; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.model.deployment.Deployment; import alien4cloud.model.deployment.DeploymentTopology; import alien4cloud.orchestrators.plugin.IOrchestratorPlugin; import alien4cloud.paas.IPaaSCallback; import alien4cloud.paas.OrchestratorPluginService; import alien4cloud.paas.model.PaaSDeploymentContext; /** * Manages topology workflows. */ @Service @Slf4j public class WorkflowExecutionService { @Inject private OrchestratorPluginService orchestratorPluginService; @Inject private DeploymentService deploymentService; @Resource(name = "alien-es-dao") private IGenericSearchDAO alienDao; @Inject private DeploymentRuntimeStateService deploymentRuntimeStateService; /** * Launch a given workflow. */ public synchronized void launchWorkflow(String applicationEnvironmentId, String workflowName, Map<String, Object> params, IPaaSCallback<?> iPaaSCallback) { Deployment deployment = deploymentService.getActiveDeploymentOrFail(applicationEnvironmentId); DeploymentTopology deploymentTopology = deploymentRuntimeStateService.getRuntimeTopologyFromEnvironment(deployment.getEnvironmentId()); IOrchestratorPlugin orchestratorPlugin = orchestratorPluginService.getOrFail(deployment.getOrchestratorId()); PaaSDeploymentContext deploymentContext = new PaaSDeploymentContext(deployment, deploymentTopology); orchestratorPlugin.launchWorkflow(deploymentContext, workflowName, params, iPaaSCallback); } }
package marks.whoneeds.gui.setups; import javafx.scene.input.KeyCode; import marks.whoneeds.gui.GUIHandler; import marks.whoneeds.gui.resources.Images; import marks.whoneeds.gui.sprites.SpriteBackground; public class SetupHowToPlay extends Setup { public SetupHowToPlay() { super(); this.addSprite(new SpriteBackground(Images.HOWTOPLAY.get())); } @Override public void onClick(double mouseX, double mouseY) { GUIHandler.setSetup(new SetupTitle()); } @Override public void update(double mouseX, double mouseY, boolean mousePressed, int frameSpeed) {} @Override public void onKeyPress(KeyCode key) {} }
package lab411.android2pc.loadsharing; import java.net.Socket; public class DetectSocket { public static Socket socket; public static void set(Socket s) { socket = s; } }
package com.swapp.swboard.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.swapp.vo.MemberVO; @Controller public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); //회원가입 페이지 이동 @RequestMapping(value = "signUpForm", method = RequestMethod.GET) public void joinGET() { logger.info("회원가입 페이지 진입"); } //로그인 페이지 이동 @RequestMapping(value = "login", method = RequestMethod.GET) public void loginGET() { logger.info("로그인 페이지 진입"); } }
package com.example.android.liverpooltour; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; /** * ToDo: Add a Class Header Comment */ public class FragmentAdapter extends FragmentPagerAdapter { private String[] INDEX_TITLE = {"ATTRACTION","PARKS","HISTORICAL"}; private int INDEX_NUMBER = 3; public FragmentAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return INDEX_NUMBER; } @Override public Fragment getItem(int position) { if (position == 0) return new AttractionsFragment(); else if (position == 1) return new GreenSpaceFragment(); else return new HistoricalFragment(); } // Returns the page title for the top indicator @Override public CharSequence getPageTitle(int position) { return INDEX_TITLE[position]; } }
package answers; import org.junit.*; import org.junit.rules.ExpectedException; public class AccountTest { @Test public void withdraw500FromAccount_shouldBeAllowed() throws Exception { // Arrange - create a new account with a balance of 1000 Account account = new Account(1000); // Act - withdraw 500 account.withdraw(500); // Assert - check that the remaining balance is 500 Assert.assertEquals(500, account.getBalance()); } @Test public void deposit500ToAccount_shouldResultInCorrectBalance() { // Arrange - create a new account with a balance of 1000 Account account = new Account(1000); // Act - deposit 500 account.deposit(500); // Assert - check that the new balance is 1500 Assert.assertEquals(1500, account.getBalance()); } @Rule public ExpectedException exceptionRule = ExpectedException.none(); @Test public void withdraw1100FromAccount_shouldThrowException() throws Exception { exceptionRule.expect(Exception.class); exceptionRule.expectMessage("Insufficient funds: could not withdraw 1100 from this account"); // Arrange - create a new account with a balance of 1000 Account account = new Account(1000); // Act - withdraw 1100 account.withdraw(1100); // Assert // TODO: make this test pass by specifying that you expect an exception // TODO: bonus points for also asserting that the Exception message is "Insufficient funds: could not withdraw 1100 from this account" // See https://www.baeldung.com/junit-assert-exception, bullet point 3. for an example } }
package homework5.api; public interface ISpliteratorText { String[] splitByRegEx(String text); String[] splitByIndexOf(String text); }
package db.jdbc; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; /** * The Class tester. */ public class Tester { /** * The main method. * * @param args the arguments * @throws IllegalAccessException * @throws InstantiationException */ public static void main(final String[] args) throws InstantiationException, IllegalAccessException { SqlFormatter formatter = new OracleSqlFormatter(); Object o = new java.sql.Date(new java.util.Date().getTime()); try { System.out.println("date=" + formatter.format(o)); o = new Long(198); System.out.println("Long=" + formatter.format(o)); o = new Boolean(true); System.out.println("Boolean=" + formatter.format(o)); } catch (SQLException e) { e.printStackTrace(); } // this goes in static debug class once, not individual classes StatementFactory.setDefaultDebug(DebugLevel.VERBOSE); StatementFactory.setDefaultFormatter(formatter); // test debuggable java.sql.Connection con = null; java.sql.PreparedStatement ps = null; java.sql.ResultSet rs = null; String databaseURL = "jdbc:oracle:thin:@grid.ngis-cville.com:1521:dev"; System.out.println(databaseURL); String user = "jacob_data"; String password = "jacob"; try { Class<Driver> c = (Class<Driver>) Class.forName("oracle.jdbc.driver.OracleDriver"); Driver driver = c.newInstance(); // instantiate Oracle driver DriverManager.registerDriver(driver); // register Oracle driver con = DriverManager.getConnection(databaseURL, user, password); System.out.println("Connection established."); String sql = "select * from APPLICATION_LOGS where LOG_TYPE = ?"; ps = StatementFactory.getStatement(con, sql); ps.setString(1, "WARNING"); System.out.println(ps.toString()); rs = ps.executeQuery(); while (rs.next()) System.out.println(" > DATE = " + rs.getDate("LOG_DATE")); } catch (java.lang.ClassNotFoundException e) { e.printStackTrace(); } catch (java.sql.SQLException se) { se.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); if (con != null && !con.isClosed()) con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.spring.integration.rest; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller @Slf4j @AllArgsConstructor public class IntegrationController { private IntegrationServiceImpl integrationService; @GetMapping("/api/send") @ResponseBody public String sendMessage(){ integrationService.sendMessage(); return "API invoked"; } }
public class Lesson_14_Activity_One { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("Enter a number:"); int x = scan.nextInt(); if (x < 5 || x > 76) { System.out.println("True"); } else { System.out.println("False"); } } }
package Tests.JunitTests; import org.junit.Test; import static Utils.ConstantsUtils.URL_BASE2; public class TestLoginJunit extends BaseClassJunit{ @Test public void loginSIte(){ System.out.println("Here we do the login"); driver.navigate().to(URL_BASE2 + "/customer/account/login"); } }
package net.awesomekorean.podo.lesson.lessons; import net.awesomekorean.podo.R; import java.io.Serializable; public class Lesson40 extends LessonInit_Lock implements Lesson, LessonItem, Serializable { private String lessonId = "L_40"; private String lessonTitle = "to do"; private String lessonSubTitle = "~(으)려고"; private Integer dayCount = 21; private String[] wordFront = {"월 / 달", "똑똑하다", "기억하다", "수업"}; private String[] wordBack = {"month", "smart", "remember", "lesson"}; private String[] wordPronunciation = {"-", "[똑또카다]", "[기어카다]", "-"}; private String[] sentenceFront = { "언제부터 배웠어요?", "한국어를 언제부터 배웠어요?", "3개월 배웠어요.", "3개월 정도 배웠어요.", "3개월 밖에 안 배웠어요?", "그런데 이렇게 잘해요?", "똑똑한 것 같아요.", "정말 똑똑한 것 같아요.", "수업 시간에 배운 것", "수업 시간에 배운 것을 기억하려고 ", "수업 시간에 배운 것을 기억하려고 매일 공부해요." }; private String[] sentenceBack = { "Since when did you learn", "Since when did you learn Korean?", "I've learned it for 3 months.", "I've learned it for about 3 months.", "You've learned it for only 3 months?", "But how come you do it so well like that?", "I think you are smart.", "I think you are so smart.", "What I've learned in the lesson", "To remember what I've learned in the lesson", "I study every day to remember what I've learned in the lesson." }; private String[] sentenceExplain = { "-", "-", "'월' : comes from Chinese character\n'달' : native Korean\n\nThere are 2 ways to count months.\n'3개월' [삼개월]\n'3달' [세달]\n\nDon't be confused that '3월'[삼월] means 'March'.", "If you use '정도' or '쯤' following after the word indicating quantity, it means 'about(approximately)'.", "When you want to say 'few', 'little', you can use '~밖에' and have to put negative form after.\n\nex)\n'~밖에 안~'\n'~밖에 못~'\n'~밖에 없다'", "You can use '이렇게' to express a big surprise.", "-", "-", "'배우다' -> '배우' + 'ㄴ 것' = '배운 것'", "When describing the intention or purpose, you can use '~(으)려고'.\n\n'기억하다' -> '기억하' + '려고' = '기억하려고'", "-" }; private String[] dialog = { "한국어를 언제부터 배웠어요?", "3개월 정도 배웠어요.", "와! 3개월 밖에 안 배웠어요?\n그런데 이렇게 잘해요?\n정말 똑똑한 것 같아요.", "아니에요.\n수업 시간에 배운 것을\n기억하려고 매일 공부해요." }; private int[] peopleImage = {R.drawable.male_b,R.drawable.female_p}; private int[] reviewId = {1,3,10}; @Override public String getLessonSubTitle() { return lessonSubTitle; } @Override public String getLessonId() { return lessonId; } @Override public String[] getWordFront() { return wordFront; } @Override public String[] getWordPronunciation() { return wordPronunciation; } @Override public String[] getSentenceFront() { return sentenceFront; } @Override public String[] getDialog() { return dialog; } @Override public int[] getPeopleImage() { return peopleImage; } @Override public String[] getWordBack() { return wordBack; } @Override public String[] getSentenceBack() { return sentenceBack; } @Override public String[] getSentenceExplain() { return sentenceExplain; } @Override public int[] getReviewId() { return reviewId; } // 레슨어뎁터 아이템 @Override public String getLessonTitle() { return lessonTitle; } @Override public Integer getDayCount() { return dayCount; } }
package br.com.wasys.gfin.cheqfast.cliente.model; /** * Created by pascke on 28/06/17. */ public class UploadModel { public String path; public UploadModel(String path) { this.path = path; } }
package com.android.wendler.wendlerandroid.main.contract; /** * Created by QiFeng on 7/11/17. */ public class EditContract { public interface Presenter{ public void saveClicked(); } public interface View{ public void showSavedToast(); } }
package com.uog.miller.s1707031_ct6039.servlets.users.child; import com.uog.miller.s1707031_ct6039.beans.ChildBean; import com.uog.miller.s1707031_ct6039.oracle.ChildConnections; import com.uog.miller.s1707031_ct6039.oracle.YearConnections; import java.io.IOException; import java.util.Map; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; /** * Action Servlet for Child Registration operations. */ @WebServlet(name = "ChildRegistration") public class ChildRegistration extends HttpServlet { static final Logger LOG = Logger.getLogger(ChildRegistration.class); //Child Registration form submit @Override public void doPost(HttpServletRequest request, HttpServletResponse response) { String firstname = request.getParameter("firstname"); String surname = request.getParameter("surname"); String email = request.getParameter("email"); String dob = request.getParameter("dob"); String address = request.getParameter("address-value"); String year = request.getParameter("year"); String pword = request.getParameter("pword"); String pwordConfirm = request.getParameter("pwordConfirm"); if (!pword.equals(pwordConfirm)) { //Error, JS has validated these should match! LOG.error("Passwords should have matched!"); //Redirect Back to Registration Page request.getSession(true).setAttribute("formErrors", "Passwords did not match despite passing checks. Please re-enter and try again"); request.getSession(true).removeAttribute("formSuccess"); try { addSessionAttributesForYear(request); response.sendRedirect(request.getContextPath() + "/jsp/users/child/childregistration.jsp"); } catch (IOException e) { LOG.error("Failure to redirect.", e); } } else { //Check user does not exist already boolean userExists = checkUserExists(email); if(userExists) { LOG.error("Registration of User: " + email + " failed, as account already exists"); //Redirect Back to Registration Page request.getSession(true).setAttribute("formErrors", "There is already an account linked with:" + email); request.getSession(true).removeAttribute("formSuccess"); try { addSessionAttributesForYear(request); response.sendRedirect(request.getContextPath() + "/jsp/users/child/childregistration.jsp"); } catch (IOException e) { LOG.error("Failure to redirect.", e); } } else { //Populate Bean for Registration ChildBean bean = new ChildBean(); bean.setFirstname(firstname); bean.setSurname(surname); bean.setEmail(email.toLowerCase()); bean.setDOB(dob); bean.setAddress(address); bean.setYear(year); bean.setPword(pword); //Get 'Default' account settings for new user bean.setEmailForHomework(true); bean.setEmailForCalendar(true); bean.setEmailForProfile(true); attemptChildRegistration(request, response, bean); } } } private void attemptChildRegistration(HttpServletRequest request, HttpServletResponse response, ChildBean bean) { LOG.debug("Account sane to be created, attempting to register to DB"); //Use ChildBean to create an account and add to DB ChildConnections childConnections = new ChildConnections(); boolean registerSuccess = childConnections.registerChild(bean); if(registerSuccess) { //Redirect happy path, remove errors (if any) request.getSession(true).removeAttribute("formErrors"); request.getSession(true).setAttribute("formSuccess", "Account created successfully."); try { response.sendRedirect(request.getContextPath() + "/jsp/users/child/childlogin.jsp"); } catch (IOException e) { LOG.error("Failure to redirect.", e); } } else { LOG.error("Unknown error occurred whilst attempting to create new User: " + bean.getEmail()); //Redirect Back to Registration Page request.getSession(true).setAttribute("formErrors", "Unknown Error. The account was not created."); request.getSession(true).removeAttribute("formSuccess"); try { addSessionAttributesForYear(request); response.sendRedirect(request.getContextPath() + "/jsp/users/child/childregistration.jsp"); } catch (IOException e) { LOG.error("Failure to redirect.", e); } } } private boolean checkUserExists(String email) { //Check DB for account linked to email ChildConnections childConnections = new ChildConnections(); return childConnections.checkUserExists(email); } //Allows Registration forms/etc to populate Year select dropdown private void addSessionAttributesForYear(HttpServletRequest request) { Map<String, String> allYears; YearConnections yearConnections = new YearConnections(); allYears = yearConnections.getAllClassYears(); if(allYears != null) { request.getSession(true).setAttribute("allYears", allYears); } } }
package cn.tedu.tickets; /*需求:设计多线程编程模型,4个窗口共计售票100张 * 本方案使用多线程编程方案1,继承Thread类的方式来完成*/ public class TestThread { public static void main(String[] args) { //5.创建多个线程对象 TicketThread t1 = new TicketThread(); TicketThread t2 = new TicketThread(); TicketThread t3 = new TicketThread(); TicketThread t4 = new TicketThread(); //6.以多线程的方式启动 t1.start(); t2.start(); t3.start(); t4.start(); } } //1.自定义多线程售票类,继承Thread class TicketThread extends Thread { //3.定义变量,保存要售卖的票数 /*问题:4个线程对象共计售票400张,原因是创建了4次对象,各自操作各自的成员变量 * 解决:让所有对象共享同一个数据,票数需要设置为静态*/ static int tickets = 100; @Override public void run() { //4.1循环卖票 while (true) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getName() + "=" + tickets--); if (tickets <= 0) break;//注意,死循环一定要设置出口 } } }
package cn.itcast.core.service; import cn.itcast.core.dao.seller.SellerDao; import cn.itcast.core.pojo.entity.PageResult; import cn.itcast.core.pojo.seller.Seller; import cn.itcast.core.pojo.seller.SellerQuery; import com.alibaba.dubbo.config.annotation.Service; import com.github.pagehelper.Page; import com.github.pagehelper.PageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; @Service @Transactional public class SellerServiceImpl implements SellerService { @Autowired private SellerDao sellerDao; @Override public void add(Seller seller) { //密码加密 // BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); // String password = passwordEncoder.encode(seller.getPassword()); // seller.setPassword(password); //刚注册, 默认卖家的状态为0, 未审核 seller.setStatus("0"); //创建时间 seller.setCreateTime(new Date()); sellerDao.insertSelective(seller); } @Override public PageResult findPage(Seller seller, Integer page, Integer rows) { SellerQuery query = new SellerQuery(); SellerQuery.Criteria criteria = query.createCriteria(); if (seller != null) { if (seller.getStatus() != null && !"".equals(seller.getStatus())) { criteria.andStatusEqualTo(seller.getStatus()); } if (seller.getName() != null && !"".equals(seller.getName())) { criteria.andNameLike("%"+seller.getName()+"%"); } if (seller.getNickName() != null && !"".equals(seller.getNickName())) { criteria.andNickNameLike("%"+seller.getNickName()+"%"); } } PageHelper.startPage(page, rows); Page<Seller> sellerList = (Page<Seller>)sellerDao.selectByExample(query); return new PageResult(sellerList.getTotal(), sellerList.getResult()); } @Override public Seller findOne(String id) { return sellerDao.selectByPrimaryKey(id); } @Override public void updateStatus(String sellerId, String status) { Seller seller = new Seller(); seller.setSellerId(sellerId); seller.setStatus(status); sellerDao.updateByPrimaryKeySelective(seller); } }
package com.blockgame.crash; import com.blockgame.crash.model.MemberVo; import com.blockgame.crash.model.RecordVo; import com.blockgame.crash.repository.MemberRepository; import com.blockgame.crash.repository.RecordRepository; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import java.util.List; import javax.transaction.Transactional; @SpringBootTest class CrashApplicationTests { @Autowired private RecordRepository recordRepository; @Autowired private MemberRepository memberRepository; @Test public void saveRecord() { Long score = (long) 24; MemberVo memberVo = memberRepository.findById("test"); RecordVo recordVo = new RecordVo(); recordVo.setScore(score); recordVo.setMember(memberVo); recordRepository.save(recordVo); } @Test public void getRecord(){ List<RecordVo> recordList = recordRepository.findAll(); for (int i = 0; i < recordList.size(); i++){ System.out.println("========================="); System.out.println(recordList.get(i).getRcdNo()); System.out.println("========================="); } } @Test @Transactional public void getMember(){ List<MemberVo> memberList = memberRepository.findAll(); System.out.println("START========================="); for (int i = 0; i < memberList.size(); i++){ System.out.println("MEMBER ID : " + memberList.get(i).getId()); List<RecordVo> records = memberList.get(i).getRecords(); for(int j = 0; j < records.size(); j++){ System.out.println("RECORD SCORE : " + records.get(j).getScore()); } } System.out.println("FINISH========================="); } /* RECORD를 소유한 MEMBER를 TRANSACTION 안에서 검색했을 때 삭제하고자 하는 RECORD를 MEMBER LIST에서 삭제해주지 않을 경우 실제로는 삭제되어서 존재하지 않는 RECORD를 MEMBER가 가지고 있게 된다. 이러한 이유 때문에 JPA를 설계할 때 한 TRANSACTION안에서 서로 연관관계가 있는 두 ENITIY를 변경할 때 동기화를 강제하고 있는 것으로 생각된다. */ @Test @Transactional public void deleteRecord(){ Long rcdNo = (long) 1; rcdNo = recordRepository.deleteByRcdNo(rcdNo); System.out.println("START========================="); System.out.println("RcdNo : " + rcdNo); List<RecordVo> recordList = recordRepository.findAll(); for(int i = 0; i < recordList.size(); i++){ System.out.println("RECORD NO : " + recordList.get(i).getRcdNo()); } System.out.println("FINISH========================="); } @Test @Transactional public void deleteMember(){ String id = "test"; Long mbr_no = memberRepository.deleteById(id); System.out.println("MBR_NO : " + mbr_no); this.getMember(); } @Test @Transactional public void updateMember(){ String targetId = "test"; MemberVo memberVo = memberRepository.findById("test"); String changedId = "testChanged"; String changedPassword = "12345"; memberVo.setId(changedId); memberVo.setPassword(changedPassword); memberRepository.save(memberVo); memberVo = memberRepository.findById(changedId); System.out.println("START========================="); System.out.println("NAME : " + memberVo.getName()); System.out.println("ID : " + memberVo.getId()); System.out.println("PASSWORD : " + memberVo.getPassword()); System.out.println("FINISH========================="); } @Test @Transactional public void updateRecord(){ String targetId = "test"; Long scoreChanged = (long) 1; MemberVo memberVo = memberRepository.findById(targetId); Long mbrNo = memberVo.getMbrNo(); List<RecordVo> recordVoList = memberVo.getRecords(); for(int i = 0; i < recordVoList.size(); i++){ RecordVo tem = recordVoList.get(i); tem.setScore(scoreChanged); recordRepository.save(tem); scoreChanged = scoreChanged + 1; } System.out.println(mbrNo); recordVoList = recordRepository.findByMember_mbrNo(mbrNo); System.out.println("START========================="); for(int i = 0; i < recordVoList.size(); i++){ System.out.println("Member ID : " + recordVoList.get(i).getMember().getId()); System.out.println("SCORE : " + recordVoList.get(i).getScore()); } System.out.println("FINISH========================="); } }
package pl.szymonleyk.jpa; /** * Hello world! * */ public class App { public static void main(String[] args) { AddressRepository addressRepository = new AddressRepository(); // dodanie elementu Address address = new Address("Gdynia", "Hutnicza", "3", 5, "51-222"); addressRepository.insert(address); // pobierz element Address szukanyAdres = new Address(); szukanyAdres = addressRepository.select(7); System.out.println(szukanyAdres); } }
package com.yc.education.service.impl.account; import com.yc.education.mapper.account.AccountReceivableRushMapper; import com.yc.education.model.account.AccountReceivableRush; import com.yc.education.service.account.IAccountReceivableRushService; import com.yc.education.service.impl.BaseService; import lombok.SneakyThrows; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * @Description * @Author BlueSky * @Date 2018-12-07 11:44 */ @Service public class AccountReceivableRushServiceImpl extends BaseService<AccountReceivableRush> implements IAccountReceivableRushService { @Autowired AccountReceivableRushMapper mapper; @Override @SneakyThrows public List<AccountReceivableRush> listAccountReceivableRush(String otherid) { return mapper.listAccountReceivableRush(otherid); } @Override public int deleteAccountReceivableRushByParentId(String otherid) { try { return mapper.deleteAccountReceivableRushByParentId(otherid); }catch (Exception e){ e.printStackTrace(); return 0; } } }
import java.math.BigDecimal; /** * Created by dell on 2016-12-30. */ public class CalculatorBean { private String a="0"; public String getA() { return a; } public void setA(String a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator; } public String getRes() { return res; } public void setRes(String res) { this.res = res; } private String b="0"; private String operator="+"; private String res; public void calculat(){ BigDecimal fir = new BigDecimal(a); BigDecimal sec = new BigDecimal(b); if(operator.equals("+")){ res = fir.add(sec).toString(); }else if(operator.equals("-")){ res = fir.subtract(sec).toString(); }else if(operator.equals("*")){ res = fir.multiply(sec).toString(); }else if(operator.equals("/")){ if(sec.doubleValue()==0.0) { throw new RuntimeException("除数是零"); } res = fir.divide(sec,20,BigDecimal.ROUND_HALF_UP).toString(); }else { throw new RuntimeException("没有运算符"); } } }
package com.yma; import java.util.*; /** * Created by Yoshan Amarathunga on 3/16/2017. */ public class Poles { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); Map map = new HashMap<Integer, Integer>(); for(int a0 = 0; a0 < n; a0++){ int x_i = in.nextInt(); int w_i = in.nextInt(); map.put(x_i,w_i); } Map <Integer, Integer>map2 = new TreeMap<Integer,Integer>(map); int point = n / k; int count = 0; int minAlt = 0; for (Map.Entry<Integer,Integer> e :map2.entrySet()) { if(count != 0){ Integer key = e.getKey(); Integer value = e.getValue(); for (int i = 1; i < k; i++) { } }else{ minAlt = e.getKey(); } count++; } } }
package com.example.administrator.panda_channel_app.MVP_Framework.module.home.intentactivity; import com.example.administrator.panda_channel_app.MVP_Framework.base.BaseActivity; import com.example.administrator.panda_channel_app.R; /** * Created by Administrator on 2017/7/15 0015. */ public class Home_VideoActivity extends BaseActivity { @Override protected void initView() { } @Override protected int getLayoutId() { return R.layout.home_videoactivity; } }
package com.aaa.house.service; import com.aaa.house.entity.HouseLaIm; import java.util.List; import java.util.Map; /** * @Author: GZB * @Description: * @Date:Created in 10:12 2019/8/2 * @Modified By: */ public interface DHouseService { List<Map> getHouse1(Map map); /** * 数量 * @return */ int queryPageCount(Map map); /** * 查询所有审核状态 * @return */ List<Map> queryCode2(); /** * 审核驳回 * @return */ int updateHouse(HouseLaIm houseLaIm); /** * 审核通过 * @param map * @return */ int upAudit1(Map map); }
package StepDefinitions; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.cucumber.java.en.*; import io.github.bonigarcia.wdm.WebDriverManager; public class SampleGoogleSearchSteps { WebDriver driver = null; @Given("browser is open") public void browser_is_open() { System.out.println("In - browser is open"); WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS); driver.manage().window().maximize(); } @And("user is on google search page") public void user_is_on_google_search_page() { System.out.println("In - user is on google search page"); driver.get("https://www.google.co.in/"); } @When("user enters a text in searchbox") public void user_enters_a_text_in_searchbox() { System.out.println("In - user enters a text in searchbox"); driver.findElement(By.name("q")).sendKeys("Automation Step by Step"); } @And("hits Enter") public void hits_Enter() { System.out.println("In - hits Enter"); driver.findElement(By.name("q")).sendKeys(Keys.ENTER); } @Then("user is navigated to search result") public void user_is_navigated_to_search_result() { System.out.println("In - user is navigated to search result"); driver.getPageSource().contains("Online Courses"); driver.close(); driver.quit(); } }
package com.example.chetanmuliya.studentpanel.helper; import android.view.View; /** * Created by domaine on 26/04/18. */ public interface CustomOnCLickListener { void onCLick(View v,int position); }
package com.example.omni_vision; import android.hardware.Camera; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.Toast; import com.google.android.youtube.player.YouTubeStandalonePlayer; /** * TODO: * * ++ Obfusicate API Key from Cofig class. * * +) Move declarations and instantiations of fragments up to improve performance. * 1) Set animations for main buttons - change "Web" and "Media" to "<--" and "-->". * 2) Set haptic feedback for buttons (will work only on some devices). */ public class MainActivity extends AppCompatActivity { /** * Camera related declarations. */ private SurfaceView preview = null; private SurfaceHolder previewHolder = null; private Camera camera = null; private boolean inPreview = false; private boolean cameraConfigured = false; /** * Main menu button declarations. */ Button leftMainButton; Button wikiPediaButton; Button gmailButton; Button rightMainButton; Button youTubeButton; Button mapsButton; Button customButton; Button urlSubmittButton; EditText customWebViewEditText; Button slackButton; boolean leftMainMenuNotShowing = true; boolean rightMainMenuNotShowing = true; boolean wikiPediaFragmentNotShowing = true; boolean gmailFragmentNotShowing = true; boolean customFragmentNotShowing = true; boolean youtubeFragmentNotShowing = true; boolean slackFragmentNotShowing = true; boolean mapsFragmentNotShowing = true; FrameLayout leftFrameLayout, rightFrameLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * Setting up the camera. */ preview = (SurfaceView) findViewById(R.id.surfaceview); // preview.setZOrderMediaOverlay(false); previewHolder = preview.getHolder(); previewHolder.addCallback(surfaceCallback); previewHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); camera = Camera.open(); /** * Getting the main menu button on top (in front of) camera preview */ leftMainButton = (Button) findViewById(R.id.leftMainButton); rightMainButton = (Button) findViewById(R.id.rightMainButton); leftMainButton.bringToFront(); preview.invalidate(); /** * Instantiating and setting up main menu buttons. */ wikiPediaButton = (Button) findViewById(R.id.wikiPediaButton); wikiPediaButton.setVisibility(View.GONE); gmailButton = (Button) findViewById(R.id.gmailButton); gmailButton.setVisibility(View.GONE); youTubeButton = (Button) findViewById(R.id.youTubeButton); youTubeButton.setVisibility(View.GONE); mapsButton = (Button) findViewById(R.id.mapsButton); mapsButton.setVisibility(View.GONE); customButton = (Button) findViewById(R.id.customButton); customButton.setVisibility(View.GONE); customWebViewEditText = (EditText) findViewById(R.id.customWebViewEditText); customWebViewEditText.setVisibility(View.GONE); urlSubmittButton = (Button) findViewById(R.id.urlSubmittButton); urlSubmittButton.setVisibility(View.GONE); slackButton = (Button) findViewById(R.id.slackButton); slackButton.setVisibility(View.GONE); /** * Setting up FrameLayouts */ leftFrameLayout = (FrameLayout) findViewById(R.id.leftFrameLayout); rightFrameLayout = (FrameLayout) findViewById(R.id.rightFrameLayout); rightFrameLayout.bringToFront(); leftFrameLayout.setVisibility(View.GONE); rightFrameLayout.setVisibility(View.GONE); /** * Left sub-Main Button click-listeners and behaviors */ wikiPediaButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(wikiPediaFragmentNotShowing) { android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); WikiPediaWebViewFragment fragment = new WikiPediaWebViewFragment(); fragmentTransaction.add(R.id.leftFrameLayout, fragment); fragmentTransaction.commit(); leftFrameLayout.setVisibility(View.VISIBLE); Toast toast = Toast.makeText(MainActivity.this, "Loading...", Toast.LENGTH_SHORT); toast.show(); customWebViewEditText.setVisibility(View.GONE); urlSubmittButton.setVisibility(View.GONE); wikiPediaButton.animate().rotation(360); wikiPediaFragmentNotShowing = false; } else if(!wikiPediaFragmentNotShowing){ leftFrameLayout.setVisibility(View.GONE); wikiPediaButton.animate().rotation(720); wikiPediaFragmentNotShowing = true; } } }); gmailButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(gmailFragmentNotShowing) { android.support.v4.app.FragmentManager fragmentManager2 = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager2.beginTransaction(); GmailWebViewFragment fragment = new GmailWebViewFragment(); fragmentTransaction.add(R.id.leftFrameLayout, fragment); fragmentTransaction.commit(); leftFrameLayout.setVisibility(View.VISIBLE); Toast toast = Toast.makeText(MainActivity.this, "Loading...", Toast.LENGTH_SHORT); toast.show(); customWebViewEditText.setVisibility(View.GONE); urlSubmittButton.setVisibility(View.GONE); gmailButton.animate().rotation(360); gmailFragmentNotShowing = false; } else if(!gmailFragmentNotShowing){ leftFrameLayout.setVisibility(View.GONE); gmailButton.animate().rotation(720); gmailFragmentNotShowing = true; } } }); customButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(customFragmentNotShowing) { urlSubmittButton.setVisibility(View.VISIBLE); customWebViewEditText.setVisibility(View.VISIBLE); CustomWebViewFragment customWebViewFragment = new CustomWebViewFragment(); android.support.v4.app.FragmentManager fragmentManager3 = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager3.beginTransaction(); Log.i("MainActivity", "EditText is" + customWebViewEditText.getText().toString()); fragmentTransaction.add(R.id.leftFrameLayout, customWebViewFragment); fragmentTransaction.commit(); //customWebViewFragment.setCustomURL(customWebViewEditText.getText().toString()); leftFrameLayout.setVisibility(View.VISIBLE); customButton.animate().rotation(360); customFragmentNotShowing = false; } else if(!customFragmentNotShowing){ urlSubmittButton.setVisibility(View.GONE); customWebViewEditText.setVisibility(View.GONE); leftFrameLayout.setVisibility(View.GONE); customButton.animate().rotation(720); customFragmentNotShowing = true; } } }); urlSubmittButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { CustomWebViewFragment customWebViewFragment = new CustomWebViewFragment(); android.support.v4.app.FragmentManager fragmentManager3 = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager3.beginTransaction(); Log.i("MainActivity", "EditText is" + customWebViewEditText.getText().toString()); fragmentTransaction.add(R.id.leftFrameLayout, customWebViewFragment); fragmentTransaction.commit(); customWebViewFragment.setCustomURL(customWebViewEditText.getText().toString()); leftFrameLayout.setVisibility(View.VISIBLE); urlSubmittButton.animate().rotation(360); Toast toast = Toast.makeText(MainActivity.this, "Loading...", Toast.LENGTH_SHORT); toast.show(); } }); /** * Right sub-Main Button click-listeners and behaviors ------------------------------------- */ youTubeButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(youtubeFragmentNotShowing) { android.support.v4.app.FragmentManager fragmentManager4 = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager4.beginTransaction(); YouTubeWebView fragment = new YouTubeWebView(); fragmentTransaction.add(R.id.rightFrameLayout, fragment); fragmentTransaction.commit(); rightFrameLayout.setVisibility(View.VISIBLE); // // YouTubeFragment fragment = new YouTubeFragment(); // Bundle arbBundle = new Bundle(); // arbBundle.putString("VIDEO_URL", "YRrjDTdq8MA"); // fragment.setArguments(arbBundle); // android.support.v4.app.FragmentManager fragmentManager4 = getSupportFragmentManager(); // FragmentTransaction fragmentTransaction = fragmentManager4.beginTransaction(); // // fragmentTransaction.add(R.id.rightFrameLayout, fragment); // fragmentTransaction.commit(); // rightFrameLayout.setVisibility(View.VISIBLE); // preview.setVisibility(View.GONE); // startActivity(YouTubeStandalonePlayer.createVideoIntent(MainActivity.this, "DEVELOPER_KEY", "YRrjDTdq8MA", 0, true, true)); Toast.makeText(MainActivity.this, "Loading...", Toast.LENGTH_SHORT).show(); youTubeButton.animate().rotation(360); youtubeFragmentNotShowing = false; } else if(!youtubeFragmentNotShowing){ rightFrameLayout.setVisibility(View.GONE); youTubeButton.animate().rotation(720); youtubeFragmentNotShowing = true; } } }); slackButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(slackFragmentNotShowing){ rightFrameLayout.setVisibility(View.VISIBLE); Toast.makeText(MainActivity.this, "Loading...", Toast.LENGTH_SHORT).show(); slackButton.animate().rotation(360); slackFragmentNotShowing = false; } else if(!slackFragmentNotShowing){ rightFrameLayout.setVisibility(View.GONE); slackButton.animate().rotation(720); slackFragmentNotShowing = true; } } }); mapsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mapsFragmentNotShowing){ rightFrameLayout.setVisibility(View.VISIBLE); Toast.makeText(MainActivity.this, "Coming Soon.", Toast.LENGTH_SHORT).show(); mapsButton.animate().rotation(360); mapsFragmentNotShowing = false; } else if(!mapsFragmentNotShowing){ rightFrameLayout.setVisibility(View.GONE); mapsButton.animate().rotation(720); mapsFragmentNotShowing = true; } } }); /** * Main menu clickListeners and behaviors. ------------------------------------------------- */ leftMainButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (leftMainMenuNotShowing){ wikiPediaButton.setVisibility(View.VISIBLE); gmailButton.setVisibility(View.VISIBLE); customButton.setVisibility(View.VISIBLE); leftMainButton.setHapticFeedbackEnabled(true); leftMainButton.animate().rotation(360); leftMainMenuNotShowing = false; } else if (!leftMainMenuNotShowing){ wikiPediaButton.setVisibility(View.GONE); gmailButton.setVisibility(View.GONE); customButton.setVisibility(View.GONE); customWebViewEditText.setVisibility(View.GONE); urlSubmittButton.setVisibility(View.GONE); leftMainButton.animate().rotation(720); leftMainMenuNotShowing = true; } } }); rightMainButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (rightMainMenuNotShowing){ youTubeButton.setVisibility(View.VISIBLE); mapsButton.setVisibility(View.VISIBLE); slackButton.setVisibility(View.VISIBLE); rightMainButton.animate().rotation(360); rightMainMenuNotShowing = false; } else if (!rightMainMenuNotShowing){ youTubeButton.setVisibility(View.GONE); mapsButton.setVisibility(View.GONE); slackButton.setVisibility(View.GONE); rightMainButton.animate().rotation(720); rightMainMenuNotShowing = true; } } }); } /** * ----------------End OnCreate----------------------------------------------------------------- * * ----------------Start Methods---------------------------------------------------------------- */ @Override public void onResume() { super.onResume(); releaseCameraAndPreview(); camera = Camera.open(); startPreview(); } @Override public void onPause() { if (inPreview) { camera.stopPreview(); } camera.release(); camera = null; inPreview = false; super.onPause(); } private void releaseCameraAndPreview() { if (camera != null) { camera.release(); camera = null; } } /** * Hides the Status bar and soft keys. * Causes non-fatal errors. * @param hasFocus */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } /** * Methods related to camera functionality. * @param width * @param height * @param parameters * @return */ private Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) { Camera.Size result = null; for (Camera.Size size : parameters.getSupportedPreviewSizes()) { if (size.width <= width && size.height <= height) { if (result == null) { result = size; } else { int resultArea = result.width * result.height; int newArea = size.width * size.height; if (newArea > resultArea) { result = size; } } } } return (result); } private void initPreview(int width, int height) { if (camera != null && previewHolder.getSurface() != null) { try { camera.setPreviewDisplay(previewHolder); } catch (Throwable t) { Log.e("MainActivity", "Exception in setPreviewDisplay()", t); Toast .makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG) .show(); } if (!cameraConfigured) { Camera.Parameters parameters = camera.getParameters(); Camera.Size size = getBestPreviewSize(width, height, parameters); if (size != null) { parameters.setPreviewSize(size.width, size.height); camera.setParameters(parameters); cameraConfigured = true; } } } } private void startPreview() { if (cameraConfigured && camera != null) { camera.startPreview(); inPreview = true; } } SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() { public void surfaceCreated(SurfaceHolder holder) { // no-op -- wait until surfaceChanged() } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { initPreview(width, height); startPreview(); } public void surfaceDestroyed(SurfaceHolder holder) { // no-op } }; }
package Business; import DataAccess.TableDAL; import Entity.Restaurant; import Entity.Table; import java.util.List; public class TableBAL { private static TableBAL instance; public static TableBAL getInstance() { if(instance == null) { instance = new TableBAL(); } return instance; } public boolean addTable(Table table) { return TableDAL.getInstance().addTable(table); } public boolean updateTable(Table table) { return TableDAL.getInstance().updateTable(table); } public boolean deleteTable(Table table) { return TableDAL.getInstance().deleteTable(table); } public List<Table> getTableList() { return TableDAL.getInstance().getTableList(); } public List<Table> getTableListByArea() { return TableDAL.getInstance().getTableListByArea(); } public List<Table> getTableListByRestaurant(int restaurantID) { return TableDAL.getInstance().getTableListByRestaurant(restaurantID); } }
package im.compIII.exghdecore.banco; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; public class Conexao { private static Connection connection; protected static PreparedStatement psmt; protected static Statement smt; private Conexao() {} public static void initConnection() throws SQLException, ClassNotFoundException { Class.forName("org.h2.Driver"); connection = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/exghDecoreDB", "admin", "admin123"); connection.setAutoCommit(false); } public static void rollBack() { try { connection.rollback(); } catch (SQLException e) { e.printStackTrace(); } } public static void commit() { try { connection.commit(); } catch (SQLException e) { e.printStackTrace(); } } public static PreparedStatement prepare(String sql) throws SQLException { psmt = connection.prepareStatement(sql); return psmt; } public static Statement prepare() throws SQLException { smt = connection.createStatement(); return smt; } public static void closeConnection() throws SQLException { if (psmt != null && !psmt.isClosed()) psmt.close(); if (smt != null && !smt.isClosed()) smt.close(); if(!connection.isClosed()) connection.close(); } }
package com.example.administrator.panda_channel_app.Activity; import android.support.v7.widget.LinearLayoutManager; import android.widget.ImageView; import com.androidkun.PullToRefreshRecyclerView; import com.androidkun.callback.PullToRefreshListener; import com.example.administrator.panda_channel_app.Adapter.OriginalAdapter; import com.example.administrator.panda_channel_app.MVP_Framework.app.App; import com.example.administrator.panda_channel_app.MVP_Framework.base.BaseActivity; import com.example.administrator.panda_channel_app.MVP_Framework.modle.biz.Panda_channelModle; import com.example.administrator.panda_channel_app.MVP_Framework.modle.biz.Panda_channelModleImpl; import com.example.administrator.panda_channel_app.MVP_Framework.network.callback.MyNetWorkCallback; import com.example.administrator.panda_channel_app.R; import com.example.administrator.panda_channel_app.model.OriginalBean; import java.util.ArrayList; import butterknife.BindView; import butterknife.OnClick; /** * Created by 闫雨婷 on 2017/7/13. */ //666666 public class OriginalActivity extends BaseActivity{ @BindView(R.id.original_image) ImageView originalImage; @BindView(R.id.original_recyclerview) PullToRefreshRecyclerView originalRecyclerview; private ArrayList<OriginalBean.InteractiveBean> list=new ArrayList<>(); private OriginalAdapter adapter; @Override protected void initView() { LinearLayoutManager manager=new LinearLayoutManager(this); originalRecyclerview.setLayoutManager(manager); manager.setOrientation(LinearLayoutManager.VERTICAL); adapter=new OriginalAdapter(this,list); originalRecyclerview.setAdapter(adapter); originalRecyclerview.setLoadingMoreEnabled(true); originalRecyclerview.setPullRefreshEnabled(true); originalRecyclerview.setPullToRefreshListener(new PullToRefreshListener() { @Override public void onRefresh() { originalRecyclerview.postDelayed(new Runnable() { @Override public void run() { adapter.notifyDataSetChanged(); originalRecyclerview.setRefreshComplete(); } }, 1000); } @Override public void onLoadMore() { originalRecyclerview.postDelayed(new Runnable() { @Override public void run() { adapter.notifyDataSetChanged(); originalRecyclerview.setLoadMoreComplete(); } }, 1000); } }); Panda_channelModle panda_channelModle=new Panda_channelModleImpl(); panda_channelModle.getOriginal(new MyNetWorkCallback<OriginalBean>() { @Override public void Success(OriginalBean originalBean) { list.addAll(originalBean.getInteractive()); App.context.runOnUiThread(new Runnable() { @Override public void run() { adapter.notifyDataSetChanged(); } }); } @Override public void onError(String errormsg) { } }); } @Override protected int getLayoutId() { return R.layout.activity_original; } @OnClick(R.id.original_image) public void onViewClicked() { finish(); } }
package ru.andersen; import ru.andersen.service.EmployeeServiceImpl; import javax.xml.ws.Endpoint; /** * @author Vladimir Ryazanov (v.ryazanov13@gmail.com) */ public class Publisher { public static void main(String[] args) { Endpoint.publish("http://localhost:8080/employeeservice", new EmployeeServiceImpl()); } }
package org.jinku.sync.application.server.comet; import io.netty.channel.ChannelHandlerContext; import org.jinku.sync.application.ao.ResultAo; import org.jinku.sync.domain.types.ReqType; public interface ReqHandler { ReqType getReqType(); ResultAo handleReq(String reqData, ChannelHandlerContext ctx); }
package lockedme.com; import java.io.File; import java.io.IOException; import java.util.Scanner; public class DigitalFileStoragePrototype { public static void main(String args[]) { int choice = 0; String Enterchoice = ("1. Display all files from directory\n" + "2. Add a File to directory\n" + "3. Search a File from directory\n" + "4. Delete a File from directory\n" + "5. Close the application\n\n" + "Enter number from above selection:\n"); Scanner input = new Scanner(System.in); System.out.println("***************************"); System.out.println("*******Lockedme.com********"); System.out.println("***************************"); System.out.println(); System.out.println(Enterchoice); choice=input.nextInt(); while (choice < 1 || choice > 5) { //checking if number entered is out to selection choice and show error System.out.println("\nERROR: Invalid option selected\n"); System.out.println("------------------------------------"); System.out.println(Enterchoice); choice=input.nextInt(); } while (choice >= 1 || choice <= 5) { switch (choice) { case 1: { display(); //calls display method to display all files from directory } System.out.println(); System.out.println("------------------------------------"); System.out.println(Enterchoice); choice=input.nextInt(); break; case 2: { add(); //calls add method to add a file to directory } System.out.println(); System.out.println("------------------------------------"); System.out.println(Enterchoice); choice=input.nextInt(); break; case 3: { search(); //calls search method to search a file from directory } System.out.println(); System.out.println("------------------------------------"); System.out.println(Enterchoice); choice=input.nextInt(); break; case 4: { delete(); //calls delete method to delete a file from directory } System.out.println(); System.out.println("------------------------------------"); System.out.println(Enterchoice); choice=input.nextInt(); break; case 5: { close(); //calls close method to close application } break; } } } static void display() { //Method to display all files from directory Scanner scan = new Scanner(System.in); System.out.println("Enter directory to get list of files from:\n" ); String directoryname = scan.next(); String [] filenames; File file = new File(directoryname); if (file.exists()) { filenames = file.list(); /* //Arrays.sort(filenames); //prints the sorted string array in ascending order //System.out.println(Arrays.toString(filenames)); */ for (String filename : filenames) { System.out.println(filename); } }else { System.out.println("***Directory does not exist***"); } } static void add() { //Method to add all file to directory try { Scanner scan = new Scanner(System.in); System.out.println("Enter directory along with file name to be created:\n" ); String filename = scan.next(); File file = new File(filename); //C://Pavani//Myfile.txt if (file.exists()) { System.out.println("***File already exists***"); }else { file.createNewFile(); System.out.println("***New file "+file.getName() +" created successfully***"); } }catch (IOException e) { e.printStackTrace(); System.out.println("***File cannot be created***"); } } static void search() { //Method to search files from directory Scanner scan = new Scanner(System.in); System.out.println("Enter directory along with file name to be searched:\n" ); //C:\Pavani\Myfile.txt String filename = scan.next(); //System.out.println("Enter the directory where to search:\n"); //String directory = scan.next(); File file = new File(filename); try { if (file.exists() && file.getCanonicalPath().equals(filename)) { System.out.println("***File exist***"); }else { System.out.println("***File not found***"); } } catch (IOException e) { e.printStackTrace(); } } static void delete() { //Method to delete files from directory Scanner scan = new Scanner(System.in); System.out.println("Enter directory along with file name to be deleted:\n" ); String filename = scan.next(); //System.out.println("Enter the directory where to search:\n"); //String directory = scan.next(); File file = new File(filename); try { if (file.exists() && file.getCanonicalPath().equals(filename)) { file.delete(); System.out.println("***File successfully deleted***"); }else { System.out.println("***File not found***"); } } catch (IOException e) { e.printStackTrace(); } } static void close() { //Method to close files from directory System.out.println("***Application closed***"); System.exit(0); } }
import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp; import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.store.FileDataStoreFactory; import com.google.api.services.gmail.Gmail; import com.google.api.services.gmail.GmailScopes; import com.google.api.services.gmail.model.ListMessagesResponse; import com.google.api.services.gmail.model.Message; import com.google.api.services.gmail.model.MessagePart; import com.google.api.services.gmail.model.MessagePartBody; import com.google.cloud.vision.v1.*; import com.google.common.collect.ImmutableList; import org.apache.commons.codec.binary.Base64; import com.google.api.services.gmail.model.ModifyMessageRequest; import com.google.api.services.gmail.model.Label; import com.google.api.services.gmail.model.ListLabelsResponse; import com.google.cloud.vision.v1.Feature.Type; import com.google.protobuf.ByteString; import java.io.*; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; // Imports the Google Cloud client library public class GmailImageAnalyzerAndLabeller { private static final String APPLICATION_NAME = "Gmail API Java Quickstart"; private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); private static final String TOKENS_DIRECTORY_PATH = "tokens"; private static final String ANALYZED_PARENT_LABEL = "Z"; /** * Global instance of the scopes required by this quickstart. * If modifying these scopes, delete your previously saved tokens/ folder. */ private static final List<String> SCOPES = ImmutableList.of(GmailScopes.GMAIL_LABELS, GmailScopes.GMAIL_MODIFY); private static final String CREDENTIALS_FILE_PATH = "/credentials.json"; private static final String ANIMALS_FILE_PATH = "animals.csv"; private final static Logger LOGGER = Logger.getLogger(GmailImageAnalyzerAndLabeller.class.getName()); /** * Creates an authorized Credential object. * * @param HTTP_TRANSPORT The network HTTP Transport. * @return An authorized Credential object. * @throws IOException If the credentials.json file cannot be found. */ protected static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException { // Load client secrets. InputStream in = GmailImageAnalyzerAndLabeller.class.getResourceAsStream(CREDENTIALS_FILE_PATH); if (in == null) { throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH); } GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in)); // Build flow and trigger user authorization request. GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder( HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES) .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) .setAccessType("offline") .build(); LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build(); return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user"); } /** * List all Messages of the user's mailbox matching the query. * * @param service Authorized Gmail API instance. * @param userId User's email address. The special value "me" * can be used to indicate the authenticated user. * @param query String used to filter the Messages listed. * @throws IOException */ public static List<Message> listMessagesMatchingQuery(Gmail service, String userId, String query) throws IOException { ListMessagesResponse response = service.users().messages().list(userId).setQ(query).execute(); List<Message> messages = new ArrayList<Message>(); while (response.getMessages() != null) { messages.addAll(response.getMessages()); if (response.getNextPageToken() != null) { String pageToken = response.getNextPageToken(); response = service.users().messages().list(userId).setQ(query) .setPageToken(pageToken).execute(); } else { break; } } return messages; } public static List<byte[]> getAttachmentsBytes(Gmail service, String userId, String messageId) throws IOException { Message message = service.users().messages().get(userId, messageId).execute(); List<MessagePart> parts = message.getPayload().getParts(); List<byte[]> attachmentImageByteArrays = new ArrayList<>(); for (MessagePart part : parts) { // maybe check file ending if its a pic ? if (part.getFilename() != null && part.getFilename().length() > 0) { String filename = part.getFilename(); String attId = part.getBody().getAttachmentId(); MessagePartBody attachPart = service.users().messages().attachments(). get(userId, messageId, attId).execute(); Base64 base64Url = new Base64(true); byte[] fileByteArray = base64Url.decodeBase64(attachPart.getData()); attachmentImageByteArrays.add(fileByteArray); } } return attachmentImageByteArrays; } /** * Detects localized objects in the specified local image. * * @param imgByteArray * @return List<EntityAnnotation> annotations of the analyzed image * @throws Exception on errors while closing the client. * @throws IOException on Input/Output errors. */ public static List<LocalizedObjectAnnotation> detectLocalizedObjects(byte[] imgByteArray) throws IOException { List<AnnotateImageRequest> requests = new ArrayList<>(); ByteString imgBytes = ByteString.copyFrom(imgByteArray); Image img = Image.newBuilder().setContent(imgBytes).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder() .addFeatures(Feature.newBuilder().setType(Type.OBJECT_LOCALIZATION)) .setImage(img) .build(); requests.add(request); // Perform the request try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests); List<AnnotateImageResponse> responses = response.getResponsesList(); // Display the results for (AnnotateImageResponse resu : responses) { for (LocalizedObjectAnnotation entity : resu.getLocalizedObjectAnnotationsList()) { LOGGER.info("Object name: " + entity.getName()); LOGGER.info("Confidence: " + entity.getScore()); } } // get first response (only sent in one image in the batch so should only be one response) // Possible to do is to handle emails with several image attachments. AnnotateImageResponse res = responses.get(0); if (res.hasError()) { LOGGER.severe("Error: " + res.getError().getMessage()); } return res.getLocalizedObjectAnnotationsList(); } } public static List<EntityAnnotation> annotateImageWithGoogleVision(byte[] imgByteArray) throws IOException { try (ImageAnnotatorClient vision = ImageAnnotatorClient.create()) { ByteString imgBytes = ByteString.copyFrom(imgByteArray); // Builds the image annotation request List<AnnotateImageRequest> requests = new ArrayList<>(); Image img = Image.newBuilder().setContent(imgBytes).build(); Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder() .addFeatures(feat) .setImage(img) .build(); requests.add(request); // Performs label detection on the image file BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests); List<AnnotateImageResponse> responses = response.getResponsesList(); // get first response (only sent in one image in the batch so should only be one response) // Possible to do is to handle emails with several image attachments. AnnotateImageResponse res = responses.get(0); if (res.hasError()) { LOGGER.severe("Error: " + res.getError().getMessage()); } return res.getLabelAnnotationsList(); } } /** * Modify the labels a message is associated with. * * @param service Authorized Gmail API instance. * @param userId User's email address. The special value "me" * can be used to indicate the authenticated user. * @param messageId ID of Message to Modify. * @param labelsToAdd List of label ids to add. * @param labelsToRemove List of label ids to remove. * @throws IOException */ public static void modifyMessage(Gmail service, String userId, String messageId, List<String> labelsToAdd, List<String> labelsToRemove) throws IOException { ModifyMessageRequest mods = new ModifyMessageRequest().setAddLabelIds(labelsToAdd) .setRemoveLabelIds(labelsToRemove); Message message = service.users().messages().modify(userId, messageId, mods).execute(); } /** * List the Labels in the user's mailbox. * * @param service Authorized Gmail API instance. * @param userId User's email address. The special value "me" * can be used to indicate the authenticated user. * @throws IOException */ public static List<Label> listLabels(Gmail service, String userId) throws IOException { ListLabelsResponse response = service.users().labels().list(userId).execute(); List<Label> labels = response.getLabels(); return labels; } /** * Add a new Label to user's inbox. * * @param service Authorized Gmail API instance. * @param userId User's email address. The special value "me" * can be used to indicate the authenticated user. * @param newLabelName Name of the new label. * @throws IOException */ public static Label createLabel(Gmail service, String userId, String newLabelName) throws IOException { Label label = new Label() .setName(newLabelName) .setLabelListVisibility("labelShow") .setMessageListVisibility("show"); label = service.users().labels().create(userId, label).execute(); return label; } public static Label getLabelByName(Gmail service, String userId, String labelName) throws IOException { // Get all labels in account List<Label> labelsInAccount = listLabels(service, userId); // See if the label name exists for (Label label : labelsInAccount) { if (label.getName().equals(labelName)) { return label; } } // Label does not seem to exist? -> create the label return createLabel(service, userId, labelName); } public static void labelEmailAndMarkAsProcessed(Gmail service, String userId, String emailId, List<String> labelNamesToAddToEmail) throws IOException { List<String> labelIdsToAdd = new ArrayList<String>(); for (String labelNameToAdd : labelNamesToAddToEmail) { // add labels as children under parent label labelIdsToAdd.add(getLabelByName(service, userId, ANALYZED_PARENT_LABEL + "/" + labelNameToAdd).getId()); } // always add the "analyzed parent label" labelIdsToAdd.add(getLabelByName(service, userId, ANALYZED_PARENT_LABEL).getId()); modifyMessage(service, userId, emailId, labelIdsToAdd, null); } public static EntityAnnotation getHighestScoringAnnotation(List<EntityAnnotation> annotations) { double highestScore = 0; EntityAnnotation highestScoredAnnotation = null; if (!annotations.isEmpty()) { for (EntityAnnotation annotation : annotations) { if (annotation.getScore() > highestScore) { highestScoredAnnotation = annotation; highestScore = annotation.getScore(); } } } return highestScoredAnnotation; } public static List<String> getListOfAnimals() throws IOException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(ANIMALS_FILE_PATH); Reader inputStreamReader = new InputStreamReader(inputStream); BufferedReader csvReader = new BufferedReader(inputStreamReader); List<String> animals = new ArrayList<String>(); String row = ""; while ((row = csvReader.readLine()) != null) { animals.add(row.toLowerCase().trim()); } csvReader.close(); return animals; } public static void main(String... args) throws Exception { // Build a new authorized API client service. final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); Gmail service = new Gmail.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT)) .setApplicationName(APPLICATION_NAME) .build(); // Print the labels in the user's account. String user = "me"; // Find emails // this is the same search string as a search would result in gmail ui String gmailSearchString = "filename:PIC.jpg newer_than:2d"; List<Message> messages = listMessagesMatchingQuery(service, user, gmailSearchString .concat(" AND NOT label:\"").concat(ANALYZED_PARENT_LABEL).concat("\"") ); if (!messages.isEmpty()) { LOGGER.info("Number of messages fetched: " + messages.size()); } // Process emails for (Message message : messages) { // download attachment LOGGER.info("Downloading attachment!"); List<byte[]> imageByteArrays = getAttachmentsBytes(service, user, message.getId()); for (byte[] imageByteArray : imageByteArrays) { LOGGER.info("Analyzing attachment for labels!"); // Analyze attachment (google vision) List<EntityAnnotation> annotations = annotateImageWithGoogleVision(imageByteArray); for (EntityAnnotation annotation : annotations) { LOGGER.info(annotation.toString()); } // is any of the labels an animal!? // check against the list of animals! List<String> labels = new ArrayList<>(); List<EntityAnnotation> animalAnnotations = getAnimalAnnotations(annotations); if (animalAnnotations != null) { for (EntityAnnotation annotation : animalAnnotations) { labels.add(annotation.getDescription()); LOGGER.info("Spotted a " + annotation.getDescription() + "!"); } } else { // no animals found :( // take the highest scoring label labels.add(getHighestScoringAnnotation(annotations).getDescription()); } LOGGER.info("Analyzing attachment for objects!"); List<LocalizedObjectAnnotation> objectAnnotations = detectLocalizedObjects(imageByteArray); for (LocalizedObjectAnnotation annotation : objectAnnotations) { LOGGER.info(annotation.toString()); labels.add(annotation.getName()); } labelEmailAndMarkAsProcessed(service, user, message.getId(), labels); } } } private static List<EntityAnnotation> getAnimalAnnotations(List<EntityAnnotation> annotations) throws IOException { List<EntityAnnotation> animalAnnotations = new ArrayList<>(); for (EntityAnnotation annotation : annotations) { if (isAnimal(annotation.getDescription())) { animalAnnotations.add(annotation); } } return animalAnnotations; } public static boolean isAnimal(String description) throws IOException { List<String> animals = getListOfAnimals(); return animals.contains(description.toLowerCase().trim()); } }
package com.Exception_concepts; public class UncheckedExceptionDemo { public static void main(String[] args) { /* int num = 12; int num1 = 0; int result = num/num1; System.out.println(result); System.out.println("Calling from main ()");*/ String name = null; System.out.println(name.length()); /*int [] ar = {1,2,3,4,5}; System.out.println(ar.length); System.out.println(ar[10]); System.out.println("Hello");*/ } }