text
stringlengths
10
2.72M
package com.grebnev.game.actors; /** * Created by Grebnev on 23.04.2017. */ public enum PieceKind { KING, QUEEN, ROOK, BISHOP, KNIGHT, PAWN, }
package com.trump.auction.web.controller; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.alibaba.fastjson.JSONObject; import com.cf.common.util.mapping.BeanMapper; import com.trump.auction.cust.api.AccountRechargeRuleStubService; import com.trump.auction.cust.api.UserInfoStubService; import com.trump.auction.cust.model.AccountRechargeRuleDetailModel; import com.trump.auction.cust.model.AccountRechargeRuleModel; import com.trump.auction.cust.model.UserInfoModel; import com.trump.auction.web.service.RechargeService; import com.trump.auction.web.util.HandleResult; import com.trump.auction.web.util.JsonView; import com.trump.auction.web.util.SpringUtils; import com.trump.auction.web.vo.AccountRechargeRuleVo; import lombok.extern.slf4j.Slf4j; import redis.clients.jedis.JedisCluster; /** * 充值 * Created by songruihuan on 2017/12/20. */ @Slf4j @Controller @RequestMapping("recharge/") public class RechargeController extends BaseController{ @Autowired private RechargeService rechargeService; @Autowired private AccountRechargeRuleStubService accountRechargeRuleStubService; @Autowired private UserInfoStubService userInfoStubService; @Autowired private BeanMapper beanMapper; @Autowired private JedisCluster jedisCluster; @RequestMapping("rule") public void gradient(HttpServletRequest request,HttpServletResponse response) { List<AccountRechargeRuleDetailModel> list = new ArrayList<AccountRechargeRuleDetailModel>(); List<AccountRechargeRuleVo> vos = new ArrayList<>(); JSONObject json = new JSONObject(); try { AccountRechargeRuleModel ruleModel = accountRechargeRuleStubService.findEnableRule(); if(ruleModel != null){ Integer ruleUser = ruleModel.getRuleUser(); if(ruleUser.equals(2)){ String userId = getUserIdFromRedis(request); if(userId != null){ UserInfoModel userInfoModel = userInfoStubService.findUserInfoById(Integer.valueOf(userId)); Integer rechargeType = userInfoModel.getRechargeType(); if(rechargeType.equals(1) && ruleModel != null){ list = ruleModel.getDetails(); vos = beanMapper.mapAsList(list, AccountRechargeRuleVo.class); } }else{ list = ruleModel.getDetails(); vos = beanMapper.mapAsList(list, AccountRechargeRuleVo.class); } }else{ list = ruleModel.getDetails(); vos = beanMapper.mapAsList(list, AccountRechargeRuleVo.class); } } json.put("list", vos); String recharge_title = jedisCluster.get("recharge_title"); recharge_title = recharge_title==null?"1.单笔充值达到指定金额即可获得对应额度的赠币奖励":recharge_title; String recharge_min_money = jedisCluster.get("recharge_min_money"); recharge_min_money = recharge_min_money==null?"100":recharge_min_money; json.put("ruleDesc", recharge_title); Integer minMoney = Integer.valueOf(recharge_min_money)/100; json.put("minMoney", minMoney); } catch (Exception e) { log.error("recharge/rule error : {}",e); } SpringUtils.renderJson(response, JsonView.build(0, "success",json)); } /** * <p> * Title: 预支付 * </p> * <p> * Description: 生成订单,请求第三方支付 生成repay_id * </p> * @param request * @param response * @param payType:支付方式:1微信,2支付宝 * @return */ @RequestMapping("prePay") public void prePay(HttpServletRequest request,HttpServletResponse response,Integer money,String payType) { String userId = getUserIdFromRedis(request); HandleResult result = rechargeService.prePay(request,Integer.valueOf(userId), money, payType); SpringUtils.renderJson(response, JsonView.build(result.getCode(), result.getMsg(),result.getData())); } }
package alien4cloud.tosca.parser; import java.util.List; import org.yaml.snakeyaml.nodes.Node; import org.yaml.snakeyaml.nodes.ScalarNode; import alien4cloud.component.ICSARRepositorySearchService; import alien4cloud.model.components.IndexedArtifactType; import alien4cloud.model.components.IndexedCapabilityType; import alien4cloud.model.components.IndexedDataType; import alien4cloud.model.components.IndexedNodeType; import alien4cloud.model.components.IndexedRelationshipType; import alien4cloud.model.components.IndexedToscaElement; import alien4cloud.tosca.model.ArchiveRoot; import alien4cloud.tosca.parser.impl.ErrorCode; public final class ToscaParsingUtil { private ToscaParsingUtil() { } /** * Get a string value. * * @param keyNode The node that represents the key of the value node to parse. * @param valueNode The value node. * @param parsingErrors A list of errors in which to add an error if the value is not a valid yaml string. * @return The value of the string. In case of an error null is returned. Null return however is not sufficient to know that an error occured. In case of an * error a new {@link ParsingError} is added to the parsingErrors list given as a parameter. */ public static String getStringValue(ScalarNode keyNode, Node valueNode, List<ParsingError> parsingErrors) { if (valueNode instanceof ScalarNode) { ScalarNode scalarNode = (ScalarNode) valueNode; return scalarNode.getValue(); } parsingErrors.add(new ParsingError(ErrorCode.SYNTAX_ERROR, "Error while parsing field " + keyNode.getValue(), keyNode.getStartMark(), "Expected a scalar type.", valueNode.getStartMark(), "scalar")); return null; } public static IndexedNodeType getNodeTypeFromArchiveOrDependencies(String nodeTypeName, ArchiveRoot archiveRoot, ICSARRepositorySearchService searchService) { return getElementFromArchiveOrDependencies(IndexedNodeType.class, nodeTypeName, archiveRoot, searchService); } public static IndexedRelationshipType getRelationshipTypeFromArchiveOrDependencies(String nodeTypeName, ArchiveRoot archiveRoot, ICSARRepositorySearchService searchService) { return getElementFromArchiveOrDependencies(IndexedRelationshipType.class, nodeTypeName, archiveRoot, searchService); } public static IndexedDataType getDataTypeFromArchiveOrDependencies(String dataTypeName, ArchiveRoot archiveRoot, ICSARRepositorySearchService searchService) { return getElementFromArchiveOrDependencies(IndexedDataType.class, dataTypeName, archiveRoot, searchService); } @SuppressWarnings("unchecked") public static <T extends IndexedToscaElement> T getElementFromArchiveOrDependencies(Class<T> elementClass, String elementId, ArchiveRoot archiveRoot, ICSARRepositorySearchService searchService) { T result = null; // fisrt off all seach in the current archive if (elementClass == IndexedCapabilityType.class) { result = (T) archiveRoot.getCapabilityTypes().get(elementId); } else if (elementClass == IndexedArtifactType.class) { result = (T) archiveRoot.getArtifactTypes().get(elementId); } else if (elementClass == IndexedRelationshipType.class) { result = (T) archiveRoot.getRelationshipTypes().get(elementId); } else if (elementClass == IndexedNodeType.class) { result = (T) archiveRoot.getNodeTypes().get(elementId); } else if (elementClass == IndexedDataType.class) { result = (T) archiveRoot.getDataTypes().get(elementId); } if (result == null) { // the result can't be found in current archive, let's have a look in dependencies result = searchService.getElementInDependencies(elementClass, elementId, archiveRoot.getArchive().getDependencies()); } return result; } }
package com.upm.subsystem; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.upm.subsystem.model.GenericResponse; import com.upm.subsystem.model.Light; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author */ public class LightController extends javax.swing.JFrame { /** * Creates new form LightController */ public LightController() { initComponents(); updateView(); } public void updateView() { System.out.println("Update View Called"); DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); try { HttpResponse<GenericResponse> allLight = Unirest.get(Utility.url+"light/getAllLight") .header("accept", "application/json") .header("Content-Type", "application/json") .asObject(GenericResponse.class); List allLights=(List)allLight.getBody().getData(); System.out.println("---- "+allLights.size()); for (Object allLight1 : allLights) { System.out.println("-------------- "+allLight1.toString()); HashMap<String,String> light=(HashMap<String,String>)allLight1; System.out.println("---- "+light.get("deviceId")); tableModel.addRow(new String[]{light.get("deviceId"),light.get("roomName"), light.get("lightType"), light.get("status"), light.get("time")}); } tableModel.fireTableDataChanged(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); addButton = new javax.swing.JButton(); switchOnBtn = new javax.swing.JButton(); switchOffBtn = new javax.swing.JButton(); removeLightBtn = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jTextField2 = new javax.swing.JTextField(); jComboBox1 = new javax.swing.JComboBox<>(); jComboBox2 = new javax.swing.JComboBox<>(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 153, 51)); jLabel1.setText("Control Light"); addButton.setBackground(new java.awt.Color(255, 255, 255)); addButton.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N addButton.setForeground(new java.awt.Color(0, 204, 51)); addButton.setText("Add Light"); addButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addButtonActionPerformed(evt); } }); switchOnBtn.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N switchOnBtn.setForeground(new java.awt.Color(0, 102, 255)); switchOnBtn.setText("Switch On Light"); switchOnBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { switchOnBtnActionPerformed(evt); } }); switchOffBtn.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N switchOffBtn.setForeground(new java.awt.Color(255, 153, 51)); switchOffBtn.setText("Switch Off Light"); switchOffBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { switchOffBtnActionPerformed(evt); } }); removeLightBtn.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N removeLightBtn.setForeground(new java.awt.Color(255, 0, 0)); removeLightBtn.setText("Remove Light"); removeLightBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeLightBtnActionPerformed(evt); } }); jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel2.setText("Device Id"); jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel3.setText("Room Name"); jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel4.setText("Light Type"); jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel5.setText("Status"); jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Night Bulb", "Tube Light", "Foot Light", "LED 10W", "LED 15W" })); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "ON", "OFF" })); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(122, 122, 122) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel2) .addComponent(jLabel4) .addComponent(jLabel5)) .addGap(64, 64, 64) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jTextField1) .addComponent(jTextField2) .addComponent(jComboBox1, 0, 177, Short.MAX_VALUE) .addComponent(jComboBox2, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(60, 60, 60) .addComponent(switchOnBtn) .addGap(76, 76, 76) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(addButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(switchOffBtn) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 105, Short.MAX_VALUE) .addComponent(removeLightBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(47, 47, 47)))) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(35, 35, 35) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(29, 29, 29) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(addButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(switchOffBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(switchOnBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(removeLightBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap()) ); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Device ID", "Room Name", "Light Type", "Status", "Time" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; boolean[] canEdit = new boolean [] { false, false, false, false, false }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); jScrollPane1.setViewportView(jTable1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 722, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(267, 267, 267) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 274, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed // Validation if(jTextField1.getText()== null || jTextField1.getText().isEmpty()){ JOptionPane.showMessageDialog(rootPane, "Device Id can't be blank"); return ; } if(jTextField2.getText()== null || jTextField2.getText().isEmpty()){ JOptionPane.showMessageDialog(rootPane, "Room name can't be null"); return ; } Light light = new Light(); light.setDeviceId(jTextField1.getText()); light.setLightType(jComboBox1.getSelectedItem().toString()); light.setRoomName(jTextField2.getText()); light.setStatus(jComboBox2.getSelectedItem().toString()); light.setTime(new Date().toString()); try { HttpResponse<GenericResponse> postResponse = Unirest.post(Utility.url+"light/addLight") .header("accept", "application/json") .header("Content-Type", "application/json") .body(light) .asObject(GenericResponse.class); JOptionPane.showMessageDialog(rootPane, postResponse.getBody().getMessage()); // Update row in table DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); tableModel.addRow(new String[]{light.getDeviceId(),light.getRoomName(), light.getLightType(), light.getStatus(), light.getTime()}); tableModel.fireTableDataChanged(); jTextField1.setText(""); jTextField2.setText(""); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } }//GEN-LAST:event_addButtonActionPerformed private void switchOnBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_switchOnBtnActionPerformed try { int rowIndex=jTable1.getSelectedRow(); DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); String deviceId=(String) tableModel.getValueAt(rowIndex, 0); System.out.println("-- Device Id "+deviceId); HttpResponse<GenericResponse> postResponse = Unirest.post(Utility.url+"light/switchOnLight/"+deviceId) .header("accept", "application/json") .header("Content-Type", "application/json") .asObject(GenericResponse.class); JOptionPane.showMessageDialog(rootPane, postResponse.getBody().getMessage()); // Update row in table tableModel.setValueAt("ON", rowIndex, 3); tableModel.fireTableDataChanged(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } }//GEN-LAST:event_switchOnBtnActionPerformed private void switchOffBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_switchOffBtnActionPerformed try { int rowIndex=jTable1.getSelectedRow(); DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); String deviceId=(String) tableModel.getValueAt(rowIndex, 0); System.out.println("-- Device Id "+deviceId); HttpResponse<GenericResponse> postResponse = Unirest.post(Utility.url+"light/switchOffLight/"+deviceId) .header("accept", "application/json") .header("Content-Type", "application/json") .asObject(GenericResponse.class); JOptionPane.showMessageDialog(rootPane, postResponse.getBody().getMessage()); // Update row in table tableModel.setValueAt("OFF", rowIndex, 3); tableModel.fireTableDataChanged(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } }//GEN-LAST:event_switchOffBtnActionPerformed private void removeLightBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeLightBtnActionPerformed try { int rowIndex=jTable1.getSelectedRow(); DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel(); String deviceId=(String) tableModel.getValueAt(rowIndex, 0); System.out.println("-- Device Id "+deviceId); HttpResponse<GenericResponse> postResponse = Unirest.delete(Utility.url+"light/removeLight/"+deviceId) .header("accept", "application/json") .header("Content-Type", "application/json") .asObject(GenericResponse.class); JOptionPane.showMessageDialog(rootPane, postResponse.getBody().getMessage()); // Update row in table tableModel.removeRow(rowIndex); tableModel.fireTableDataChanged(); } catch (Exception ex) { ex.printStackTrace(); JOptionPane.showMessageDialog(rootPane, ex.getMessage()); } }//GEN-LAST:event_removeLightBtnActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton addButton; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JComboBox<String> jComboBox2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JTextField jTextField1; private javax.swing.JTextField jTextField2; private javax.swing.JButton removeLightBtn; private javax.swing.JButton switchOffBtn; private javax.swing.JButton switchOnBtn; // End of variables declaration//GEN-END:variables }
package com.xianzaishi.wms.tmscore.manage.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.xianzaishi.wms.common.exception.BizException; import com.xianzaishi.wms.tmscore.dao.itf.IWaveDetailDao; import com.xianzaishi.wms.tmscore.manage.itf.IWaveDetailManage; import com.xianzaishi.wms.tmscore.vo.WaveDetailQueryVO; import com.xianzaishi.wms.tmscore.vo.WaveDetailVO; public class WaveDetailManageImpl implements IWaveDetailManage { @Autowired private IWaveDetailDao waveDetailDao = null; private void validate(WaveDetailVO waveDetailVO) { if (waveDetailVO.getWaveId() == null || waveDetailVO.getWaveId() <= 0) { throw new BizException("waveID error:" + waveDetailVO.getWaveId()); } if (waveDetailVO.getDistributionId() == null || waveDetailVO.getDistributionId() <= 0) { throw new BizException("distributionID error:" + waveDetailVO.getDistributionId()); } } private void validate(Long id) { if (id == null || id <= 0) { throw new BizException("ID error:" + id); } } public IWaveDetailDao getWaveDetailDao() { return waveDetailDao; } public void setWaveDetailDao(IWaveDetailDao waveDetailDao) { this.waveDetailDao = waveDetailDao; } public Boolean addWaveDetailVO(WaveDetailVO waveDetailVO) { validate(waveDetailVO); waveDetailDao.addDO(waveDetailVO); return true; } public List<WaveDetailVO> queryWaveDetailVOList( WaveDetailQueryVO waveDetailQueryVO) { return waveDetailDao.queryDO(waveDetailQueryVO); } public WaveDetailVO getWaveDetailVOByID(Long id) { return (WaveDetailVO) waveDetailDao.getDOByID(id); } public Boolean modifyWaveDetailVO(WaveDetailVO waveDetailVO) { return waveDetailDao.updateDO(waveDetailVO); } public Boolean deleteWaveDetailVOByID(Long id) { return waveDetailDao.delDO(id); } public List<WaveDetailVO> getWaveDetailVOByOutgoingID(Long id) { WaveDetailQueryVO queryVO = new WaveDetailQueryVO(); queryVO.setWaveId(id); queryVO.setSize(Integer.MAX_VALUE); return waveDetailDao.queryDO(queryVO); } public Boolean batchAddWaveDetailVO(List<WaveDetailVO> waveDetailVOs) { return waveDetailDao.batchAddDO(waveDetailVOs); } public Boolean batchModifyWaveDetailVO(List<WaveDetailVO> waveDetailVOs) { return waveDetailDao.batchModifyDO(waveDetailVOs); } public Boolean batchDeleteWaveDetailVO(List<WaveDetailVO> waveDetailVOs) { return waveDetailDao.batchDeleteDO(waveDetailVOs); } public Boolean batchDeleteWaveDetailVOByID(List<Long> waveDetailIDs) { return waveDetailDao.batchDeleteDOByID(waveDetailIDs); } }
package com.gome.manager.domain; import java.util.ArrayList; import java.util.List; /** * * 会议投票实体类. * * <pre> * 修改日期 修改人 修改原因 * 2015年11月6日 caowei 新建 * </pre> */ public class MeetingVote { //ID private Long id; //会议编号 private String code; //投票人 private String perId; //题目编号 private String questionCode; //题目编号 private String status; //选择答案 private String auswer; //选择答案 private String wide; //选择答案 private String height; public String getWide() { return wide; } public void setWide(String wide) { this.wide = wide; } public String getHeight() { return height; } public void setHeight(String height) { this.height = height; } private List<MeetingVoteResult> voteResultList = new ArrayList<MeetingVoteResult>(); public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public List<MeetingVoteResult> getVoteResultList() { return voteResultList; } public void setVoteResultList(List<MeetingVoteResult> voteResultList) { this.voteResultList = voteResultList; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getPerId() { return perId; } public void setPerId(String perId) { this.perId = perId; } public String getQuestionCode() { return questionCode; } public void setQuestionCode(String questionCode) { this.questionCode = questionCode; } public String getAuswer() { return auswer; } public void setAuswer(String auswer) { this.auswer = auswer; } }
package poi; import com.alibaba.fastjson.JSON; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Description * @auther denny * @create 2020-01-03 14:07 */ public class Crawl6_3 { public static void main(String[] args) throws Exception { List<String> keywords = Arrays.asList( "运动健身:海滨浴场", "运动健身:瑜伽", "运动健身:羽毛球馆", "运动健身:乒乓球馆", "运动健身:网球场", "运动健身:篮球场", "运动健身:足球场", "运动健身:壁球场", "运动健身:橄榄球", "运动健身:马术", "运动健身:赛马场", "运动健身:高尔夫场", "运动健身:保龄球馆", "运动健身:台球馆", "运动健身:滑雪", "运动健身:溜冰", "运动健身:跆拳道", "运动健身:舞蹈", "运动健身:综合体育场馆", "运动健身:运动健身场所附属", "运动健身:其它运动健身", "汽车", "汽车:加油站", "汽车:加油站:中石化", "汽车:加油站:中石油", "汽车:加油站:加油加气站", "汽车:加油站:加气站", "汽车:加油站:充电站", "汽车:加油站:其它加油站", "汽车:停车场", "汽车:停车场设施", "汽车:停车场设施:停车缴费处", "汽车:停车场设施:可充电停车位", "汽车:停车场设施:小客车停车位", "汽车:停车场设施:其它停车位", "汽车:汽车销售", "汽车:汽车维修", "汽车:摩托车", "汽车:摩托车:摩托车服务相关", "汽车:摩托车:销售", "汽车:摩托车:维修", "汽车:摩托车:其它摩托车", "汽车:驾校", "汽车:汽车租赁", "汽车:汽车养护", "汽车:洗车场", "汽车:汽车俱乐部", "汽车:汽车救援", "汽车:汽车配件销售", "汽车:二手车交易市场", "汽车:车辆管理机构", "汽车:其它汽车", "医疗保健", "医疗保健:综合医院", "医疗保健:专科医院", "医疗保健:专科医院:齿科", "医疗保健:专科医院:整形", "医疗保健:专科医院:眼科", "医疗保健:专科医院:耳鼻喉", "医疗保健:专科医院:胸科", "医疗保健:专科医院:骨科", "医疗保健:专科医院:肿瘤", "医疗保健:专科医院:脑科", "医疗保健:专科医院:妇产科", "医疗保健:专科医院:儿科", "医疗保健:专科医院:传染病医院", "医疗保健:专科医院:精神病医院", "医疗保健:专科医院:其它专科医院", "医疗保健:诊所", "医疗保健:急救中心", "医疗保健:药房药店", "医疗保健:疾病预防", "医疗保健:体检", "医疗保健:医疗保健附属", "医疗保健:医疗保健附属:门诊部", "医疗保健:医疗保健附属:急诊", "医疗保健:医疗保健附属:其它医疗保健附属", "医疗保健:其它医疗保健", "酒店宾馆", "酒店宾馆:酒店宾馆", "酒店宾馆:星级酒店", "酒店宾馆:经济型酒店", "酒店宾馆:公寓式酒店", "酒店宾馆:旅馆招待所", "酒店宾馆:度假村", "酒店宾馆:农家院", "酒店宾馆:青年旅社", "酒店宾馆:酒店宾馆附属", "酒店宾馆:其它酒店宾馆", "旅游景点", "旅游景点:风景名胜", "旅游景点:公园", "旅游景点:植物园", "旅游景点:动物园", "旅游景点:水族馆", "旅游景点:城市广场", "旅游景点:世界遗产", "旅游景点:国家级景点", "旅游景点:省级景点", "旅游景点:纪念馆", "旅游景点:寺庙道观", "旅游景点:教堂", "旅游景点:海滩", "旅游景点:清真寺", "旅游景点:景点公园附属", "旅游景点:其它旅游景点", "文化场馆", "文化场馆:博物馆", "文化场馆:展览馆", "文化场馆:科技馆", "文化场馆:图书馆", "文化场馆:图书馆:儿童图书馆", "文化场馆:天文馆" ); List<Map<String, String>> mapList = Arrays.asList( // new HashMap<String, String>() {{ put("name","XT新塘地王广场");put("gps","113.614610,23.116868");put("adcode","增城区"); }}, // new HashMap<String, String>() {{ put("name","HD花来又来广百");put("gps","113.233118,23.397909");put("adcode","花都区"); }}, // new HashMap<String, String>() {{ put("name","GZ中华广场");put("gps","113.282599,23.125918");put("adcode","越秀区"); }}, // new HashMap<String, String>() {{ put("name","GZ正佳广场");put("gps","113.327030,23.132175");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ增城增江");put("gps","113.839980,23.280614");put("adcode","增城区"); }}, // new HashMap<String, String>() {{ put("name","GZ增城万达广场");put("gps","113.815277,23.276029");put("adcode","增城区"); }}, // new HashMap<String, String>() {{ put("name","GZ增城锦绣");put("gps","113.811451,23.286874");put("adcode","增城区"); }}, // new HashMap<String, String>() {{ put("name","GZ增城挂绿广场");put("gps","113.833175,23.291104");put("adcode","增城区"); }}, // new HashMap<String, String>() {{ put("name","GZ增城东汇城");put("gps","113.823881,23.285385");put("adcode","增城区"); }}, // new HashMap<String, String>() {{ put("name","GZ粤信大厦");put("gps","113.332718,23.094867");put("adcode","海珠区"); }}, // // new HashMap<String, String>() {{ put("name","GZ越秀粤海");put("gps","113.269620,23.119570");put("adcode","越秀区"); }}, // new HashMap<String, String>() {{ put("name","GZ又一城");put("gps","113.321506,23.132529");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ宜安广场店");put("gps","113.284827,23.134374");put("adcode","越秀区"); }}, // new HashMap<String, String>() {{ put("name","GZ新市新天地");put("gps","113.264642,23.191245");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ欣荣宏商贸城");put("gps","113.590780,23.532056");put("adcode","从化区"); }}, // new HashMap<String, String>() {{ put("name","GZ晓港湾");put("gps","113.294085,23.071044");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ夏茅金铂");put("gps","113.251922,23.213315");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ下渡路");put("gps","113.307988,23.099633");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ西湖路");put("gps","113.267460,23.123320");put("adcode","越秀区"); }}, // new HashMap<String, String>() {{ put("name","GZ西城都荟");put("gps","113.240152,23.110770");put("adcode","荔湾区"); }}, // // new HashMap<String, String>() {{ put("name","GZ五号停机坪");put("gps","113.264528,23.181180");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ万家福广场");put("gps","113.298757,23.332571");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ天银广场");put("gps","113.321196,23.137388");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河直通车");put("gps","113.321962,23.135186");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河娱乐店");put("gps","113.340038,23.135646");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河曜一城");put("gps","113.344600,23.141779");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河万科");put("gps","113.402586,23.168336");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河天汇广场");put("gps","113.332151,23.116274");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河天环广场");put("gps","113.325673,23.131722");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河尚德大厦");put("gps","113.344295,23.139679");put("adcode","天河区"); }}, // // new HashMap<String, String>() {{ put("name","GZ天河路");put("gps","113.330170,23.132829");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河乐都汇");put("gps","113.376466,23.126979");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河骏唐广场");put("gps","113.383416,23.125877");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河好又多店");put("gps","113.378272,23.124939");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河国金中心");put("gps","113.322846,23.118160");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ天河城");put("gps","113.323209,23.132363");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ太阳新天地");put("gps","113.343720,23.123460");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ四季时尚荟");put("gps","113.401970,23.119117");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ时尚天河");put("gps","113.319942,23.141626");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ狮岭家宜多");put("gps","113.155865,23.461858");put("adcode","花都区"); }}, // // new HashMap<String, String>() {{ put("name","GZ圣地广场");put("gps","113.229792,23.132650");put("adcode","荔湾区"); }}, // new HashMap<String, String>() {{ put("name","GZ三元里大道");put("gps","113.251677,23.172184");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ祈福缤纷世界");put("gps","113.332024,22.969600");put("adcode","番禺区"); }}, // new HashMap<String, String>() {{ put("name","GZ南沙万达广场");put("gps","113.532817,22.794742");put("adcode","南沙区"); }}, // new HashMap<String, String>() {{ put("name","GZ南沙华汇广场");put("gps","113.557716,22.800598");put("adcode","南沙区"); }}, // new HashMap<String, String>() {{ put("name","GZ南沙大岗达森");put("gps","113.406128,22.802368");put("adcode","南沙区"); }}, // new HashMap<String, String>() {{ put("name","GZ南沙COCO");put("gps","113.547061,22.807183");put("adcode","南沙区"); }}, // new HashMap<String, String>() {{ put("name","GZ木棉湾广场");put("gps","113.329069,23.185444");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ名盛广场");put("gps","113.270708,23.121961");put("adcode","越秀区"); }}, // new HashMap<String, String>() {{ put("name","GZ美东百货");put("gps","113.297243,23.128294");put("adcode","越秀区"); }}, // // new HashMap<String, String>() {{ put("name","GZ梅花园");put("gps","113.321062,23.178549");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ漫广场");put("gps","113.424873,23.112497");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ萝岗区高德汇");put("gps","113.452784,23.167779");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ萝岗奥园");put("gps","113.501067,23.174213");put("adcode","黄埔区"); }}, // new HashMap<String, String>() {{ put("name","GZ罗冲围友田城");put("gps","113.227654,23.144227");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ龙骏广场");put("gps","113.226801,23.177741");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ龙洞商业楼");put("gps","113.368398,23.193693");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ六福广场");put("gps","113.327173,23.086339");put("adcode","海珠区"); }}, // // new HashMap<String, String>() {{ put("name","GZ荔园新天地");put("gps","113.345624,22.919752");put("adcode","番禺区"); }}, // new HashMap<String, String>() {{ put("name","GZ荔湾荔胜广场");put("gps","113.233291,23.073920");put("adcode","荔湾区"); }}, // new HashMap<String, String>() {{ put("name","GZ荔湾花地人家");put("gps","113.230071,23.095207");put("adcode","荔湾区"); }}, // new HashMap<String, String>() {{ put("name","GZ丽影广场");put("gps","113.321047,23.095769");put("adcode","越秀区"); }}, // new HashMap<String, String>() {{ put("name","GZ乐峰广场");put("gps","113.259017,23.089267");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ金田百佳");put("gps","113.335354,23.141910");put("adcode","天河区"); }}, // new HashMap<String, String>() {{ put("name","GZ金沙洲梦乐城");put("gps","113.194081,23.147189");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ金海岸城市广");put("gps","113.602585,23.127689");put("adcode","增城区"); }}, // new HashMap<String, String>() {{ put("name","GZ金国商业广场");put("gps","113.253981,23.204473");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ江夏新天地");put("gps","113.282532,23.211133");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ江南西人");put("gps","113.272263,23.095610");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ江高家宜多");put("gps","113.232854,23.274836");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ黄埔潮楼购物");put("gps","113.424875,23.112499");put("adcode","黄埔区"); }}, // new HashMap<String, String>() {{ put("name","GZ花都盛妆");put("gps","113.209466,23.382311");put("adcode","花都区"); }}, // new HashMap<String, String>() {{ put("name","GZ花都融创茂");put("gps","113.604209,23.140307");put("adcode","花都区"); }}, // new HashMap<String, String>() {{ put("name","GZ花都摩登");put("gps","113.204970,23.386230");put("adcode","花都区"); }}, // new HashMap<String, String>() {{ put("name","GZ花都骏壹万邦");put("gps","113.227390,23.405389");put("adcode","花都区"); }}, // new HashMap<String, String>() {{ put("name","GZ花都建设路");put("gps","113.210069,23.374717");put("adcode","花都区"); }}, // new HashMap<String, String>() {{ put("name","GZ花都百花广场");put("gps","113.223112,23.379196");put("adcode","花都区"); }}, // new HashMap<String, String>() {{ put("name","GZ恒宝华庭店");put("gps","113.241603,23.118105");put("adcode","荔湾区"); }}, // // new HashMap<String, String>() {{ put("name","GZ合生广场");put("gps","113.275185,23.088314");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ好信广场");put("gps","113.302410,23.070008");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ海珠万国广场");put("gps","113.272883,23.101389");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ海珠保利广场");put("gps","113.280536,23.102284");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ海印自由闲");put("gps","113.285863,23.126264");put("adcode","越秀区"); }}, // new HashMap<String, String>() {{ put("name","GZ海铂丽廊广场");put("gps","113.312450,23.103120");put("adcode","海珠区"); }}, // new HashMap<String, String>() {{ put("name","GZ广州亚运城");put("gps","113.477228,22.940801");put("adcode","番禺区"); }}, // new HashMap<String, String>() {{ put("name","GZ广州骐利广场");put("gps","113.235294,23.156027");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ广州龙归金铂");put("gps","113.293413,23.267821");put("adcode","白云区"); }}, // new HashMap<String, String>() {{ put("name","GZ广州领好广场");put("gps","113.526046,23.085015");put("adcode","黄埔区"); }}, // new HashMap<String, String>() {{ put("name","GZ广州金铂广场");put("gps","113.325608,23.196350");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ广州江燕路");put("gps","113.277967,23.082078");put("adcode","海珠区"); }}, new HashMap<String, String>() {{ put("name","GZ广州江南新地");put("gps","113.270569,23.094681");put("adcode","海珠区"); }}, new HashMap<String, String>() {{ put("name","GZ广州黄埔万达");put("gps","113.466258,23.167464");put("adcode","黄浦区"); }}, new HashMap<String, String>() {{ put("name","GZ广州花都国华");put("gps","113.208262,23.375644");put("adcode","花都区"); }}, new HashMap<String, String>() {{ put("name","GZ广州高德汇");put("gps","113.347353,23.169586");put("adcode","天河区"); }}, new HashMap<String, String>() {{ put("name","GZ广州大道北");put("gps","113.326234,23.187919");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ广州卜蜂莲花");put("gps","113.256967,23.160901");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ广州白云万达");put("gps","113.266379,23.172775");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ广州白云凯德");put("gps","113.269448,23.181018");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ广天河优托邦");put("gps","113.415600,23.132750");put("adcode","天河区"); }}, new HashMap<String, String>() {{ put("name","GZ广海珠同乐汇");put("gps","113.271532,23.104079");put("adcode","海珠区"); }}, new HashMap<String, String>() {{ put("name","GZ广百新一城");put("gps","113.266656,23.092994");put("adcode","海珠区"); }}, new HashMap<String, String>() {{ put("name","GZ高德置地春");put("gps","113.322172,23.119884");put("adcode","天河区"); }}, new HashMap<String, String>() {{ put("name","GZ富丽城");put("gps","113.311339,23.026651");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ富景花园店");put("gps","113.289506,23.092654");put("adcode","海珠区"); }}, new HashMap<String, String>() {{ put("name","GZ凤凰城");put("gps","113.576840,23.125721");put("adcode","增城区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺愉园酒店");put("gps","113.366310,22.941120");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺永旺广场");put("gps","113.384300,22.934005");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺雄峰城");put("gps","113.303334,22.970348");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺喜悦天地");put("gps","113.361600,22.949411");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺万科里");put("gps","113.378011,22.932867");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺万达广场");put("gps","113.348742,22.990104");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺人人佳");put("gps","113.387531,23.004902");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺桥东路店");put("gps","113.367009,22.936720");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番禺建华汇");put("gps","113.315316,23.024777");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ番山商贸城店");put("gps","113.365102,22.941331");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ动漫星城");put("gps","113.267021,23.125887");put("adcode","越秀区"); }}, new HashMap<String, String>() {{ put("name","GZ东平时代都荟");put("gps","113.309423,23.248031");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ东急新天地店");put("gps","113.248754,23.114504");put("adcode","荔湾区"); }}, new HashMap<String, String>() {{ put("name","GZ大学城新天地");put("gps","113.393421,23.060742");put("adcode","番禺区"); }}, // new HashMap<String, String>() {{ put("name","GZ大石金科广场");put("gps","113.325036,23.010095");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ潮流新天地");put("gps","113.327676,23.130793");put("adcode","天河区"); }}, new HashMap<String, String>() {{ put("name","GZ保利中环广场");put("gps","113.281489,23.137405");put("adcode","越秀区"); }}, new HashMap<String, String>() {{ put("name","GZ百事佳商业城");put("gps","113.543391,23.110467");put("adcode","黄埔区"); }}, new HashMap<String, String>() {{ put("name","GZ百佳购物广场");put("gps","113.454076,23.100816");put("adcode","黄埔区"); }}, new HashMap<String, String>() {{ put("name","GZ白云万民广场");put("gps","113.228646,23.212658");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ白云时代广场");put("gps","113.304646,23.221700");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ白云岭南新世");put("gps","113.265106,23.181008");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ白云来利");put("gps","113.357180,23.292247");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ白云百信西广");put("gps","113.262607,23.194289");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ白云安华汇");put("gps","113.302696,23.226385");put("adcode","白云区"); }}, new HashMap<String, String>() {{ put("name","GZ奥园广场");put("gps","113.357256,22.924046");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","GZ奥园城市广场");put("gps","113.300915,23.051377");put("adcode","番禺区"); }}, new HashMap<String, String>() {{ put("name","CH新世纪广场");put("gps","113.267766,23.115023");put("adcode","番禺区"); }} ); Map<String,String> params = new HashMap<>(); params.put("key", "UUUBZ-XPCKP-2GODC-LWD26-3NFL7-NJFPN"); params.put("page_size", "20"); String url = "https://apis.map.qq.com/ws/place/v1/search" ; String[][] values = new String[mapList.size()+1][keywords.size()+1]; String[][] jsons = new String[mapList.size()+1][keywords.size()+1]; for (int i=0;i<mapList.size();i++) { Map<String, String> map = mapList.get(i); String name = map.get("name"); String boundary = "nearby(%s,500)"; String[] strings = map.get("gps").split(","); String gps = strings[1] + "," + strings[0]; boundary = String.format(boundary,gps); params.put("boundary",boundary); values[i][0] = name; jsons[i][0] = name; for(int j=0;j<keywords.size();j++){ String keyword = keywords.get(j); String category = "category=" + keyword; params.put("keyword",category); String result = HttpClientUtils.doGet(url, params); String count = JSON.parseObject(result).getString("count"); values[i][j+1] = count; String json = JSON.parseObject(result).getString("data"); jsons[i][j+1] = json; Thread.sleep(300); } System.out.println(name + "结束"); } String[] title = new String[keywords.size()+1]; title[0] = "门店名称"; for (int j=0;j<keywords.size();j++) { title[j+1] = keywords.get(j); } String path = "D:\\java_work\\demo\\common\\src\\resources\\" + "业态查询三级维度Count_3.1.xlsx"; ExcelUtils.createExcel(path, "sheet1", title, null); ExcelUtils.appendToExcel(path,"sheet1",values); String jsonPath = "D:\\java_work\\demo\\common\\src\\resources\\" + "业态查询三级维度Count_Json_3.xlsx"; ExcelUtils excelUtils = new ExcelUtils(); excelUtils.createExcel(jsonPath, "sheet1", title, null); excelUtils.appendToExcel(jsonPath, "sheet1", jsons); } }
package com.datagraph.core.common; import com.datagraph.common.Context; import com.datagraph.common.cons.DBType; import com.datagraph.core.db.datasource.DatabaseManager; import javax.sql.DataSource; /** * Created by Denny Joseph on 6/4/16. */ public class ContextImpl extends Context { private DatabaseManager dbManager; private DBType dbType; public ContextImpl(DatabaseManager dbManager, DBType dbType) { this.dbManager = dbManager; this.dbType = dbType; } @Override public DataSource getDataSource(String name) { return dbManager.getDataSource(name); } public DBType getDBType() { return dbType; } }
package com.citibank.ods.entity.pl.valueobject; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Date; import com.citibank.ods.common.entity.valueobject.BaseEntityVO; /** * @author m.nakamura * * Representação da tabela de Conta de Produto */ public class BaseTo3ProductAccountEntityVO extends BaseEntityVO { // Código da conta produto private BigInteger m_prodAcctCode = null; // Código da sub conta produto private BigInteger m_prodUnderAcctCode = null; // Número do cliente no CMS private BigInteger m_custNbr = null; // Número do relacionamento do cliente. private BigInteger m_reltnNbr = null; // Número da conta corrente associada ao produto. private BigInteger m_curAcctNbr = null; //Número da conta cci associada ao produto. private String m_investCurAcctNbr = ""; // Código do produto. private String m_prodCode = ""; // Código do sistema origem do cadastro do produto. private String m_sysCode = ""; // Codigo da segmentação do sistema origem do cadastro do produto. private BigInteger m_sysSegCode = null; // Número da conta produto no processador de origem. private String m_origProdAcctNbr = ""; // Data de abertura/início do contrato da conta produto. private Date m_prodAcctStaDate = null; // Data de fim/encerramento do contrato da conta produto. private Date m_prodAcctEndDate = null; // Código da situação do contrato da conta produto. private String m_prodAcctSitCode = ""; // Status registro. private String m_recStatCode = ""; //Indicador de Carteira Administrada da Conta Produto private String m_prodAcctPortfMgmtCode = ""; //Indicador de política sob contrato 23A private String m_prodAcctPlcy23aInd = ""; //Indicador de política sob contrato 23B private String m_prodAcctPlcy23bInd = ""; //Código Isin private String m_prodAcctIsinCode = ""; //Código de entidade legal private BigInteger m_prodAcctLegalBusCode = null; //Código do usuário que aprovou o cadastro do registro private String m_lastAuthUserId = ""; //Data e hora que o usuário aprovou o registro do cadastro private Date m_lastAuthDate = null; //Código do usuário da última alteração private String m_lastUpdUserId = ""; //Data e hora da última alteração private Date m_lastUpdDate = null; //Última Posição Carregada private Date m_balRefDate = null; //Valor private BigDecimal m_acctAmt = null; private String segCode = ""; private String segName = ""; public String getSegName() { return segName; } public void setSegName(String segName) { this.segName = segName; } public String getSegCode() { return segCode; } public void setSegCode(String segCode) { this.segCode = segCode; } /** * Seta o código da conta produto. * * @param prodAcctCode_ - O código da conta produto. */ public void setProdAcctCode( BigInteger prodAcctCode_ ) { m_prodAcctCode = prodAcctCode_; } /** * Recupera o código da conta produto. * * @return BigInteger - Retorna o código da conta produto. */ public BigInteger getProdAcctCode() { return m_prodAcctCode; } /** * Seta o código da sub conta produto * * @param prodUnderAcctCode_ - O código da sub conta produto */ public void setProdUnderAcctCode( BigInteger prodUnderAcctCode_ ) { m_prodUnderAcctCode = prodUnderAcctCode_; } /** * Recupera o código da sub conta produto * * @return BigInteger - Retorna o código da sub conta produto */ public BigInteger getProdUnderAcctCode() { return m_prodUnderAcctCode; } /** * Seta o número do cliente no CMS * * @param custNbr_ - O número do cliente no CMS */ public void setCustNbr( BigInteger custNbr_ ) { m_custNbr = custNbr_; } /** * Recupera o número do cliente no CMS * * @return BigInteger - Retorna o número do cliente no CMS */ public BigInteger getCustNbr() { return m_custNbr; } /** * Seta o número do relacionamento do cliente. * * @param reltnNbr_ - O número do relacionamento do cliente. */ public void setReltnNbr( BigInteger reltnNbr_ ) { m_reltnNbr = reltnNbr_; } /** * Recupera o número do relacionamento do cliente. * * @return BigInteger - Retorna o número do relacionamento do cliente. */ public BigInteger getReltnNbr() { return m_reltnNbr; } /** * Seta o número da conta corrente associada ao produto. * * @param curAcctNbr_ - O número da conta corrente associada ao produto. */ public void setCurAcctNbr( BigInteger curAcctNbr_ ) { m_curAcctNbr = curAcctNbr_; } /** * Recupera o número da conta corrente associada ao produto. * * @return BigInteger - Retorna o número da conta corrente associada ao * produto. */ public BigInteger getCurAcctNbr() { return m_curAcctNbr; } /** * Seta o código do produto. * * @param prodCode_ - O código do produto. */ public void setProdCode( String prodCode_ ) { m_prodCode = prodCode_; } /** * Recupera o código do produto. * * @return String - Retorna o código do produto. */ public String getProdCode() { return m_prodCode; } /** * Seta o código do sistema origem do cadastro do produto. * * @param sysCode_ - O código do sistema origem do cadastro do produto. */ public void setSysCode( String sysCode_ ) { m_sysCode = sysCode_; } /** * Recupera o código do sistema origem do cadastro do produto. * * @return String - Retorna o código do sistema origem do cadastro do produto. */ public String getSysCode() { return m_sysCode; } /** * Seta o codigo da segmentação do sistema origem do cadastro do produto. * * @param sysSegCode_ - O codigo da segmentação do sistema origem do cadastro * do produto. */ public void setSysSegCode( BigInteger sysSegCode_ ) { m_sysSegCode = sysSegCode_; } /** * Recupera o codigo da segmentação do sistema origem do cadastro do produto. * * @return BigInteger - Retorna o codigo da segmentação do sistema origem do * cadastro do produto. */ public BigInteger getSysSegCode() { return m_sysSegCode; } /** * Seta o número da conta produto no processador de origem. * * @param origProdAcctNbr_ - O número da conta produto no processador de * origem. do produto. */ public void setOrigProdAcctNbr( String origProdAcctNbr_ ) { m_origProdAcctNbr = origProdAcctNbr_; } /** * Recupera o número da conta produto no processador de origem. * * @return BigInteger - Retorna o número da conta produto no processador de * origem. */ public String getOrigProdAcctNbr() { return m_origProdAcctNbr; } /** * Seta a data de abertura/início do contrato da conta produto. * * @param prodAcctStaDate_ - A data de abertura/início do contrato da conta * produto. */ public void setProdAcctStaDate( Date prodAcctStaDate_ ) { m_prodAcctStaDate = prodAcctStaDate_; } /** * Recupera a data de abertura/início do contrato da conta produto. * * @return Date - Retorna a data de abertura/início do contrato da conta * produto. */ public Date getProdAcctStaDate() { return m_prodAcctStaDate; } /** * Seta a data de fim/encerramento do contrato da conta produto. * * @param prodAcctEndDate_ - A data de fim/encerramento do contrato da conta * produto. */ public void setProdAcctEndDate( Date prodAcctEndDate_ ) { m_prodAcctEndDate = prodAcctEndDate_; } /** * Recupera a data de fim/encerramento do contrato da conta produto. * * @return Date - Retorna a data de fim/encerramento do contrato da conta * produto. */ public Date getProdAcctEndDate() { return m_prodAcctEndDate; } /** * Seta o código da situação do contrato da conta produto. * * @param prodAcctSitCode_ - O código da situação do contrato da conta * produto. */ public void setProdAcctSitCode( String prodAcctSitCode_ ) { m_prodAcctSitCode = prodAcctSitCode_; } /** * Recupera o código da situação do contrato da conta produto. * * @return String - Retorna o código da situação do contrato da conta produto. */ public String getProdAcctSitCode() { return m_prodAcctSitCode; } /** * Seta o status registro. * * @param recStatCode_ - O status registro. */ public void setRecStatCode( String recStatCode_ ) { m_recStatCode = recStatCode_; } /** * Recupera o status registro. * * @return String - Retorna o status registro. */ public String getRecStatCode() { return m_recStatCode; } /** * @return Retorna data/hora da aprovação do cadastro. */ public Date getLastAuthDate() { return m_lastAuthDate; } /** * @param lastAuthDate_.Seta data/hora da aprovação do cadastro. */ public void setLastAuthDate( Date lastAuthDate_ ) { m_lastAuthDate = lastAuthDate_; } /** * @return Retorna o usuário que aprovou a última alteração. */ public String getLastAuthUserId() { return m_lastAuthUserId; } /** * @param lastAuthUserId_.Seta o usuário que aprovou a última alteração. */ public void setLastAuthUserId( String lastAuthUserId_ ) { m_lastAuthUserId = lastAuthUserId_; } /** * @return Retorna data/hora da última atualização. */ public Date getLastUpdDate() { return m_lastUpdDate; } /** * @param lastUpdDate_.Seta data/hora da última atualização. */ public void setLastUpdDate( Date lastUpdDate_ ) { m_lastUpdDate = lastUpdDate_; } /** * @return Retorna usuário da última atualização. */ public String getLastUpdUserId() { return m_lastUpdUserId; } /** * @param lastUpdUserId_.Seta o usuário da última atualização. */ public void setLastUpdUserId( String lastUpdUserId_ ) { m_lastUpdUserId = lastUpdUserId_; } /** * @return Retorna o código Isin. */ public String getProdAcctIsinCode() { return m_prodAcctIsinCode; } /** * @param prodAcctIsinCode_.Seta o código Isin. */ public void setProdAcctIsinCode( String prodAcctIsinCode_ ) { m_prodAcctIsinCode = prodAcctIsinCode_; } /** * @return Retorna o código da entidade legal. */ public BigInteger getProdAcctLegalBusCode() { return m_prodAcctLegalBusCode; } /** * @param prodAcctLegalBusCode_.Seta o código da entidade legal. */ public void setProdAcctLegalBusCode( BigInteger prodAcctLegalBusCode_ ) { m_prodAcctLegalBusCode = prodAcctLegalBusCode_; } /** * @return Retorna o indicador de política 23A. */ public String getProdAcctPlcy23aInd() { return m_prodAcctPlcy23aInd; } /** * @param prodAcctPlcy23aInd_.Seta o indicador de política 23A. */ public void setProdAcctPlcy23aInd( String prodAcctPlcy23aInd_ ) { m_prodAcctPlcy23aInd = prodAcctPlcy23aInd_; } /** * @return Retorna o indicador de política 23B. */ public String getProdAcctPlcy23bInd() { return m_prodAcctPlcy23bInd; } /** * @param prodAcctPlcy23bInd_.Seta o indicador de política 23B. */ public void setProdAcctPlcy23bInd( String prodAcctPlcy23bInd_ ) { m_prodAcctPlcy23bInd = prodAcctPlcy23bInd_; } /** * @return Retorna o código da carteira administrada da conta produto. */ public String getProdAcctPortfMgmtCode() { return m_prodAcctPortfMgmtCode; } /** * @param prodAcctPortfMgmtCode_.Seta o código da carteira administrada da * conta produto. */ public void setProdAcctPortfMgmtCode( String prodAcctPortfMgmtCode_ ) { m_prodAcctPortfMgmtCode = prodAcctPortfMgmtCode_; } /** * @return Retorna o Valor */ public BigDecimal getAcctAmt() { return m_acctAmt; } /** * @return a Última Posição Carregada */ public Date getBalRefDate() { return m_balRefDate; } /** * @param AcctAmt_.Seta o valor */ public void setAcctAmt(BigDecimal m_acctAmt_) { m_acctAmt = m_acctAmt_; } /** * @param BalRefDate_.Seta a Última Posição Carregada */ public void setBalRefDate(Date m_balRefDate_) { m_balRefDate = m_balRefDate_; } /** * @return */ public String getInvestCurAcctNbr() { return m_investCurAcctNbr; } /** * @param string */ public void setInvestCurAcctNbr(String m_investCurAcctNbr_) { m_investCurAcctNbr = m_investCurAcctNbr_; } }
package com.memefilter.imagefilter.impl; import com.memefilter.imagefilter.ImageFilter; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; import org.springframework.test.context.junit4.SpringRunner; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import static org.assertj.core.api.Assertions.*; /** * Created by aross on 18/02/17. */ @RunWith(SpringRunner.class) @EnableAutoConfiguration @ComponentScan(basePackages = {"com.memefilter.imagefilter.impl"}) public class MemeImageFilterTest { @Autowired @Qualifier("imageFilter") private ImageFilter imageFilter; @Test public void getImageTextThrowsOnNullImage() { assertThatThrownBy(() -> imageFilter.getImageText(null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Image must not be null."); } @Test public void getImageTextReturnsEmptyStringIfNoTextFound() { final String result = getTextFromImageResource("solid-black.png"); assertThat(result).isEqualTo(""); } @Test public void getImageTextReturnsTextForClearImage() { final String result = getTextFromImageResource("handle-clear.png"); assertThat(result).isEqualToIgnoringCase("If you can't handle me at my worst, you don't deserve me at my best"); } private String getTextFromImageResource(final String filename) { final InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename); BufferedImage image = null; try { image = ImageIO.read(resourceAsStream); } catch (final IOException e) { fail("Unable to read image.", e); } return imageFilter.getImageText(image); } }
package com.example.zverek.treasure; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Toast; import com.example.zverek.treasure.validator.Validator; import java.io.FileNotFoundException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { ImageButton img ; final int Pick_image = 1; Bitmap bitmap; ImageView imgview; EditText name,nik,pass1,pass2; String ename=null,enik=null,epass1=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); img = (ImageButton) findViewById(R.id.myimgbtn); imgview = (ImageView) findViewById(R.id.imageVieww); name = (EditText)findViewById(R.id.editText); nik = (EditText)findViewById(R.id.editText2); pass1 = (EditText)findViewById(R.id.editText3); pass2 = (EditText)findViewById(R.id.editText4); Button b = (Button) findViewById(R.id.button); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in = new Intent(getApplicationContext(),Vhod.class); startActivity(in); } }); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent pickPhoto = new Intent(Intent.ACTION_PICK); pickPhoto.setType("image/*"); startActivityForResult(pickPhoto, Pick_image); img.setVisibility(img.GONE); imgview.setVisibility(ImageView.VISIBLE); } }); imgview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent pickPhoto = new Intent(Intent.ACTION_PICK); pickPhoto.setType("image/*"); startActivityForResult(pickPhoto, Pick_image); } }); Button btn_reg = (Button)findViewById(R.id.button2); btn_reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Validator validator = new Validator(); ename = validator.validname(name.getText().toString()); if(ename.equals(name.getText().toString())){ enik = validator.validnik(nik.getText().toString()); if(enik.equals(nik.getText().toString())){ epass1 = validator.validpass(pass1.getText().toString(),pass2.getText().toString()); if(epass1.equals(pass2.getText().toString())){ imgview = validator.validphoto(imgview); if(imgview!=null){ Intent intent = new Intent(getApplicationContext(),TwoMainActivity.class); intent.putExtra("name",ename); intent.putExtra("nik",enik); intent.putExtra("pass",epass1); startActivity(intent); }else{ Toast.makeText(getApplicationContext(),"Загрузите фото",Toast.LENGTH_SHORT).show(); } } else{ Toast.makeText(getApplicationContext(),epass1,Toast.LENGTH_SHORT).show(); } }else{Toast.makeText(getApplicationContext(),enik,Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(getApplicationContext(),ename,Toast.LENGTH_SHORT).show();} } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case Pick_image: if(resultCode == RESULT_OK){ Uri uri = data.getData(); try { InputStream input = getContentResolver().openInputStream(uri); bitmap = BitmapFactory.decodeStream(input); imgview.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } } } }
package com.microsoft.hsg.android.hvsample; import android.app.Activity; import android.os.Bundle; import android.support.annotation.Nullable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import com.microsoft.hsg.HVException; import com.microsoft.hsg.android.simplexml.HealthVaultApp; import com.microsoft.hsg.android.simplexml.ShellActivity; import com.microsoft.hsg.android.simplexml.client.HealthVaultClient; import com.microsoft.hsg.android.simplexml.client.RequestCallback; import com.microsoft.hsg.android.simplexml.methods.getthings3.request.ThingRequestGroup2; import com.microsoft.hsg.android.simplexml.methods.getthings3.response.ThingResponseGroup2; import com.microsoft.hsg.android.simplexml.things.thing.Thing2; import com.microsoft.hsg.android.simplexml.things.types.medication.Medication; import com.microsoft.hsg.android.simplexml.things.types.types.PersonInfo; import com.microsoft.hsg.android.simplexml.things.types.types.Record; import com.microsoft.hsg.android.simplexml.things.types.weight.Weight; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemSelectedListener; public class MainMedicationActivity extends Activity { private HealthVaultApp mService; private HealthVaultClient mHVClient; private Record mCurrentRecord; private static final String mCurrentMeds = "Current medications"; private static final String mPastMeds = "Past medications"; private static final int mIndex = 0; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.medication_main); mService = HealthVaultApp.getInstance(); mHVClient = new HealthVaultClient(); mCurrentRecord = HealthVaultApp.getInstance().getCurrentRecord(); LinearLayout addMeddicationTile = (LinearLayout) findViewById(R.id.medication_layout); addMeddicationTile.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { if (mService.isAppConnected()) { Intent myIntent = new Intent(MainMedicationActivity.this, AddMedicationActivity.class); myIntent.putExtra(Constants.IndexParameter, mIndex); startActivity(myIntent); } else { Toast.makeText(MainMedicationActivity.this, "Please connect to HV from Setting menu!", Toast.LENGTH_SHORT).show(); } } }); setTitle("Medication sample"); } @Override protected void onResume() { super.onResume(); mHVClient.start(); getMedications(); } @Override protected void onPause() { mHVClient.stop(); super.onPause(); } private void getMedications() { mHVClient.asyncRequest(mCurrentRecord.getThingsAsync(ThingRequestGroup2.thingTypeQuery(Medication.ThingType)), new MedicationCallback()); } private void renderMedications(List<Thing2> things) { if(!things.isEmpty()) { Medication meds = (Medication) things.get(mIndex).getDataXml().getAny().getThing().getData(); TextView medicationTitle = (TextView) findViewById(R.id.medication_title); TextView medsName = (TextView) findViewById(R.id.medication_name); TextView dosage = (TextView) findViewById(R.id.dosage_strength); TextView prescribe = (TextView) findViewById(R.id.prescribed_date); final String dose = meds.getDose().getDisplay().toString(); final String strength = meds.getStrength().getDisplay(); final String name = meds.getName().getText(); medsName.setText(name); dosage.setText(dose + ", " + strength); if (meds.getDateDiscontinued() == null) { medicationTitle.setText(mCurrentMeds); } else { medicationTitle.setText(mPastMeds); final String monthStart = String.valueOf(meds.getDateStarted().getStructured().getDate().getM()); final String dayStart = String.valueOf(meds.getDateStarted().getStructured().getDate().getD()); final String yearStart = String.valueOf(meds.getDateStarted().getStructured().getDate().getY()); final String prescribed = String.format("prescribed: " + monthStart + "/" + dayStart + "/" + yearStart); String expired = ""; if (meds.getDateDiscontinued() != null) { final String monthEnd = String.valueOf(meds.getDateStarted().getStructured().getDate().getM()); final String dayEnd = String.valueOf(meds.getDateStarted().getStructured().getDate().getD()); final String yearEnd = String.valueOf(meds.getDateStarted().getStructured().getDate().getY()); expired = String.format("Expired: " + monthEnd + "/" + dayEnd + "/" + yearEnd); } prescribe.setText(prescribed + " " + expired); } } else { Toast.makeText(MainMedicationActivity.this, "Currently there are no medications entered for user!", Toast.LENGTH_SHORT).show(); } } public class MedicationCallback<Object> implements RequestCallback { public MedicationCallback() { } @Override public void onError(HVException exception) { Toast.makeText(MainMedicationActivity.this, String.format("An error occurred. " + exception.getMessage()), Toast.LENGTH_SHORT).show(); } @Override public void onSuccess(java.lang.Object obj) { renderMedications(((ThingResponseGroup2)obj).getThing()); } } }
package homework; import java.util.Scanner; public class degree { public static void main(String[] args) { // TODO Auto-generated method stub // DegreesC = 5(DegreesF −32)/9 // Enter a temperature in degrees Fahrenheit: 72 // 72 degrees Fahrenheit is 22.2 degrees Celsius Scanner keyboard = new Scanner(System.in); System.out.println("Enter a temperature in degrees Fahrenheit:"); int Fahrenheit, Celsius; Fahrenheit = keyboard.nextInt(); Celsius = 5 * (Fahrenheit - 32) / 9; System.out.println(Fahrenheit + "degrees Fahrenheit is " + Celsius + " degrees Celsius"); } }
package norswap.autumn; import norswap.autumn.memo.*; import norswap.autumn.parsers.*; import norswap.utils.NArrays; import norswap.utils.Slot; import norswap.utils.Util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.function.IntPredicate; import java.util.function.Predicate; import java.util.function.Supplier; /** * This class implements a domain specific language (DSL) for creating parsers. It's just * a nicer API than having to piece together parser constructors. * * <p>This class features methods that return a {@link rule} object wrapping a parser. * Methods can be called on this wrapper to create further wrappers. e.g.: * * <pre> * {@code * Parser arith = digit().at_least(1).sep(1, choice("+", "-")).get(); * } * </pre> * * <p><b>Usage:</b> To use the DSL, create a class (the <b>grammar class</b>) that extends this class * (recommended). It's also possible to instantiate this class and to call methods on it. * * <p><b>Automatic conversion:</b> Most DSL methods take instances of {@code Object} instead of * {@link Parser}. Parsers passed like this are simply passed through. Parsers are extracted out * of {@link rule} instances, and {@code String} instances are replaced by calling {@link #str} * with the string. * * <p><b>Whitespace handling:</b> set {@link #ws} to skip whitespace after matching certain parser * (most importantly, when using {@link #word}). */ public class DSL { // --------------------------------------------------------------------------------------------- /** * The token factory used by the grammar. */ public final Tokens tokens; // --------------------------------------------------------------------------------------------- /** * Creates a new instance using the default memoization strategy for tokens (currently: an * 8-slot cache). */ public DSL () { this.tokens = new Tokens(() -> new MemoCache(8, false)); } // --------------------------------------------------------------------------------------------- /** * Creates a new instance using a custom memoization strategy for tokens. */ public DSL (Supplier<Memoizer> token_memo) { this.tokens = new Tokens(token_memo); } // --------------------------------------------------------------------------------------------- /** * Change this to specify the whitespace parser used for {@link #word} and {@link rule#word} and * used after automatically converted string literals. * * <p>This parser <b>must</b> always succeed, meaning it must be able to succeed matching * the empty string. * * <p>null by default, meaning no whitespace will be matched. * * <p>Both {@link #word} and {@link rule#word} capture the value of this field when called, so * setting the value of this field should be one of the first thing you do in your grammar. * * <p>If {@link #exclude_ws_errors} is set, its {@link Parser#exclude_errors} field will be * automatically set as long as {@link #word(String)} or {@link rule#word()} is called at least * once (otherwise you'll have to set it yourself if you use {@code ws} explicitly). */ public rule ws = null; // --------------------------------------------------------------------------------------------- private Parser ws() { Parser p = ws.get(); if (!p.exclude_errors && exclude_ws_errors) p.exclude_errors = true; return p; } // --------------------------------------------------------------------------------------------- /** * Whether to exclude errors inside whitespace ({@link #ws}) from counting against the furthest * parse error ({@link Parse#error}). True by default. */ public boolean exclude_ws_errors = true; // --------------------------------------------------------------------------------------------- private Parser compile (Object item) { if (item instanceof rule) return ((rule) item).get(); if (item instanceof Parser) return (Parser) item; if (item instanceof String) return new StringMatch((String) item, null); throw new Error("unknown item type " + item.getClass()); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link Sequence} of the given parsers. */ public rule seq (Object... parsers) { return new rule(new Sequence(NArrays.map(parsers, new Parser[0], this::compile))); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link Choice} between the given parsers. */ public rule choice (Object... parsers) { return new rule(new Choice(NArrays.map(parsers, new Parser[0], this::compile))); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link Longest} match choice between the given parsers. */ public rule longest (Object... parsers) { return new rule(new Longest(NArrays.map(parsers, new Parser[0], this::compile))); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link StringMatch} parser for the given string. */ public rule str (String string) { return new rule(new StringMatch(string, null)); } // ---------------------------------------------------------------------------------------------˜ /** * Returns a {@link StringMatch} parser with post whitespace matching dependent on {@link * #ws}. */ public rule word (String string) { return new rule(new StringMatch(string, ws())); } // --------------------------------------------------------------------------------------------- /** * A parser that always succeeds. */ public rule empty = new rule(new Empty()); // --------------------------------------------------------------------------------------------- /** * A parser that always fails. */ public rule fail = new rule(new Fail()); // --------------------------------------------------------------------------------------------- /** * A {@link CharPredicate} parser that matches any character. */ public rule any = new rule(CharPredicate.any()); // --------------------------------------------------------------------------------------------- /** * A {@link CharPredicate} that matches a single character. */ public rule character (char character) { return new rule(CharPredicate.single(character)); } // --------------------------------------------------------------------------------------------- /** * A {@link CharPredicate} that matches a single ASCII alphabetic character. */ public rule alpha = new rule(CharPredicate.alpha()); // --------------------------------------------------------------------------------------------- /** * A {@link CharPredicate} that matches a single ASCII alpha-numeric character. */ public rule alphanum = new rule(CharPredicate.alphanum()); // --------------------------------------------------------------------------------------------- /** * A {@link CharPredicate} that matches a single decimal digit. */ public rule digit = new rule(CharPredicate.digit()); // --------------------------------------------------------------------------------------------- /** * A {@link CharPredicate} that matches a single hexadecimal digit (for letters, both * the lowercase and uppercase forms are allowed). */ public rule hex_digit = new rule(CharPredicate.hex_digit()); // --------------------------------------------------------------------------------------------- /** * A {@link CharPredicate} that matches a single octal digit. */ public rule octal_digit = new rule(CharPredicate.octal_digit()); // --------------------------------------------------------------------------------------------- /** * A rule that matches zero or more of the usual whitespace characters (spaces, tabs (\t), line * return (\n) and carriage feed (\r)). Fit to be assigned to {@link #ws}. */ public rule usual_whitespace = set(" \t\n\r").at_least(0); // --------------------------------------------------------------------------------------------- /** * Returns a {@link CharPredicate} parser that matches an (inclusive) range of characters. */ public rule range (char start, char end) { return new rule(CharPredicate.range(start, end)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link CharPredicate} parser that matches a set of characters. */ public rule set (String string) { return new rule(CharPredicate.set(string)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link CharPredicate} parser that matches a set of characters. */ public rule set (char... chars) { return new rule(CharPredicate.set(chars)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link CharPredicate} parser with name "cpred". */ public rule cpred (IntPredicate predicate) { return new rule(new CharPredicate("cpred", predicate)); } // --------------------------------------------------------------------------------------------- /** * Returns an {@link ObjectPredicate} parser with name "opred". */ public rule opred (Predicate<Object> predicate) { return new rule(new ObjectPredicate("opred", predicate)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LazyParser} using the given supplier. */ public rule lazy_parser (Supplier<Parser> supplier) { return new rule(new LazyParser(supplier)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LazyParser} using the given supplier. */ public rule lazy (Supplier<rule> supplier) { return new rule(new LazyParser(() -> supplier.get().parser)); } // --------------------------------------------------------------------------------------------- private rule recursive_parser (Function<rule, Parser> f) { Slot<Parser> slot = new Slot<>(); slot.x = f.apply(new rule(new LazyParser(() -> slot.x))); return new rule(slot.x); } // --------------------------------------------------------------------------------------------- /** * Returns the parser returned by {@code f}, which takes as parameter a {@link LazyParser} able * to recursively invoke the parser {@code f} will return, but *not* in left position. */ public rule recursive (Function<rule, rule> f) { return recursive_parser(r -> f.apply(r).get()); } // --------------------------------------------------------------------------------------------- /** * Returns the parser returned by {@code f}, which takes as parameter a {@link LazyParser} able * to recursively invoke the parser {@code f} will return, including in left position. * If the parser is both left- and right-recursive, the result will be right-associative. * * <p>In general, prefer using {@link #right(Object, Object, StackAction.Push)} or one of * its variants. */ public rule left_recursive (Function<rule, rule> f) { return recursive_parser(r -> new LeftRecursive(f.apply(r).get(), false)); } // --------------------------------------------------------------------------------------------- /** * Returns the parser returned by {@code f}, which takes as parameter a {@link LazyParser} able * to recursively invoke the parser {@code f} will return, including in left position. * If the parser is both left- and right-recursive, the result will be left-associative. * * <p>In general, prefer using {@link #left(Object, Object, StackAction.Push)} or one of * its variants. */ public rule left_recursive_left_assoc (Function<rule, rule> f) { return recursive_parser(r -> new LeftRecursive(f.apply(r).get(), true)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LeftAssoc} parser that allows left-only matches. */ public rule left (Object left, Object operator, Object right, StackAction.Push step) { return new rule( new LeftAssoc(compile(left), compile(operator), compile(right), false, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LeftAssoc} parser that allows left-only matches, and with no step * action performed. */ public rule left (Object left, Object operator, Object right) { return new rule( new LeftAssoc(compile(left), compile(operator), compile(right), false, null)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LeftAssoc} parser that allows left-only matches, with the same * operand on both sides. */ public rule left (Object operand, Object operator, StackAction.Push step) { Parser coperand = compile(operand); return new rule(new LeftAssoc(coperand, compile(operator), coperand, false, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LeftAssoc} parser that does not allow left-only matches. */ public rule left_full (Object left, Object operator, Object right, StackAction.Push step) { return new rule( new LeftAssoc(compile(left), compile(operator), compile(right), true, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LeftAssoc} parser that does not allow left-only matches, with the same * operand on both sides. */ public rule left_full (Object operand, Object operator, StackAction.Push step) { Parser coperand = compile(operand); return new rule(new LeftAssoc(coperand, compile(operator), coperand, true, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link RightAssoc} parser that allows left-only matches. */ public rule right (Object left, Object operator, Object right, StackAction.Push step) { return new rule( new RightAssoc(compile(left), compile(operator), compile(right), false, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link RightAssoc} parser that allows left-only matches, with the same * operand on both sides. */ public rule right (Object operand, Object operator, StackAction.Push step) { Parser coperand = compile(operand); return new rule(new RightAssoc(coperand, compile(operator), coperand, false, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link RightAssoc} parser that does not allow left-only matches. */ public rule right_full (Object left, Object operator, Object right, StackAction.Push step) { return new rule( new RightAssoc(compile(left), compile(operator), compile(right), true, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link RightAssoc} parser that does not allow left-only matches, with the same * operand on both sides. */ public rule right_full (Object operand, Object operator, StackAction.Push step) { Parser coperand = compile(operand); return new rule(new RightAssoc(coperand, compile(operator), coperand, true, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LeftAssoc} parser that matches a postfix expression (the right-hand * side matches nothing). Allows left-only matches. */ public rule postfix (Object operand, Object operator, StackAction.Push step) { return new rule( new LeftAssoc(compile(operand), compile(operator), empty.get(), false, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link LeftAssoc} parser that matches a postfix expression (the right-hand * side matches nothing). Does not allow left-only matches. */ public rule postfix_full (Object operand, Object operator, StackAction.Push step) { return new rule( new LeftAssoc(compile(operand), compile(operator), empty.get(), true, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link RightAssoc} parser that matches a prefix expression (the left-hand * side matches nothing). Allows right-only matches. */ public rule prefix (Object operator, Object operand, StackAction.Push step) { return new rule( new RightAssoc(empty.get(), compile(operand), compile(operator), false, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link RightAssoc} parser that matches a prefix expression (the left-hand * side matches nothing). Does not allow right-only matches. */ public rule prefix_full (Object operator, Object operand, StackAction.Push step) { return new rule( new RightAssoc(empty.get(), compile(operand), compile(operator), true, step)); } // --------------------------------------------------------------------------------------------- /** * Returns a {@link TokenChoice} parser that selects between the passed token parsers or base * token parsers. These tokens must have been defined previously (using {@link rule#token()}, * <b>lazy references won't work.</b> */ public rule token_choice (Object... parsers) { Parser[] compiled_parsers = new Parser[parsers.length]; for (int i = 0; i < parsers.length; ++i) { if (parsers[i] instanceof String) throw new Error("Token choice requires exact parser reference and does not work " + "with automatic string conversion. String:" + parsers[i]); compiled_parsers[i] = compile(parsers[i]); } return new rule(tokens.token_choice(compiled_parsers)); } // --------------------------------------------------------------------------------------------- /** * Wraps the given parser into a {@link rule}. */ public rule rule (Parser parser) { return new rule(parser); } // --------------------------------------------------------------------------------------------- /** * Hints that a lambda represents a {@link StackAction.PushWithParse} action, so it * can be used with DSL methods that except a {@link StackAction.Push}. */ public StackAction.PushWithParse with_parse (StackAction.PushWithParse action) { return action; } // --------------------------------------------------------------------------------------------- /** * Hints that a lambda represents a {@link StackAction.PushWithString} action, so it * can be used with DSL methods that except a {@link StackAction.Push}. */ public StackAction.PushWithString with_string (StackAction.PushWithString action) { return action; } // --------------------------------------------------------------------------------------------- /** * Hints that a lambda represents a {@link StackAction.PushWithList} action, so it * can be used with DSL methods that except a {@link StackAction.Push}. */ public StackAction.PushWithList with_list (StackAction.PushWithList action) { return action; } // --------------------------------------------------------------------------------------------- /** * Wraps a {@link Parser} to enable builder-style parser construction. * * <p>Functionally, this is a parser wrapper, but it is called "rule" to prettify grammar * definitions (where each rule is a field declaration whose type is "rule"). * * <p>Extract the parser using {@link #get()}. */ public final class rule { private final Parser parser; private final int lookback; private final boolean peek_only; private final boolean collect_on_fail; private rule (Parser parser) { this.parser = parser; this.lookback = 0; this.peek_only = false; this.collect_on_fail = false; } private rule (Parser parser, int lookback, boolean peek_only, boolean collect_on_fail) { this.parser = parser; this.lookback = lookback; this.peek_only = peek_only; this.collect_on_fail = collect_on_fail; } private rule make (Parser parser) { if (lookback != 0) throw new IllegalStateException("You're trying to create a new rule wrapper from " + "a rule wrapper on which you defined a lookback, without specifying a " + "corresponding collect action. Wrapper holds: " + this); if (peek_only) throw new IllegalStateException("You're trying to create a new rule wrapper from " + "a rule wrapper on which you defined the peek_only property, without " + "specifying a corresponding collect action. Wrapper holds: " + this); return new rule(parser); } /** * Returns the DSL instance this rule belongs to. */ public DSL dsl() { return DSL.this; } /** * Returns this wrapper, after setting the name of the parser to the given name. Only works * for parsers with a name property: {@link Collect}, {@link CharPredicate} and {@link * ObjectPredicate}. */ public rule named (String name) { /**/ if (parser instanceof Collect) ((Collect) parser).name = name; else if (parser instanceof CharPredicate) ((CharPredicate) parser).name = name; else if (parser instanceof ObjectPredicate) ((ObjectPredicate) parser).name = name; else throw new Error("Wrapped parser doesn't have a name property: " + this); return this; } /** * Returns the wrapped parser. */ public Parser get() { return parser; } /** * Returns a negation ({@link Not}) of the parser. */ public rule not() { return make(new Not(parser)); } /** * Returns a lookahead version ({@link Lookahead}) of the parser. */ public rule ahead() { return make(new Lookahead(parser)); } /** * Returns an optional version ({@link Optional}) of the parser. */ public rule opt() { return make(new Optional(parser)); } /** * Returns a repetition ({@link Repeat}) of exactly {@code n} times the parser. */ public rule repeat (int n) { return make(new Repeat(n, true, parser)); } /** * Returns a repetition ({@link Repeat}) of at least {@code min} times the parser. */ public rule at_least (int min) { return make(new Repeat(min, false, parser)); } /** * Returns an {@link Around} parser that matches at least {@code min} repetition * of the parser, separated by the {@code separator} parser. */ public rule sep (int min, Object separator) { return make(new Around(min, false, false, parser, compile(separator))); } /** * Returns an {@link Around} parser that matches exactly {@code n} repetition * of the parser, separated by the {@code separator} parser. */ public rule sep_exact (int n, Object separator) { return make(new Around(n, true, false, parser, compile(separator))); } /** * Returns an {@link Around} parser that matches at least {@code min} repetition of the * parser, separated by the {@code separator} parser, and allowing for a trailing separator. */ public rule sep_trailing (int min, Object separator) { return make(new Around(min, false, true, parser, compile(separator))); } /** * Returns a {@link Sequence} composed of the parser followed by the whitespace parser * {@link #ws}. */ public rule word() { return make(new Sequence(parser, ws())); } /** * Returns a {@link GuardedRecursion} wrapping the parser. */ public rule guarded() { return make(new GuardedRecursion(parser)); } /** * Returns a new {@link TokenParser} wrapping the parser, adding it as a possible token * kind. The underlying parser will have its {@link Parser#exclude_errors} flag set to true. */ public rule token() { return make(tokens.token_parser(parser)); } /** * Pre-defines the {@link Collect#lookback} lookback parameter for a {@link Collect} parser. * Once this parameter is set, the only parser that this rule wrapper can be used to build * is a {@link Collect} parser. */ public rule lookback (int lookback) { if (this.lookback != 0) throw new IllegalStateException( "Trying to redefine the lookback on rule wrapper holding: " + this); return new rule(this.parser, lookback, this.peek_only, this.collect_on_fail); } /** * Pre-defines the {@link Collect#pop} parameter for a {@link Collect} parser to be * false. Once this parameter is set, the only parser that this rule wrapper can be used to * build is a {@link Collect} parser. */ public rule peek_only() { if (peek_only) throw new IllegalStateException( "Attempting to set the peek_only property twice on rule wrapper holding: " + this); return new rule(this.parser, lookback, true, this.collect_on_fail); } /** * Pre-defines the {@link Collect#action_on_fail} parameter for a {@link Collect} parser to * be true. Once this parameter is set, the only parser that this rule wrapper can be used * to build is a {@link Collect} parser. */ public rule collect_on_fail() { if (collect_on_fail) throw new IllegalStateException( "Attempting to set the collect_on_fail property twice on rule wrapper holding: " + this); return new rule(this.parser, lookback, this.peek_only, true); } /** * Returns a {@link Collect} parser wrapping the parser, performing a simple collect * action ({@link StackAction.Collect}). * * <p>Can be modified by {@link #peek_only()}, {@link #lookback(int)} and {@link * #collect_on_fail()}. By default: has no lookback, pops the items off the stack on success * and does nothing in case of failure. */ public rule collect (StackAction.Collect action) { return new rule(new Collect("collect", parser, lookback, collect_on_fail, !peek_only, action)); } /** * Returns a {@link Collect} parser wrapping the parser, performing a string-capturing * collect action ({@link StackAction.CollectWithString}). * * <p>See {@link #collect(StackAction.Collect)} for details of how the behaviour of this * parser can be modified. */ public rule collect_with_string (StackAction.CollectWithString action) { return new rule(new Collect("collect_with_string", parser, lookback, collect_on_fail, !peek_only, action)); } /** * Returns a {@link Collect} parser wrapping the parser, performing a list-capturing * collect action ({@link StackAction.CollectWithList}). * * <p>See {@link #collect(StackAction.Collect)} for details of how the behaviour of this * parser can be modified. */ public rule collect_with_list (StackAction.CollectWithList action) { return new rule(new Collect("collect_with_list", parser, lookback, collect_on_fail, !peek_only, action)); } /** * Returns a {@link Collect} parser wrapping the parser, performing a simple pushing collect * action ({@link StackAction.Push}). * * <p>See {@link #collect(StackAction.Collect)} for details of how the behaviour of this * parser can be modified. */ public rule push (StackAction.Push action) { return new rule(new Collect("push", parser, lookback, collect_on_fail, !peek_only, action)); } /** * Returns a {@link Collect} parser wrapping the parser that pushes the string matched * by the parser onto the value stack. * * <p>See {@link #collect(StackAction.Collect)} for details of how the behaviour of this * parser can be modified. */ public rule push_string_match () { return new rule(new Collect("push_string_match", parser, lookback, collect_on_fail, !peek_only, (StackAction.CollectWithString) (p,xs,str) -> p.stack.push(str))); } /** * Returns a {@link Collect} parser wrapping the parser that pushes the sublist matched * by the parser onto the value stack. * * <p>See {@link #collect(StackAction.Collect)} for details of how the behaviour of this * parser can be modified. */ public rule push_list_match () { return new rule(new Collect("push_list_match", parser, lookback, collect_on_fail, !peek_only, (StackAction.CollectWithString) (p,xs,lst) -> p.stack.push(lst))); } /** * Returns a {@link Collect} parser wrapping the parser. The action consists of pushing a * list of all collected items onto the stack, casted to the type denoted by {@code klass}. * * <p>See {@link #collect(StackAction.Collect)} for details of how the behaviour of this * parser can be modified. */ public <T> rule as_list(Class<T> klass) { return new rule(new Collect("as_list", parser, lookback, collect_on_fail, !peek_only, (StackAction.PushWithParse) (p, xs) -> Arrays.asList(Util.<T[]>cast(xs)))); } /** * Returns a peek-only {@link Collect} parser wrapping the parser. The returned parser * pushes true or false on the stack depending on whether the underlying parser succeeds or * fails. The returned parser always succeeds. * * <p>The collect flags {@link #lookback(int)}, {@link #peek_only()} and {@link * #collect_on_fail()} may not be set when calling this method. */ public rule as_bool() { return make(new Collect("as_bool", new Optional(parser), 0, true, false, (StackAction.PushWithParse) (p, xs) -> xs != null)); } /** * Returns a peek-only {@link Collect} parser wrapping the parser. The returned parser * pushes the supplied value on the stack if the underlying parser is successful. * * <p>The collect flags {@link #lookback(int)}, {@link #peek_only()} and {@link * #collect_on_fail()} may not be set when calling this method. */ public rule as_val (Object value) { return make(new Collect("as_val", parser, 0, false, false, (StackAction.PushWithParse) (p, xs) -> value)); } /** * Returns a peek-only {@link Collect} parser wrapping the parser. The returned parser * pushes null on the stack if and only if the underlying parser fails. The returned parser * always succeeds. * * <p>The collect flags {@link #lookback(int)}, {@link #peek_only()} and {@link * #collect_on_fail()} may not be set when calling this method. */ public rule maybe() { return make(new Collect("maybe", parser, 0, true, false, (StackAction.Collect) (p,xs) -> { if (xs == null) p.stack.push((Object) null); })); } /** * Returns a new {@link Memo} parser wrapping the parser. The parse results will be memoized * in a {@link MemoTable}. */ public rule memo() { return memo((Function<Parse, Object>) null); } /** * Returns a new context-sensitive {@link Memo} parser wrapping the parser. The parse * results will be memoized in a {@link MemoTable}. {@code extractor} will be used to * extract and compare the relevant context (see {@link Memo} for details). */ public rule memo (Function<Parse, Object> extractor) { ParseState<Memoizer> memoizer = new ParseState<>(new Slot<>(parser), () -> new MemoTable(false)); return make(new Memo(parser, memoizer, extractor)); } /** * Returns a new {@link Memo} parser wrapping the parser. The parse results will be memoized * in a {@link MemoCache} with {@code n} slots (must be strictly positive). */ public rule memo (int n) { return memo(n, null); } /** * Returns a new context-sensitive {@link Memo} parser wrapping the parser. The parse * results will be memoized in a {@link MemoCache} with {@code n} slots (must be strictly * positive). {@code extractor} will be used to extract and compare the relevant context * (see {@link Memo} for details). */ public rule memo (int n, Function<Parse, Object> extractor) { if (n <= 0) throw new IllegalArgumentException ("A memo cache must have a strictly positive number of entries."); ParseState<Memoizer> memoizer = new ParseState<>(new Slot<>(parser), () -> new MemoCache(n, false)); return make(new Memo(parser, memoizer, extractor)); } /** * Returns a new {@link Memo} wrapping the parser. The parse results will be memoized using * the supplied memoizer. This form is useful when you want to share a single memoizer * amongst multiple parsers. */ public rule memo (ParseState<Memoizer> memoizer) { return make(new Memo(parser, memoizer, null)); } /** * Returns a new context-sensitive {@link Memo} wrapping the parser. The parse results will * be memoized using the supplied memoizer. This form is useful when you want to share a * single memoizer amongst multiple parsers. {@code extractor} will be used to extract and * compare the relevant context (see {@link Memo} for details). */ public rule memo (ParseState<Memoizer> memoizer, Function<Parse, Object> extractor) { return make(new Memo(parser, memoizer, extractor)); } @Override public String toString() { return parser.toString(); } } // --------------------------------------------------------------------------------------------- /** * Returns a new list wrapping the given array after casting it to to an array of type {@code T}. * * <p>Use the {@code this.<T>list(array)} form to specify the type {@code T}. */ public <T> List<T> list (Object... array) { //noinspection unchecked return Arrays.asList((T[]) array); } // --------------------------------------------------------------------------------------------- /** * Returns a new list wrapping the slice {@code [start, length[} of {@code array} after casting * it to to an array of type {@code T}. * * <p>Use the {@code this.<T>list(array)} form to specify the type {@code T}. */ public <T> List<T> list (int start, Object[] array) { //noinspection unchecked return Arrays.asList(Arrays.copyOfRange((T[]) array, start, array.length)); } // --------------------------------------------------------------------------------------------- /** * Returns a new list wrapping the slice {@code [start, end[} of {@code array} after casting it * to to an array of type {@code T}. * * <p>Use the {@code this.<T>list(array)} form to specify the type {@code T}. */ public <T> List<T> list (int start, int end, Object[] array) { //noinspection unchecked return Arrays.asList(Arrays.copyOfRange((T[]) array, start, end)); } // --------------------------------------------------------------------------------------------- /** * Returns a new empty list of type T. */ public <T> List<T> list () { return Collections.emptyList(); } // --------------------------------------------------------------------------------------------- /** * Returns the given object, casted to type {@code T}. * * <p>The target type {@code T} can be inferred from the assignment target. * e.g. {@code Object x = "hello"; String y = $(x);} */ public <T> T $ (Object object) { //noinspection unchecked return (T) object; } // --------------------------------------------------------------------------------------------- /** * Returns the array item at the given index, casted to type {@code T}. * * @see #$ */ public <T> T $ (Object[] array, int index) { //noinspection unchecked return (T) array[index]; } // --------------------------------------------------------------------------------------------- /** * Fetches all the fields declared in the class of this object (i.e. {@code this.getClass()}), * and for those that are of type {@link rule} or {@link Parser}, sets the rule name to the name * of the field, if no rule name has been set already. */ public void make_rule_names () { make_rule_names(this.getClass()); } // --------------------------------------------------------------------------------------------- /** * Fetches all the fields declared in {@code klass}, and for those that are of type {@link rule} * or {@link Parser}, sets the rule name to the name of the field, if no rule name has been set * already. */ public void make_rule_names (Class<?> klass) { make_rule_names(DSL.class.getFields()); make_rule_names(klass.getDeclaredFields()); } // --------------------------------------------------------------------------------------------- // Note: supresses warning on `f.isAccessible()` deprecated after Java 8 in favor of // `f.canAccess(this)`. Language level 8 with a later JDK will yield a warning while we // can't use `canAccess` yet. @SuppressWarnings("deprecation") private void make_rule_names (Field[] fields) { try { for (Field f : fields) { if (!Modifier.isPublic(f.getModifiers()) && !f.isAccessible()) f.setAccessible(true); if (f.getType().equals(rule.class)) { rule w = (rule) f.get(this); if (w == null) continue; Parser p = w.get(); if (p.rule() == null) p.set_rule(f.getName()); } else if (f.getType().equals(Parser.class)) { Parser p = (Parser) f.get(this); if (p == null) continue; if (p.rule() == null) p.set_rule(f.getName()); } } } // Should always be a security exception: illegal access prevented by `setAccessible`. catch (SecurityException e) { throw new RuntimeException( "The security policy does not allow Autumn to access private or protected fields " + "in the grammar. Either make all the fields containing grammar rules public, " + "or amend the security policy by granting: " + "permission java.lang.reflect.ReflectPermission \"suppressAccessChecks\";", e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } // --------------------------------------------------------------------------------------------- }
/* * 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 Entities; /** * * @author ASUS */ public class Fournisseur { private int id_fournisseur; private String nom; private int numero; private String Email; public Fournisseur(int id_fournisseur, String nom, int numero, String Email) { this.id_fournisseur = id_fournisseur; this.nom = nom; this.numero = numero; String regex = "^[\\w-_\\.+]*[\\w-_\\.]\\@([\\w]+\\.)+[\\w]+[\\w]$"; if(Email.matches(regex)){ this.Email = Email; } } public String getEmail() { return Email; } public int getId_fournisseur() { return id_fournisseur; } public String getNom() { return nom; } public int getNumero() { return numero; } public void setId_fournisseur(int id_fournisseur) { this.id_fournisseur = id_fournisseur; } public void setNom(String nom) { this.nom = nom; } public void setNumero(int numero) { this.numero = numero; } public void setEmail(String Email) { this.Email = Email; } }
package com.huruilei.designpattern.observer; import java.util.ArrayList; import java.util.List; /** * @author: huruilei * @date: 2019/10/31 * @description: * @return */ public class WeatherData implements Subject { private List observers; private float temperature; private float humidity; private float pressure; public WeatherData(){ observers = new ArrayList(); } @Override public void registerObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { int i = observers.indexOf(o); if(i>0){ observers.remove(o); } } @Override public void notifyObservers() { for (int i = 0;i<observers.size();i++) { Observer observer = (Observer) observers.get(i); observer.update(temperature,humidity,pressure); } } public void measurementsChanged(){ notifyObservers(); } public void setMeasurements(float temperature,float humidity,float pressure){ this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; measurementsChanged(); } }
/* * The MIT License * * Copyright 2012 Universidad de Montemorelos A. C. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package mx.edu.um.academia.web; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.util.CalendarFactoryUtil; import com.liferay.portal.kernel.util.UnicodeFormatter; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.model.User; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.ServiceContextFactory; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.portlet.journal.model.JournalArticle; import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.RenderRequest; import javax.validation.Valid; import mx.edu.um.academia.dao.RespuestaDao; import mx.edu.um.academia.model.Respuesta; import mx.edu.um.academia.utils.ComunidadUtil; import mx.edu.um.academia.utils.TextoUtil; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; /** * * @author J. David Mendoza <jdmendoza@um.edu.mx> */ @Controller @RequestMapping("VIEW") public class RespuestaPortlet extends BaseController { @Autowired private RespuestaDao respuestaDao; @Autowired private TextoUtil textoUtil; public RespuestaPortlet() { log.info("Nueva instancia del Controlador de Respuestas"); } @RequestMapping public String lista(RenderRequest request, @RequestParam(required = false) String filtro, @RequestParam(required = false) Integer offset, @RequestParam(required = false) Integer max, @RequestParam(required = false) Integer direccion, @RequestParam(required = false) String order, @RequestParam(required = false) String sort, @RequestParam(required = false) Long pagina, Model modelo) throws SystemException, PortalException { log.debug("Lista de respuestas [filtro: {}, offset: {}, max: {}, direccion: {}, order: {}, sort: {}, pagina: {}]", new Object[]{filtro, offset, max, direccion, order, sort, pagina}); Map<Long, String> comunidades = ComunidadUtil.obtieneComunidades(request); Map<String, Object> params = new HashMap<>(); params.put("comunidades", comunidades.keySet()); if (StringUtils.isNotBlank(filtro)) { params.put("filtro", filtro); } if (StringUtils.isNotBlank(order)) { params.put("order", order); params.put("sort", sort); } params.put("max", max); params.put("offset", offset); params.put("pagina", pagina); params = respuestaDao.lista(params); List<Respuesta> respuestas = (List<Respuesta>) params.get("respuestas"); if (respuestas != null && respuestas.size() > 0) { modelo.addAttribute("respuestas", respuestas); this.pagina(params, modelo, "respuestas", pagina); } return "respuesta/lista"; } @RequestMapping(params = "action=nuevo") public String nuevo(RenderRequest request, Model modelo) throws SystemException, PortalException { log.debug("Nuevo respuesta"); Respuesta respuesta = new Respuesta(); modelo.addAttribute("respuesta", respuesta); modelo.addAttribute("comunidades", ComunidadUtil.obtieneComunidades(request)); return "respuesta/nuevo"; } @RequestMapping(params = "action=nuevoError") public String nuevoError(RenderRequest request, Model modelo) throws SystemException, PortalException { log.debug("Nuevo respuesta despues de error"); modelo.addAttribute("comunidades", ComunidadUtil.obtieneComunidades(request)); return "respuesta/nuevo"; } @RequestMapping(params = "action=crea") public void crea(ActionRequest request, ActionResponse response, @Valid Respuesta respuesta, BindingResult result) throws SystemException, PortalException { log.debug("Creando respuesta {}", respuesta); if (result.hasErrors()) { log.debug("Hubo algun error en la forma, regresando"); response.setRenderParameter("action", "nuevoError"); return; } User creador = PortalUtil.getUser(request); respuestaDao.crea(respuesta, creador); // redirectAttributes.addFlashAttribute("message", "La respuesta ha sido creada exitosamente"); response.setRenderParameter("action", "ver"); response.setRenderParameter("id", respuesta.getId().toString()); } @RequestMapping(params = "action=ver") public String ver(RenderRequest request, @RequestParam Long id, Model modelo) throws PortalException, SystemException { log.debug("Mostrando respuesta {}", id); Respuesta respuesta = respuestaDao.obtiene(id); String texto = textoUtil.obtieneTexto(respuesta.getContenido(), this.getThemeDisplay(request)); if (texto != null) { modelo.addAttribute("texto", texto); } modelo.addAttribute("respuesta", respuesta); return "respuesta/ver"; } @RequestMapping(params = "action=edita") public String edita(RenderRequest request, Model modelo, @RequestParam Long id) throws SystemException, PortalException { log.debug("Edita respuesta"); Respuesta respuesta = respuestaDao.obtiene(id); modelo.addAttribute("respuesta", respuesta); modelo.addAttribute("comunidades", ComunidadUtil.obtieneComunidades(request)); return "respuesta/edita"; } @RequestMapping(params = "action=editaError") public String editaError(RenderRequest request, Model modelo) throws SystemException, PortalException { log.debug("Edita respuesta despues de error"); modelo.addAttribute("comunidades", ComunidadUtil.obtieneComunidades(request)); return "respuesta/edita"; } @RequestMapping(params = "action=actualiza") public void actualiza(ActionRequest request, ActionResponse response, @Valid Respuesta respuesta, BindingResult result) throws SystemException, PortalException { log.debug("Actualizando respuesta {}", respuesta); if (result.hasErrors()) { log.debug("Hubo algun error en la forma, regresando"); response.setRenderParameter("action", "editaError"); } User creador = PortalUtil.getUser(request); respuestaDao.actualiza(respuesta, creador); response.setRenderParameter("action", "ver"); response.setRenderParameter("id", respuesta.getId().toString()); } @RequestMapping(params = "action=elimina") public void elimina(ActionRequest request, @RequestParam Long id) throws PortalException, SystemException { log.debug("eliminando respuesta {}", id); Respuesta respuesta = respuestaDao.obtiene(id); if (respuesta.getContenido() != null) { JournalArticleLocalServiceUtil.deleteJournalArticle(respuesta.getContenido()); } User creador = PortalUtil.getUser(request); respuestaDao.elimina(id, creador); } @RequestMapping(params = "action=nuevoTexto") public String nuevoTexto(RenderRequest request, Model modelo, @RequestParam Long id) throws SystemException, PortalException { log.debug("Nuevo texto para respuesta {}", id); Respuesta respuesta = respuestaDao.obtiene(id); modelo.addAttribute("respuesta", respuesta); return "respuesta/nuevoTexto"; } @RequestMapping(params = "action=creaTexto") public void creaTexto(ActionRequest request, ActionResponse response, @ModelAttribute Respuesta respuesta, @RequestParam String texto) throws SystemException, PortalException { log.debug("Creando texto para respuesta {}", respuesta.getId()); respuesta = respuestaDao.obtiene(respuesta.getId()); StringBuilder sb = new StringBuilder(); sb.append("<?xml version='1.0' encoding='UTF-8'?><root><static-content><![CDATA["); sb.append(texto); sb.append("]]></static-content></root>"); texto = sb.toString(); ThemeDisplay themeDisplay = getThemeDisplay(request); Calendar displayDate; if (themeDisplay != null) { displayDate = CalendarFactoryUtil.getCalendar(themeDisplay.getTimeZone(), themeDisplay.getLocale()); } else { displayDate = CalendarFactoryUtil.getCalendar(); } User creador = PortalUtil.getUser(request); ServiceContext serviceContext = ServiceContextFactory.getInstance(JournalArticle.class.getName(), request); if (respuesta.getContenido() != null) { JournalArticleLocalServiceUtil.deleteJournalArticle(respuesta.getContenido()); } JournalArticle article = textoUtil.crea( respuesta.getNombre(), respuesta.getNombre(), texto, displayDate, creador.getUserId(), respuesta.getComunidadId(), serviceContext); respuesta.setContenido(article.getId()); respuesta = respuestaDao.actualizaContenido(respuesta, creador); response.setRenderParameter("action", "ver"); response.setRenderParameter("id", respuesta.getId().toString()); } @RequestMapping(params = "action=asignaTextoATodas") public void asignaTextoATodas(ActionRequest request, ActionResponse response) throws SystemException, PortalException { log.debug("Asignando texto a todas las que no tienen"); int cont = 0; ThemeDisplay themeDisplay = getThemeDisplay(request); Calendar displayDate; if (themeDisplay != null) { displayDate = CalendarFactoryUtil.getCalendar(themeDisplay.getTimeZone(), themeDisplay.getLocale()); } else { displayDate = CalendarFactoryUtil.getCalendar(); } List<Respuesta> respuestas = respuestaDao.listaSinTexto(themeDisplay.getScopeGroupId()); for(Respuesta respuesta : respuestas) { String texto = respuesta.getNombre(); StringBuilder sb = new StringBuilder(); sb.append("<?xml version='1.0' encoding='UTF-8'?><root><static-content><![CDATA["); sb.append(texto); sb.append("]]></static-content></root>"); texto = sb.toString(); User creador = PortalUtil.getUser(request); ServiceContext serviceContext = ServiceContextFactory.getInstance(JournalArticle.class.getName(), request); if (respuesta.getContenido() != null) { JournalArticleLocalServiceUtil.deleteJournalArticle(respuesta.getContenido()); } JournalArticle article = textoUtil.crea( respuesta.getNombre(), respuesta.getNombre(), texto, displayDate, creador.getUserId(), respuesta.getComunidadId(), serviceContext); respuesta.setContenido(article.getId()); respuesta = respuestaDao.actualizaContenido(respuesta, creador); cont++; } log.debug("##################"); log.debug("##################"); log.debug("##################"); log.debug("Termino de asignar texto a {} respuestas", cont); log.debug("##################"); log.debug("##################"); log.debug("##################"); } @RequestMapping(params = "action=editaTexto") public String editaTexto(RenderRequest request, Model modelo, @RequestParam Long id) throws SystemException, PortalException { log.debug("Edita texto para respuesta {}", id); Respuesta respuesta = respuestaDao.obtiene(id); modelo.addAttribute("respuesta", respuesta); ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY); String texto = textoUtil.obtieneTexto(respuesta.getContenido(), themeDisplay); if (texto != null) { modelo.addAttribute("texto", texto); modelo.addAttribute("textoUnicode", UnicodeFormatter.toString(texto)); } return "respuesta/editaTexto"; } @RequestMapping(params = "action=actualizaTexto") public void actualizaTexto(ActionRequest request, ActionResponse response, @ModelAttribute Respuesta respuesta, @RequestParam String texto) throws SystemException, PortalException { log.debug("Actualizando texto para respuesta {}", respuesta.getId()); respuesta = respuestaDao.obtiene(respuesta.getId()); StringBuilder sb = new StringBuilder(); sb.append("<?xml version='1.0' encoding='UTF-8'?><root><static-content><![CDATA["); sb.append(texto); sb.append("]]></static-content></root>"); texto = sb.toString(); User creador = PortalUtil.getUser(request); JournalArticle ja = JournalArticleLocalServiceUtil.getArticle(respuesta.getContenido()); ja.setUserId(creador.getUserId()); ja.setTitle(respuesta.getNombre()); ja.setDescription(respuesta.getNombre()); ja.setContent(texto); ja.setVersion(ja.getVersion() + 1); JournalArticleLocalServiceUtil.updateJournalArticle(ja); response.setRenderParameter("action", "ver"); response.setRenderParameter("id", respuesta.getId().toString()); } }
package me.rainnny.util; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; public class UtilServer { public static void sendToStaff(String message) { ProxyServer.getInstance().getConsole().sendMessage(message); for (ProxiedPlayer staff : ProxyServer.getInstance().getPlayers()) { if (staff.hasPermission("qbungee.staff")) { staff.sendMessage(message); } } } public static void sendToManagers(String message) { ProxyServer.getInstance().getConsole().sendMessage(message); for (ProxiedPlayer staff : ProxyServer.getInstance().getPlayers()) { if (staff.hasPermission("qbungee.manager")) { staff.sendMessage(message); } } } }
package com.joalib.board.svc; import com.joalib.DAO.DAO; import com.joalib.DTO.Board_Small_CommentDTO; public class SmallCommentChangeService { public boolean SmallCommentChange(Board_Small_CommentDTO dto) { boolean isSuccess = false; DAO dao = DAO.getinstance(); int i = dao.boardSmallCommentChange(dto); if(i > 0) { isSuccess = true; } return isSuccess; } }
package top.qifansfc.study_springboot.domain; import com.fasterxml.jackson.annotation.JsonFormat; import java.sql.Date; public class User { private Integer id; private String name; private Integer age; private String sex; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private String addtime; public Integer getId() { return id; } // public void setId(Integer id) { // this.id = id; // } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddtime() { return addtime; } public void setAddtime(String addtime) { this.addtime = addtime; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", addtime=" + addtime + '}'; } }
package org.vpontus.vuejs.repository; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.jpa.repository.EntityGraph; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.query.Param; import org.vpontus.vuejs.domain.User; /** * * @author vpontus * * */ import java.util.Optional; public interface UserRepository extends JpaRepository<User, Long> { String USERS_BY_USERNAME = "usersByUsername"; String USERS_BY_EMAIL = "usersByEmail"; Optional<User> findUserByUsername(@Param("username") String username); Optional<User> findUserByEmailIgnoreCase(@Param("email")String email); @EntityGraph(attributePaths = "authorities") @Cacheable(cacheNames = USERS_BY_USERNAME) Optional<User> findOneWithAuthoritiesByUsername(@Param("username")String username); @EntityGraph(attributePaths = "authorities") @Cacheable(cacheNames = USERS_BY_EMAIL) Optional<User> findOneWithAuthoritiesByEmail(@Param("email")String email); @EntityGraph(attributePaths = "authorities") Optional<User> findOneWithAuthoritiesById(@Param("id")Long id); }
package sample; import java.io.IOException; import java.net.*; public class UdpConnector implements Runnable { private DatagramSocket socket; private int udpPort = 7000; private int udpPortEcho = 7007; private Controller controller; private boolean receiveMessages = true; public UdpConnector(Controller controller) { this.controller = controller; setupSocket(); } public void setupSocket() { try { socket = new DatagramSocket(udpPort); } catch (SocketException e) { e.printStackTrace(); } } public void closeSocket() { socket.close(); } public void echoServer() { do { UdpMessage msg = receiveMessage(); sendMessage("received: "+ msg.getMessage(), msg.getIp() ); } while (receiveMessages); } public void sendMessage(String string, String ip) { try { sendMessage(string.getBytes(), InetAddress.getByName(ip)); } catch (UnknownHostException e) { e.printStackTrace(); } } public void sendMessage(byte[] bytes, InetAddress address) { DatagramPacket packet = new DatagramPacket(bytes, bytes.length, address, udpPortEcho); try { socket.send(packet); } catch (IOException e) { e.printStackTrace(); } } public UdpMessage receiveMessage() { byte[] buffer = new byte[256]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); try { socket.receive(packet); UdpMessage udpMessage = new UdpMessage(packet.getData(), packet.getLength(), packet.getAddress(), packet.getPort()); System.out.println(udpMessage); return udpMessage; } catch (IOException e) { e.printStackTrace(); return null; } } @Override public void run() { while (true) { echoServer(); //receiveMessage(); } } }
package com.demo; public class IntegerTest { public static final Integer b = 6; public static void main(String[] args) { User user = new User(); user.setName("wyy"); String name = user.getName(); user.setAge(5); Integer a = user.getAge(); user.setAge(6); user.setName("wangyuanye"); System.out.println(a); System.out.println(user.getAge()); System.out.println(name); } }
package testarch.cases; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Cases { private List<String> cases; public Cases(List<String> cases) { this.cases = cases; } public final void fillAllData(String[] object){ cases.addAll(Arrays.asList(object)); } public final void fillOne(String object){ cases.add(object); } public List<String> getCases() { return cases; } }
/** * This class is generated by jOOQ */ package schema.tables; import java.sql.Timestamp; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Identity; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.TableImpl; import schema.BitnamiEdx; import schema.Keys; import schema.tables.records.WorkflowAssessmentworkflowRecord; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class WorkflowAssessmentworkflow extends TableImpl<WorkflowAssessmentworkflowRecord> { private static final long serialVersionUID = 1202195495; /** * The reference instance of <code>bitnami_edx.workflow_assessmentworkflow</code> */ public static final WorkflowAssessmentworkflow WORKFLOW_ASSESSMENTWORKFLOW = new WorkflowAssessmentworkflow(); /** * The class holding records for this type */ @Override public Class<WorkflowAssessmentworkflowRecord> getRecordType() { return WorkflowAssessmentworkflowRecord.class; } /** * The column <code>bitnami_edx.workflow_assessmentworkflow.id</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, Integer> ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * The column <code>bitnami_edx.workflow_assessmentworkflow.created</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, Timestamp> CREATED = createField("created", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.workflow_assessmentworkflow.modified</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, Timestamp> MODIFIED = createField("modified", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.workflow_assessmentworkflow.status</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, String> STATUS = createField("status", org.jooq.impl.SQLDataType.VARCHAR.length(100).nullable(false), this, ""); /** * The column <code>bitnami_edx.workflow_assessmentworkflow.status_changed</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, Timestamp> STATUS_CHANGED = createField("status_changed", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false), this, ""); /** * The column <code>bitnami_edx.workflow_assessmentworkflow.submission_uuid</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, String> SUBMISSION_UUID = createField("submission_uuid", org.jooq.impl.SQLDataType.VARCHAR.length(36).nullable(false), this, ""); /** * The column <code>bitnami_edx.workflow_assessmentworkflow.uuid</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, String> UUID = createField("uuid", org.jooq.impl.SQLDataType.VARCHAR.length(36).nullable(false), this, ""); /** * The column <code>bitnami_edx.workflow_assessmentworkflow.course_id</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, String> COURSE_ID = createField("course_id", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * The column <code>bitnami_edx.workflow_assessmentworkflow.item_id</code>. */ public final TableField<WorkflowAssessmentworkflowRecord, String> ITEM_ID = createField("item_id", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); /** * Create a <code>bitnami_edx.workflow_assessmentworkflow</code> table reference */ public WorkflowAssessmentworkflow() { this("workflow_assessmentworkflow", null); } /** * Create an aliased <code>bitnami_edx.workflow_assessmentworkflow</code> table reference */ public WorkflowAssessmentworkflow(String alias) { this(alias, WORKFLOW_ASSESSMENTWORKFLOW); } private WorkflowAssessmentworkflow(String alias, Table<WorkflowAssessmentworkflowRecord> aliased) { this(alias, aliased, null); } private WorkflowAssessmentworkflow(String alias, Table<WorkflowAssessmentworkflowRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, ""); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return BitnamiEdx.BITNAMI_EDX; } /** * {@inheritDoc} */ @Override public Identity<WorkflowAssessmentworkflowRecord, Integer> getIdentity() { return Keys.IDENTITY_WORKFLOW_ASSESSMENTWORKFLOW; } /** * {@inheritDoc} */ @Override public UniqueKey<WorkflowAssessmentworkflowRecord> getPrimaryKey() { return Keys.KEY_WORKFLOW_ASSESSMENTWORKFLOW_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<WorkflowAssessmentworkflowRecord>> getKeys() { return Arrays.<UniqueKey<WorkflowAssessmentworkflowRecord>>asList(Keys.KEY_WORKFLOW_ASSESSMENTWORKFLOW_PRIMARY, Keys.KEY_WORKFLOW_ASSESSMENTWORKFLOW_SUBMISSION_UUID, Keys.KEY_WORKFLOW_ASSESSMENTWORKFLOW_UUID); } /** * {@inheritDoc} */ @Override public WorkflowAssessmentworkflow as(String alias) { return new WorkflowAssessmentworkflow(alias, this); } /** * Rename this table */ public WorkflowAssessmentworkflow rename(String name) { return new WorkflowAssessmentworkflow(name, null); } }
package com.zhaoyan.ladderball.domain.common.http; public class RequestHeader { /** * 用户id */ public String userToken; /** * app版本号 */ public String clientVersion; /** * 服务版本号 */ public int serviceVersion; /** * 客户端时间 */ public long requestTime; @Override public String toString() { return "RequestHeader{" + "userToken='" + userToken + '\'' + ", clientVersion='" + clientVersion + '\'' + ", serviceVersion=" + serviceVersion + ", requestTime=" + requestTime + '}'; } }
package com.esum.appcommon.security; import com.esum.appcommon.resource.application.Config; public class SecurityFactory { private static SecurityFactory instance = new SecurityFactory(); private SecurityEncoder encoderObject; private SecurityDecoder decoderObject; //private final String DEFAULT_ENCODER_CLASS = "com.sds.acube.ep.security.symmetric.EnDecoder"; //private final String DEFAULT_DECODER_CLASS = "com.sds.acube.ep.security.symmetric.EnDecoder"; private SecurityFactory() { // Properties props = new Properties(); // InputStream fis = null; try { // fis = // getClass().getResourceAsStream("/security/security.properties"); // props.load(fis); String encoderClass = Config.getString("Common", Config.getString("Common", "SECURITY.METHOD") + ".ENCODER"); encoderObject = (SecurityEncoder) Class.forName(encoderClass).newInstance(); String decoderClass = Config.getString("Common", Config.getString("Common", "SECURITY.METHOD") + ".DECODER"); decoderObject = (SecurityDecoder) Class.forName(decoderClass).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static SecurityFactory getInstance() { if (instance == null) { instance = new SecurityFactory(); } return instance; } public void clearInstance() { instance = null; } public SecurityEncoder getEncoder() { return encoderObject; } public SecurityDecoder getDecoder() { return decoderObject; } }
package com.domineer.triplebro.mistakebook.activities; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.ListView; import android.widget.RelativeLayout; import com.domineer.triplebro.mistakebook.R; import com.domineer.triplebro.mistakebook.adapters.ClassAdapter; import com.domineer.triplebro.mistakebook.adapters.ErrorAdapter; import com.domineer.triplebro.mistakebook.adapters.ErrorListAdapter; import com.domineer.triplebro.mistakebook.controllers.AdminManagerController; import com.domineer.triplebro.mistakebook.models.ErrorInfo; import com.domineer.triplebro.mistakebook.views.MyListView; import java.util.List; public class ErrorActivity extends Activity implements View.OnClickListener { private ImageView iv_close_error_list; private ListView lv_error_list; private RelativeLayout rl_image_large; private ImageView iv_image_large; private ImageView iv_close_image_large; private AdminManagerController adminManagerController; List<ErrorInfo> errorInfoList; private ErrorAdapter errorAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_error); initView(); initData(); setOnClickListener(); } private void initView() { iv_close_error_list = (ImageView) findViewById(R.id.iv_close_error_list); lv_error_list = (ListView) findViewById(R.id.lv_error_list); rl_image_large = (RelativeLayout) findViewById(R.id.rl_image_large); iv_image_large = (ImageView) findViewById(R.id.iv_image_large); iv_close_image_large = (ImageView) findViewById(R.id.iv_close_image_large); } private void initData() { adminManagerController = new AdminManagerController(this); errorInfoList = adminManagerController.getErrorList(); errorAdapter = new ErrorAdapter(this,errorInfoList); errorAdapter.setViewInfo(rl_image_large,iv_image_large,iv_close_image_large); lv_error_list.setAdapter(errorAdapter); } private void setOnClickListener() { } @Override public void onClick(View v) { switch (v.getId()){ } } }
/* * The MIT License * * Copyright 2012 Universidad de Montemorelos A. C. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package mx.edu.um.academia.dao; import java.util.ArrayList; import java.util.List; import mx.edu.um.academia.model.Examen; import mx.edu.um.academia.model.ExamenPregunta; import mx.edu.um.academia.model.Pregunta; import mx.edu.um.academia.model.Respuesta; import org.hibernate.Session; import org.hibernate.SessionFactory; import static org.junit.Assert.*; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; /** * * @author J. David Mendoza <jdmendoza@um.edu.mx> */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:context/academia.xml"}) @Transactional public class ExamenDaoTest { private static final Logger log = LoggerFactory.getLogger(ExamenDaoTest.class); @Autowired private ExamenDao examenDao; @Autowired private PreguntaDao preguntaDao; @Autowired private RespuestaDao respuestaDao; @Autowired private SessionFactory sessionFactory; public Session currentSession() { return sessionFactory.getCurrentSession(); } @Test public void debieraCrearExamen() { log.debug("Debiera crear examen"); log.debug("Creando respuestas"); List<Respuesta> respuestas = creaRespuestas(); log.debug("Creando preguntas"); List<Pregunta> preguntas = creaPreguntas(); log.debug("Asigna respuestas a preguntas"); for (int i = 0; i < 10; i++) { asignaRespuestas(respuestas, preguntas, i); Pregunta pregunta = preguntas.get(i); currentSession().refresh(pregunta); if (i < 7) { assertFalse(pregunta.getEsMultiple()); assertEquals(1, pregunta.getCorrectas().size()); assertEquals(3, pregunta.getIncorrectas().size()); } else { assertTrue(pregunta.getEsMultiple()); assertEquals(2, pregunta.getCorrectas().size()); assertEquals(2, pregunta.getIncorrectas().size()); } } log.debug("Crea examen"); Examen examen = new Examen("EXAMEN--1", 1l); examen = examenDao.crea(examen, null); assertNotNull(examen.getId()); log.debug("Asigna preguntas a examen"); boolean bandera = true; for(Pregunta pregunta : preguntas) { if (pregunta.getEsMultiple() && bandera) { asignaPreguntas(examen, pregunta, 1, true); bandera = false; } else { asignaPreguntas(examen, pregunta, 1, false); } } currentSession().refresh(examen); assertEquals(10, examen.getPreguntas().size()); for(ExamenPregunta examenPregunta : examen.getPreguntas()) { log.debug("{} | {}", examenPregunta.getId().getExamen(), examenPregunta.getId().getPregunta()); log.debug("{}", examenPregunta); } log.debug("Elimina una de las preguntas del examen"); List<String> nombres = examenDao.quitaPregunta(examen.getId(), preguntas.get(9).getId()); assertNotNull(nombres); assertEquals(2, nombres.size()); assertEquals("EXAMEN--1", nombres.get(0)); assertEquals("PREGUNTA-9", nombres.get(1)); currentSession().refresh(examen); assertEquals(9, examen.getPreguntas().size()); for(ExamenPregunta examenPregunta : examen.getPreguntas()) { log.debug("{}", examenPregunta); } } private void asignaPreguntas(Examen examen, Pregunta pregunta, Integer puntos, Boolean porPregunta) { log.debug("Asignando {} a {}", pregunta, examen); ExamenPregunta examenPregunta = examenDao.asignaPregunta(examen.getId(), pregunta.getId(), puntos, porPregunta, 1l, null); assertNotNull(examenPregunta); } private void asignaRespuestas(List<Respuesta> respuestas, List<Pregunta> preguntas, int pos) { log.debug("Asignando respuestas de pregunta {}", pos); if (pos < 7) { Long[] correctas = new Long[]{respuestas.get(pos).getId()}; Long[] incorrectas = new Long[]{ respuestas.get(pos + 1).getId(), respuestas.get(pos + 2).getId(), respuestas.get(pos + 3).getId() }; preguntaDao.asignaRespuestas(preguntas.get(pos).getId(), correctas, incorrectas); } else { Pregunta pregunta = preguntas.get(pos); pregunta.setEsMultiple(true); preguntaDao.actualiza(pregunta, null); Long[] correctas = new Long[]{ respuestas.get(pos).getId(), respuestas.get(pos - 1).getId() }; Long[] incorrectas = new Long[]{ respuestas.get(pos - 2).getId(), respuestas.get(pos - 3).getId() }; preguntaDao.asignaRespuestas(preguntas.get(pos).getId(), correctas, incorrectas); } } private List<Respuesta> creaRespuestas() { List<Respuesta> respuestas = new ArrayList<>(); Respuesta respuesta0 = new Respuesta("RESPUESTA-0", 1l); respuesta0 = respuestaDao.crea(respuesta0, null); assertNotNull(respuesta0.getId()); respuestas.add(respuesta0); Respuesta respuesta1 = new Respuesta("RESPUESTA-1", 1l); respuesta1 = respuestaDao.crea(respuesta1, null); assertNotNull(respuesta1.getId()); respuestas.add(respuesta1); Respuesta respuesta2 = new Respuesta("RESPUESTA-2", 1l); respuestaDao.crea(respuesta2, null); assertNotNull(respuesta2.getId()); respuestas.add(respuesta2); Respuesta respuesta3 = new Respuesta("RESPUESTA-3", 1l); respuestaDao.crea(respuesta3, null); assertNotNull(respuesta3.getId()); respuestas.add(respuesta3); Respuesta respuesta4 = new Respuesta("RESPUESTA-4", 1l); respuestaDao.crea(respuesta4, null); assertNotNull(respuesta4.getId()); respuestas.add(respuesta4); Respuesta respuesta5 = new Respuesta("RESPUESTA-5", 1l); respuestaDao.crea(respuesta5, null); assertNotNull(respuesta5.getId()); respuestas.add(respuesta5); Respuesta respuesta6 = new Respuesta("RESPUESTA-6", 1l); respuestaDao.crea(respuesta6, null); assertNotNull(respuesta6.getId()); respuestas.add(respuesta6); Respuesta respuesta7 = new Respuesta("RESPUESTA-7", 1l); respuestaDao.crea(respuesta7, null); assertNotNull(respuesta7.getId()); respuestas.add(respuesta7); Respuesta respuesta8 = new Respuesta("RESPUESTA-8", 1l); respuestaDao.crea(respuesta8, null); assertNotNull(respuesta8.getId()); respuestas.add(respuesta8); Respuesta respuesta9 = new Respuesta("RESPUESTA-9", 1l); respuestaDao.crea(respuesta9, null); assertNotNull(respuesta9.getId()); respuestas.add(respuesta9); return respuestas; } public List<Pregunta> creaPreguntas() { log.debug("Creando Preguntas"); List<Pregunta> preguntas = new ArrayList<>(); Pregunta pregunta0 = new Pregunta("PREGUNTA-0", 1l); pregunta0 = preguntaDao.crea(pregunta0, null); assertNotNull(pregunta0.getId()); preguntas.add(pregunta0); Pregunta pregunta1 = new Pregunta("PREGUNTA-1", 1l); pregunta1 = preguntaDao.crea(pregunta1, null); assertNotNull(pregunta1.getId()); preguntas.add(pregunta1); Pregunta pregunta2 = new Pregunta("PREGUNTA-2", 1l); preguntaDao.crea(pregunta2, null); assertNotNull(pregunta2.getId()); preguntas.add(pregunta2); Pregunta pregunta3 = new Pregunta("PREGUNTA-3", 1l); preguntaDao.crea(pregunta3, null); assertNotNull(pregunta3.getId()); preguntas.add(pregunta3); Pregunta pregunta4 = new Pregunta("PREGUNTA-4", 1l); preguntaDao.crea(pregunta4, null); assertNotNull(pregunta4.getId()); preguntas.add(pregunta4); Pregunta pregunta5 = new Pregunta("PREGUNTA-5", 1l); preguntaDao.crea(pregunta5, null); assertNotNull(pregunta5.getId()); preguntas.add(pregunta5); Pregunta pregunta6 = new Pregunta("PREGUNTA-6", 1l); preguntaDao.crea(pregunta6, null); assertNotNull(pregunta6.getId()); preguntas.add(pregunta6); Pregunta pregunta7 = new Pregunta("PREGUNTA-7", 1l); preguntaDao.crea(pregunta7, null); assertNotNull(pregunta7.getId()); preguntas.add(pregunta7); Pregunta pregunta8 = new Pregunta("PREGUNTA-8", 1l); preguntaDao.crea(pregunta8, null); assertNotNull(pregunta8.getId()); preguntas.add(pregunta8); Pregunta pregunta9 = new Pregunta("PREGUNTA-9", 1l); preguntaDao.crea(pregunta9, null); assertNotNull(pregunta9.getId()); preguntas.add(pregunta9); return preguntas; } }
package EXAMS.E04.viceCity.repositories.interfaces; import EXAMS.E04.viceCity.models.guns.Gun; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; public class GunRepository implements Repository<Gun> { private List<Gun> models; public GunRepository() { this.models = new ArrayList<>(); } @Override public Collection<Gun> getModels() { return Collections.unmodifiableList(this.models); } @Override public void add(Gun model) { if (this.find(model.getName()) == null) { this.models.add(model); } } @Override public boolean remove(Gun model) { return this.models.remove(model); } @Override public Gun find(String name) { return this.models.stream() .filter(g -> g.getName().equals(name)) .findAny().orElse(null); } }
package com.example.model; import com.example.entity.Question; import lombok.Builder; import lombok.Data; @Data @Builder public class QuestionDto { private String question; private Integer questionNumber; private OptionDto options; public static QuestionDto getQuestionDto(Question question) { return QuestionDto.builder() .question(question.getQuestion()) .questionNumber(question.getQuestionNumber()) .options(OptionDto.getOptionDto(question.getOptions())) .build(); } }
package atua.anddev.testtask1.dao; import atua.anddev.testtask1.entity.Company; import java.util.List; public interface CompanyDAO { void addCompany(Company company); Company getCompanyById(int id); List<Company> getAllCompanies(); List<Company> getChildrenCompanies(int companyId); List<Company> getRootCompanies(); void updateCompany(Company company); void deleteCompany(Company company); }
package com.cs.administration; import com.cs.administration.security.LoginAttemptsRecordingAuthenticationProvider; import com.cs.administration.security.UserLogonService; import com.cs.rest.RestConfig; import com.cs.user.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.WebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.header.writers.StaticHeadersWriter; import static org.springframework.http.HttpMethod.GET; /** * @author Joakim Gottzén */ @Configuration @EnableWebMvcSecurity public class BackOfficeWebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_URL = "/api/users/login"; private static final String LOGIN_SUCCESSFUL_URL = "/api/users/login/success"; private static final String LOGIN_FAILURE_URL = "/api/users/login/failure"; private static final String LOGOUT_URL = "/api/users/logout"; private static final String LOGOUT_SUCCESSFUL_URL = "/api/users/logout/success"; private static final String INVALID_SESSION_URL = "/api/users/session/invalid"; private static final String SESSION_EXPIRED_URL = "/api/users/session/expired"; @Autowired private UserLogonService userLogonService; @Autowired private UserService userService; @Autowired private PasswordEncoder passwordEncoder; // @Autowired // private CsrfTokenRepository csrfTokenRepository; @Override public void configure(final WebSecurity web) throws Exception { web.ignoring().antMatchers("/resources/**"); } @Override protected void configure(final HttpSecurity http) throws Exception { final String[] allowedGetUrls = {LOGIN_URL, LOGIN_FAILURE_URL, LOGOUT_URL, LOGOUT_SUCCESSFUL_URL, INVALID_SESSION_URL, SESSION_EXPIRED_URL}; //@formatter:off http .csrf() .disable() // .csrfTokenRepository(csrfTokenRepository) // .and() .headers() .addHeaderWriter(new StaticHeadersWriter("Access-Control-Allow-Origin", "*")) .and() .authorizeRequests() .antMatchers(GET, allowedGetUrls).permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage(LOGIN_URL) .defaultSuccessUrl(LOGIN_SUCCESSFUL_URL) .failureUrl(LOGIN_FAILURE_URL) .permitAll() .and() .logout() .logoutUrl(LOGOUT_URL) .logoutSuccessUrl(LOGOUT_SUCCESSFUL_URL) .invalidateHttpSession(true) .deleteCookies(RestConfig.JSESSIONID) .permitAll() .and() .sessionManagement() .sessionFixation() .changeSessionId() .invalidSessionUrl(INVALID_SESSION_URL) .maximumSessions(1) .expiredUrl(SESSION_EXPIRED_URL); //@formatter:on } @Override protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); } private LoginAttemptsRecordingAuthenticationProvider authenticationProvider() { final LoginAttemptsRecordingAuthenticationProvider authenticationProvider = new LoginAttemptsRecordingAuthenticationProvider(userService); authenticationProvider.setUserDetailsService(userLogonService); authenticationProvider.setPasswordEncoder(passwordEncoder); return authenticationProvider; } }
package gov.nih.mipav.view.renderer.J3D.volumeview; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.view.*; import gov.nih.mipav.view.renderer.J3D.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.media.j3d.*; import javax.swing.*; /** * Volume Sculpturing allows the user to draw a region on the screen in the volume render view, and to remove the parts * of the volume covered by that region. The user outlines a region by holding the left mouse button down and drawing * directly on the screen. Volume Sculpturing works in both the Raycast and Shearwarp volume render views through the * VolumeSculptor.java implementation and on the VolumeTexture render views through the TextureSculptor.java * implemetation. * * <p>The user draws an outline on the screen, and defines the cut-away or sculpture region. If the user chooses to * apply the sculpture region to the volume, the voxels defined by an extruded volume of the cut-away region are * removed. This is done by projecting the voxels in the volume into screen space and determining which voxels fall * inside the sculpture region. Voxels that are inside the sculpture region are set to the minimum voxel value, which is * rendered as transparent. The user may also undo volume sculpturing, returning the volume data to its original values. * </p> * * <p>Drawing the Sculpt Region on the Screen</p> * * <p>The VolumeSculptor class implements both MouseListener and MouseMotionListener interfaces. Drawing is done through * the mousePressed, mouseReleased, and mouseDragged functions.</p> * * <p>When sculpting is enabled, the viewing transformations (rotation, scale, translation) are disabled, so the left * mouse button can be used for drawing on the screen instead of rotating the volume. Second, the view canvas is * captured and stored. When the left mouse button is pressed, the VolumeSculptor class captures and stores all * subsequent mouse positions, and draws them directly into the canvas image, connecting the mouse positions by drawing * 2D lines on the image. On a mouseReleased event the outline is closed by connecting the first and last recorded mouse * positions and the outline region is filled in. The line drawing and polygon filling functions are implemented as 2D * scan-conversion algorithms and are drawn directly by the VolumeSculptor onto the canvas image. This implementation * allows concave and self-intersecting outlines.</p> * * <p>Multiple outlines may be drawn on the canvas image before applying the sculpt regions to the volume. Because the * sculpt regions are in image space, to apply the sculpt region to the volume, it is simply necessary to project the * volume voxels onto the canvas image. Voxels that project onto blue pixels in the canvas image are removed, and voxels * that project to non-masked pixels are unaltered.</p> * * <p>Removing Sculpted Voxels</p> * * <p>The process of applying the sculpt region to the volume data and removing the voxels that fall inside the sculpt * region is broken down into three steps. First, the ModelImage data is retrieved and the center and spacing of the * data is determined. Second, the viewing transformations are calculated. Third, the voxels are mapped into screen * space and the location of the voxel is compared to the corresponding pixel. If the voxel maps to a pixel inside the * sculpt region its value is set to the minimum voxel value.</p> * * @author Alexandra Bokinsky, Ph.D. Under contract from Magic Software. * @see ViewJFrameVolumeView * @see RayCastVolumeRenderer * @see ShearWarpVolumeRenderer */ public abstract class Sculptor implements MouseMotionListener, MouseListener { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** DOCUMENT ME! */ public static int LINES = 0; /** DOCUMENT ME! */ public static int RECTANGLE = 1; //~ Instance fields ------------------------------------------------------------------------------------------------ /** DOCUMENT ME! */ protected double dAMinAlpha = Float.MAX_VALUE; /** DOCUMENT ME! */ protected double dAMinBlue = Float.MAX_VALUE; /** DOCUMENT ME! */ protected double dAMinGreen = Float.MAX_VALUE; /** DOCUMENT ME! */ protected double dAMinRed = Float.MAX_VALUE; /** DOCUMENT ME! */ protected double dBMinAlpha = Float.MAX_VALUE; /** DOCUMENT ME! */ protected double dBMinBlue = Float.MAX_VALUE; /** DOCUMENT ME! */ protected double dBMinGreen = Float.MAX_VALUE; /** DOCUMENT ME! */ protected double dBMinRed = Float.MAX_VALUE; /** DOCUMENT ME! */ protected float fImageBMin = Float.MAX_VALUE; /** Min and Max image intensity and color values:. */ protected float fImageMin = Float.MAX_VALUE; /** Backup of the data for undo:. */ protected int[] m_aiImageA_backup; /** DOCUMENT ME! */ protected int[] m_aiImageB_backup; /** Mouse positions in x,y for drawing the sculpt region:. */ protected int[] m_aiXPoints; /** DOCUMENT ME! */ protected int[] m_aiYPoints; /** m_bMousePressed is set to true when the mousePressed callback is activated and the left mouse button is down. */ protected boolean m_bMousePressed; /** DOCUMENT ME! */ protected boolean m_bSculptDrawn = false; /** m_bSculptEnabled is turned on when the user presses the "Draw Sculpt Outline" button. */ protected boolean m_bSculptEnabled = false; /** The sculpt region color. */ protected int m_iColorSculpt = 0xff0000ff; /** DOCUMENT ME! */ protected int m_iFirstX; /** DOCUMENT ME! */ protected int m_iFirstY; /** DOCUMENT ME! */ protected int m_iLastX; /** DOCUMENT ME! */ protected int m_iLastY; /** DOCUMENT ME! */ protected int m_iNumberPoints; /** DOCUMENT ME! */ protected int m_iOriginalHeight; /** The original canvas size. This is used if the ViewJFrameVolumeView window is resized by the user. */ protected int m_iOriginalWidth; /** Previous and first mouse positions:. */ protected int m_iPreviousX; /** DOCUMENT ME! */ protected int m_iPreviousY; /** DOCUMENT ME! */ protected int m_iSculptImageHeight; /** Size of the m_kSculptImage, when it is captured. */ protected int m_iSculptImageWidth; /** DOCUMENT ME! */ protected int m_iXMax; /** The min and max x,y mouse values:. */ protected int m_iXMin; /** DOCUMENT ME! */ protected int m_iYMax; /** DOCUMENT ME! */ protected int m_iYMin; /** Canvas3D reference for drawing :. */ protected Canvas3D m_kCanvas3D; /** Green Progress bar at the top right hand corner of the ViewJFrameVolumeView window. */ protected JProgressBar m_kProgress; /** DOCUMENT ME! */ protected BufferedImage m_kSavedImage; /** * m_kSculptImage is a screen shot of the canvas image. The sculpt region is drawn directly into m_kSculptImage. The * outline is filled by alpha-blending the Sculpt region color with the m_kSculptImage backgound image. * m_kSculptImageOpaque is filled with solid color, but not displayed, it is used to test whether voxels are inside * the sculpt region. */ protected BufferedImage m_kSculptImage; /** DOCUMENT ME! */ protected BufferedImage m_kSculptImageOpaque; /** Shape of the drawing rectangle. */ private int drawShape = LINES; //~ Methods -------------------------------------------------------------------------------------------------------- /** * applySculpt: abstract function, implementation depends on whether the instance is VolumeTextureSculptor or * VolumeSculptor. * * @return DOCUMENT ME! */ public abstract boolean applySculpt(); /** * undoSculpt: abstract function, implementation depends on whether the instance is VolumeTextureSculptor or * VolumeSculptor. */ public abstract void undoSculpt(); /** * DOCUMENT ME! */ public abstract void update(); /** * clearSculpt: called by ViewJFrameVolumeView when the user presses the "Clear Ouline" button, clearing the sculpt * outline from the canvas image. The function disables sculpting and reactivates the mouse events for the * m_kVolumeRenderer. */ public void clearSculpt() { m_bSculptEnabled = false; m_bSculptDrawn = false; m_iNumberPoints = 0; } /** * Sets all variables to null, disposes, and garbage collects. * * @param flag DOCUMENT ME! */ public void disposeLocal(boolean flag) { if (m_kSculptImage != null) { m_kSculptImage.flush(); m_kSculptImage = null; } if (m_kSculptImageOpaque != null) { m_kSculptImageOpaque.flush(); m_kSculptImageOpaque = null; } if (m_kSavedImage != null) { m_kSavedImage.flush(); m_kSavedImage = null; } m_aiImageA_backup = null; m_aiImageB_backup = null; m_aiXPoints = null; m_aiYPoints = null; } /** * enableSculpt: called by the ViewJFrameVolumeView object when the Draw Sculpt button is pressed. This function * deactivates the m_kVolumeRenderer's mouse response, so the mouse can be used to draw the sculpt outline. It also * allocates and initializes the m_iSculptImage buffer for drawing. * * @param bEnabled DOCUMENT ME! */ public void enableSculpt(boolean bEnabled) { m_bSculptEnabled = bEnabled; if (m_bSculptEnabled == false) { return; } m_iNumberPoints = 0; /* Get the current size of the canvas */ m_iSculptImageWidth = m_kCanvas3D.getWidth(); m_iSculptImageHeight = m_kCanvas3D.getHeight(); if ((m_iSculptImageWidth <= 0) || (m_iSculptImageHeight <= 0)) { return; // Dual Panel mode, both are enabled, but only one panel // is visible } /* Allocate the m_kSculptImage, and m_kSculptImageOpaque and read the * canvas image into the buffers. */ m_kSculptImage = null; m_kSculptImage = new BufferedImage(m_iSculptImageWidth, m_iSculptImageHeight, BufferedImage.TYPE_INT_ARGB); m_kSculptImageOpaque = null; m_kSculptImageOpaque = new BufferedImage(m_iSculptImageWidth, m_iSculptImageHeight, BufferedImage.TYPE_INT_ARGB); m_kSavedImage = null; m_kSavedImage = new BufferedImage(m_iSculptImageWidth, m_iSculptImageHeight, BufferedImage.TYPE_INT_ARGB); getFrameBuffer(); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public boolean getEnable() { return m_bSculptEnabled; } /** * Initialize the Mouse events, store the progress bar, and get the original canvas widths. Disable sculpting and * drawing with the mouse. Note - this function should be called once per instance only, as it sets up the * MouseMotionListener and MouseListener. * * @param iSculptWidth DOCUMENT ME! * @param iSculptHeight DOCUMENT ME! */ public void initVolumeSculptor(int iSculptWidth, int iSculptHeight) { m_kCanvas3D.addMouseMotionListener(this); m_kCanvas3D.addMouseListener(this); m_kProgress = ViewJFrameVolumeView.getRendererProgressBar(); m_iOriginalWidth = iSculptWidth; m_iOriginalHeight = iSculptHeight; m_bSculptEnabled = false; m_bMousePressed = false; } /** * invertSculpt: called by ViewJFrameVolumeView when the user presses the "Invert Sculpt Region" button, inverting * the sculpt region. */ public void invertSculpt() { if (m_bSculptDrawn == false) { return; } int iImageColor = 0; int iNewColor = 0; /* Loop over the pixels in the sculpt buffer: */ for (int iX = 0; iX < m_iSculptImageWidth; iX++) { for (int iY = 0; iY < m_iSculptImageHeight; iY++) { /* If the pixel is inside the sculpt region, then change it to * the saved image color: */ if (m_kSculptImageOpaque.getRGB(iX, iY) == m_iColorSculpt) { iImageColor = m_kSavedImage.getRGB(iX, iY); m_kSculptImageOpaque.setRGB(iX, iY, iImageColor); m_kSculptImage.setRGB(iX, iY, iImageColor); } else { /* If the pixel is outside the sculpt, use the original * saved image to blend in the sculpt color for the SculptImage, and use the m_iColorSculpt for the * Opaque * image: */ iImageColor = m_kSavedImage.getRGB(iX, iY); iNewColor = blendColor(iImageColor, m_iColorSculpt); m_kSculptImage.setRGB(iX, iY, iNewColor); m_kSculptImageOpaque.setRGB(iX, iY, m_iColorSculpt); } } } /* Draw update image: */ int iCanvasHeight = m_kCanvas3D.getHeight(); int iCanvasWidth = m_kCanvas3D.getWidth(); Graphics kGraphics = m_kCanvas3D.getGraphics(); kGraphics.drawImage(m_kSculptImage, 0, 0, m_iSculptImageWidth, m_iSculptImageHeight, 0, 0, iCanvasWidth, iCanvasHeight, new Color(0, 0, 0, 0), m_kCanvas3D); } /** * One of the overrides necessary to be a MouseListener. This function is invoked when a button has been pressed and * released. * * @param kEvent the mouse event generated by a mouse clicked */ public void mouseClicked(MouseEvent kEvent) { /* stub */ } /** * Invoked when the mouse is dragged while a button is held down. If this occurs while sculpting is enabled, then * the mouse positions are stored and the sculpt outline is drawn on the canvas, using the previously recorded mouse * position and the current mouse position as the start and end points of a 2D line on the canvas. * * @param kEvent the mouse event generated by a mouse drag */ public void mouseDragged(MouseEvent kEvent) { if (m_bSculptEnabled && m_bMousePressed) { int iX = kEvent.getX(); int iY = kEvent.getY(); if ((iX >= 0) && (iX < m_iSculptImageWidth) && (iY >= 0) && (iY < m_iSculptImageHeight)) { if (drawShape == LINES) { /* If the mouse position isn't the same as the last mouse * position, then add it to the point list, draw a line from * the last point to this point, and update min,max. */ if ((iX != m_iPreviousX) || (iY != m_iPreviousY)) { m_aiXPoints[m_iNumberPoints] = iX; m_aiYPoints[m_iNumberPoints] = iY; m_iNumberPoints++; line(iX, iY, m_iPreviousX, m_iPreviousY); } m_iPreviousX = iX; m_iPreviousY = iY; if (iX < m_iXMin) { m_iXMin = iX; } if (iX > m_iXMax) { m_iXMax = iX; } if (iY < m_iYMin) { m_iYMin = iY; } if (iY > m_iYMax) { m_iYMax = iY; } } /* Draw update image: */ int iCanvasHeight = m_kCanvas3D.getHeight(); int iCanvasWidth = m_kCanvas3D.getWidth(); Graphics kGraphics = m_kCanvas3D.getGraphics(); kGraphics.drawImage(m_kSculptImage, 0, 0, m_iSculptImageWidth, m_iSculptImageHeight, 0, 0, iCanvasWidth, iCanvasHeight, new Color(0, 0, 0, 0), m_kCanvas3D); if (drawShape == RECTANGLE) { if (m_iFirstX < iX) { m_iXMin = m_iFirstX; } else { m_iXMin = iX; } if (m_iFirstX > iX) { m_iXMax = m_iFirstX; } else { m_iXMax = iX; } if (m_iFirstY < iY) { m_iYMin = m_iFirstY; } else { m_iYMin = iY; } if (m_iFirstY > iY) { m_iYMax = m_iFirstY; } else { m_iYMax = iY; } kGraphics.setColor(Color.cyan); kGraphics.drawLine(m_iXMin, m_iYMax, m_iXMax, m_iYMax); kGraphics.drawLine(m_iXMax, m_iYMax, m_iXMax, m_iYMin); kGraphics.drawLine(m_iXMax, m_iYMin, m_iXMin, m_iYMin); kGraphics.drawLine(m_iXMin, m_iYMin, m_iXMin, m_iYMax); } } } } /** * One of the overrides necessary to be a MouseListener. Invoked when the mouse enters a component. * * @param kEvent the mouse event generated by a mouse entered */ public void mouseEntered(MouseEvent kEvent) { } /** * Invoked when the mouse leaves a component. This function captures the mouseExited event when the button is * pressed and the sculpt outline is being drawn, so that the outline is contained within the bounds of the canvas. * * @param kEvent the mouse event generated by a mouse exit */ public void mouseExited(MouseEvent kEvent) { if (m_bSculptEnabled && m_bMousePressed) { processMouseReleased(m_iPreviousX, m_iPreviousY); m_bMousePressed = false; } } /** * One of the overrides necessary to be a MouseMotionListener. Invoked when the mouse is moved, but no buttons are * pressed. * * @param kEvent the event generated by a mouse movement */ public void mouseMoved(MouseEvent kEvent) { } /** * Invoked when a mouse button is pressed. When the left mouse button is pressed, and sculpting is enabled, then the * user is beginning to outline the sculpt region. This function initializes the outline drawing, and stores the * first point(x,y) so the outline can be closed on mouseReleased. The first and following mouse positions are drawn * in outline form using current and previously (last recorded) positions as the start and end points of a 2D line * on the canvas. * * @param kEvent the mouse event generated by a mouse press */ public void mousePressed(MouseEvent kEvent) { if (m_bSculptEnabled && (kEvent.getButton() == MouseEvent.BUTTON1)) { m_bMousePressed = true; /* Get the x,y position of the mouse: */ int iX = kEvent.getX(); int iY = kEvent.getY(); /* Store first point in the previous point */ m_iPreviousX = iX; m_iPreviousY = iY; /* Store first point */ m_iFirstX = iX; m_iFirstY = iY; /* Initialize the min and max points */ m_iXMin = iX; m_iXMax = iX; m_iYMin = iY; m_iYMax = iY; m_aiXPoints = null; m_aiXPoints = new int[m_iSculptImageWidth * m_iSculptImageHeight]; m_aiYPoints = null; m_aiYPoints = new int[m_iSculptImageWidth * m_iSculptImageHeight]; m_aiXPoints[m_iNumberPoints] = iX; m_aiYPoints[m_iNumberPoints] = iY; m_iNumberPoints++; /* If the point is within the SculptImage bounds, then draw the * point on the canvas */ if ((iX >= 0) && (iX < m_iSculptImageWidth) && (iY >= 0) && (iY < m_iSculptImageHeight)) { m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); /* Draw the modified image: */ int iCanvasHeight = m_kCanvas3D.getHeight(); int iCanvasWidth = m_kCanvas3D.getWidth(); Graphics kGraphics = m_kCanvas3D.getGraphics(); kGraphics.drawImage(m_kSculptImage, 0, 0, m_iSculptImageWidth, m_iSculptImageHeight, 0, 0, iCanvasWidth, iCanvasHeight, new Color(0, 0, 0, 0), m_kCanvas3D); } } } /** * Invoked when a mouse button is released. If this happens while drawing the sculpt outline, the mouse release * indicates that the outline is complete. The function closes the outline by connecting the first and last points, * and then calls processMouseReleased(), which fills the outline. * * @param kEvent the mouse event generated by a mouse release */ public void mouseReleased(MouseEvent kEvent) { if (m_bSculptEnabled && m_bMousePressed && (kEvent.getButton() == MouseEvent.BUTTON1)) { m_bMousePressed = false; /* Get the x,y position of the mouse: */ int iX = kEvent.getX(); int iY = kEvent.getY(); if (drawShape == RECTANGLE) { m_iLastX = iX; m_iLastY = iY; if (m_iFirstX < iX) { m_iXMin = m_iFirstX; } else { m_iXMin = iX; } if (m_iFirstX > iX) { m_iXMax = m_iFirstX; } else { m_iXMax = iX; } if (m_iFirstY < iY) { m_iYMin = m_iFirstY; } else { m_iYMin = iY; } if (m_iFirstY > iY) { m_iYMax = m_iFirstY; } else { m_iYMax = iY; } drawRectangleArea(); } else if (drawShape == LINES) { /* If the mouse position isn't the same as the last mouse * position, then add it to the point list, draw a line from the * last point to this point, and update min,max. */ if ((iX != m_iPreviousX) || (iY != m_iPreviousY)) { m_aiXPoints[m_iNumberPoints] = iX; m_aiYPoints[m_iNumberPoints] = iY; m_iNumberPoints++; line(iX, iY, m_iPreviousX, m_iPreviousY); if (iX < m_iXMin) { m_iXMin = iX; } if (iX > m_iXMax) { m_iXMax = iX; } if (iY < m_iYMin) { m_iYMin = iY; } if (iY > m_iYMax) { m_iYMax = iY; } } } // Fill the sculpt outline: processMouseReleased(iX, iY); } } /** * Set the shape of the drawing sculptor. * * @param shape 0 for LINES, 1 for RECTANGLE */ public void setDrawingShape(int shape) { drawShape = shape; } /** * Called by the TextureSculptor or VolumeSculptor objects. The function stores the original volume data back to the * original values in the m_aiImage_backup data members. * * @param kImageA DOCUMENT ME! * @param kImageB DOCUMENT ME! */ protected void backupImage(ModelImage kImageA, ModelImage kImageB) { /* The size of the ModelImage for indexing: */ int iXBound = kImageA.getExtents()[0]; int iYBound = kImageA.getExtents()[1]; int iZBound = kImageA.getExtents()[2]; int iSliceSize = iXBound * iYBound; int iColor = 1; if (kImageA.isColorImage()) { iColor = 4; } if (m_aiImageA_backup == null) { m_aiImageA_backup = new int[iXBound * iYBound * iZBound * iColor]; if (kImageB != null) { iColor = 1; if (kImageB.isColorImage()) { iColor = 4; } m_aiImageB_backup = new int[iXBound * iYBound * iZBound * iColor]; } } for (int iZ = 0; iZ < iZBound; iZ++) { for (int iY = 0; iY < iYBound; iY++) { for (int iX = 0; iX < iXBound; iX++) { int iIndex = (iZ * iSliceSize) + (iY * iXBound) + iX; /* Store the volume data in the backup */ if (kImageA.isColorImage()) { for (int iC = 0; iC < iColor; iC++) { m_aiImageA_backup[(iIndex * iColor) + iC] = kImageA.getInt((iIndex * iColor) + iC); } } else { m_aiImageA_backup[iIndex] = kImageA.getInt(iIndex); } if (kImageB != null) { if (kImageB.isColorImage()) { for (int iC = 0; iC < iColor; iC++) { m_aiImageB_backup[(iIndex * iColor) + iC] = kImageB.getInt((iIndex * iColor) + iC); } } else { m_aiImageB_backup[iIndex] = kImageB.getInt(iIndex); } } } } } } /** * Called by the TextureSculptor or VolumeSculptor objects. The function stores the original volume data back to the * original values in the m_aiImage_backup data members. * * @param kImageA DOCUMENT ME! * @param kImageB DOCUMENT ME! * @param iIndex DOCUMENT ME! */ protected void backupImage(ModelImage kImageA, ModelImage kImageB, int iIndex) { /* The size of the ModelImage for indexing: */ int iXBound = kImageA.getExtents()[0]; int iYBound = kImageA.getExtents()[1]; int iZBound = kImageA.getExtents()[2]; int iSliceSize = iXBound * iYBound; int iColor = 1; if (kImageA.isColorImage()) { iColor = 4; } if (m_aiImageA_backup == null) { m_aiImageA_backup = new int[iXBound * iYBound * iZBound * iColor]; if (kImageB != null) { iColor = 1; if (kImageB.isColorImage()) { iColor = 4; } m_aiImageB_backup = new int[iXBound * iYBound * iZBound * iColor]; } } /* Store the volume data in the backup */ if (kImageA.isColorImage()) { for (int iC = 0; iC < iColor; iC++) { m_aiImageA_backup[(iIndex * iColor) + iC] = kImageA.getInt((iIndex * iColor) + iC); } } else { m_aiImageA_backup[iIndex] = kImageA.getInt(iIndex); } if (kImageB != null) { if (kImageB.isColorImage()) { for (int iC = 0; iC < iColor; iC++) { m_aiImageB_backup[(iIndex * iColor) + iC] = kImageB.getInt((iIndex * iColor) + iC); } } else { m_aiImageB_backup[iIndex] = kImageB.getInt(iIndex); } } } /** * blendColor: blends two colors in ARGB format from the BufferedImage class, using an alpha value of 0.5. * * @param iImageColor DOCUMENT ME! * @param iBlendColor DOCUMENT ME! * * @return DOCUMENT ME! */ protected int blendColor(int iImageColor, int iBlendColor) { int iImageRed = ((iImageColor >> 16) & 0xFF); int iImageGreen = ((iImageColor >> 8) & 0xFF); int iImageBlue = (iImageColor & 0xFF); iImageRed = iImageRed >> 1; iImageGreen = iImageGreen >> 1; iImageBlue = iImageBlue >> 1; int iBlendRed = ((iBlendColor >> 16) & 0xFF); int iBlendGreen = ((iBlendColor >> 8) & 0xFF); int iBlendBlue = (iBlendColor & 0xFF); iBlendRed = iBlendRed >> 1; iBlendGreen = iBlendGreen >> 1; iBlendBlue = iBlendBlue >> 1; int iRed = (iImageRed + iBlendRed); int iGreen = (iImageGreen + iBlendGreen); int iBlue = (iImageBlue + iBlendBlue); int iNewColor = (iRed & 0x00ff0000) | (iGreen & 0x0000ff00) | (iBlue & 0x000000ff); iNewColor = (iNewColor | 0xff000000); return iNewColor; } /** * Called by the TextureSculptor or VolumeSculptor objects. The function calculates the mimumum and maximum * intensity and color values in the images. * * @param kImageA DOCUMENT ME! * @param kImageB DOCUMENT ME! */ protected void calculateMinMaxValues(ModelImage kImageA, ModelImage kImageB) { /* When the volume is sculpted, the removed voxels are set to the * lowest (zero-value) in the volume. This step calculates the minimum * value in the ModelImage volume data:*/ fImageMin = Float.MAX_VALUE; fImageBMin = Float.MAX_VALUE; dAMinAlpha = Float.MAX_VALUE; dAMinRed = Float.MAX_VALUE; dAMinGreen = Float.MAX_VALUE; dAMinBlue = Float.MAX_VALUE; dBMinAlpha = Float.MAX_VALUE; dBMinRed = Float.MAX_VALUE; dBMinGreen = Float.MAX_VALUE; dBMinBlue = Float.MAX_VALUE; /* The size of the ModelImage for indexing: */ int iXBound = kImageA.getExtents()[0]; int iYBound = kImageA.getExtents()[1]; int iZBound = kImageA.getExtents()[2]; int iSliceSize = iXBound * iYBound; int iSize = iZBound * iYBound * iXBound; /* iMod is used for the progress bar */ int iMod = iYBound / 10; for (int iY = 0; iY < iYBound; iY++) { int iIndexY = iY * iXBound; /* Update progress bar: */ if (((iY % iMod) == 0) || (iY == (iYBound - 1))) { if (iY == (iYBound - 1)) { m_kProgress.setValue(100); } else { m_kProgress.setValue(Math.round((float) (iY) / (iYBound - 1) * 100)); m_kProgress.update(m_kProgress.getGraphics()); } } for (int iX = 0; iX < iXBound; iX++) { for (int iZ = 0; iZ < iZBound; iZ++) { int iIndexZ = iZ * iSliceSize; int iIndex = iIndexZ + iIndexY + iX; /* get the min value for ModelImageA */ if (kImageA.isColorImage()) { if (kImageA.getDouble((iIndex * 4) + 0) < dAMinAlpha) { dAMinAlpha = kImageA.getDouble((iIndex * 4) + 0); } if (kImageA.getDouble((iIndex * 4) + 1) < dAMinRed) { dAMinRed = kImageA.getDouble((iIndex * 4) + 1); } if (kImageA.getDouble((iIndex * 4) + 2) < dAMinGreen) { dAMinGreen = kImageA.getDouble((iIndex * 4) + 2); } if (kImageA.getDouble((iIndex * 4) + 3) < dAMinBlue) { dAMinBlue = kImageA.getDouble((iIndex * 4) + 3); } } else if (kImageA.getFloat(iIndex) < fImageMin) { fImageMin = kImageA.getFloat(iIndex); } /* get the min value for ModelImageB */ if (kImageB != null) { if (kImageB.isColorImage()) { if (kImageB.getDouble((iIndex * 4) + 0) < dBMinAlpha) { dBMinAlpha = kImageB.getDouble((iIndex * 4) + 0); } if (kImageB.getDouble((iIndex * 4) + 1) < dBMinRed) { dBMinRed = kImageB.getDouble((iIndex * 4) + 1); } if (kImageB.getDouble((iIndex * 4) + 2) < dBMinGreen) { dBMinGreen = kImageB.getDouble((iIndex * 4) + 2); } if (kImageB.getDouble((iIndex * 4) + 3) < dBMinBlue) { dBMinBlue = kImageB.getDouble((iIndex * 4) + 3); } } else if (kImageB.getFloat(iIndex) < fImageBMin) { fImageBMin = kImageB.getFloat(iIndex); } } } } } } /** * Draw rectangle shape object. */ protected void drawRectangleArea() { // /* if (!(m_iLastX < m_iFirstX)) { line(m_iXMin, m_iYMax, m_iXMax, m_iYMax); m_aiXPoints[m_iNumberPoints] = m_iXMin; m_aiYPoints[m_iNumberPoints] = m_iYMax; m_iNumberPoints++; m_aiXPoints[m_iNumberPoints] = m_iXMax; m_aiYPoints[m_iNumberPoints] = m_iYMax; m_iNumberPoints++; } line(m_iXMax, m_iYMax, m_iXMax, m_iYMin); m_aiXPoints[m_iNumberPoints] = m_iXMax; m_aiYPoints[m_iNumberPoints] = m_iYMax; m_iNumberPoints++; m_aiXPoints[m_iNumberPoints] = m_iXMax; m_aiYPoints[m_iNumberPoints] = m_iYMin; m_iNumberPoints++; line(m_iXMax, m_iYMin, m_iXMin, m_iYMin); m_aiXPoints[m_iNumberPoints] = m_iXMax; m_aiYPoints[m_iNumberPoints] = m_iYMin; m_iNumberPoints++; m_aiXPoints[m_iNumberPoints] = m_iXMin; m_aiYPoints[m_iNumberPoints] = m_iYMin; m_iNumberPoints++; line(m_iXMin, m_iYMin, m_iXMin, m_iYMax); m_aiXPoints[m_iNumberPoints] = m_iXMin; m_aiYPoints[m_iNumberPoints] = m_iYMin; m_iNumberPoints++; m_aiXPoints[m_iNumberPoints] = m_iXMin; m_aiYPoints[m_iNumberPoints] = m_iYMax; m_iNumberPoints++; if ((m_iLastX < m_iFirstX)) { line(m_iXMin, m_iYMax, m_iXMax, m_iYMax); m_aiXPoints[m_iNumberPoints] = m_iXMin; m_aiYPoints[m_iNumberPoints] = m_iYMax; m_iNumberPoints++; m_aiXPoints[m_iNumberPoints] = m_iXMax; m_aiYPoints[m_iNumberPoints] = m_iYMax; m_iNumberPoints++; } } /** * fill: fill the sculpt outline drawn by the user. Pixels are determined to be inside or outside the sculpt region * based on the parameters, aaiCrossingPoints and aiNumCrossings, using a scan-conversion algorithm that traverses * each row and column of the bounding box of the sculpt region coloring inside points as it goes. * * @param aaiCrossingPoints DOCUMENT ME! * @param aiNumCrossings DOCUMENT ME! */ protected void fill(int[][] aaiCrossingPoints, int[] aiNumCrossings) { int iColumn = 0; /* Loop over the width of the sculpt region bounding-box: */ for (int iX = m_iXMin; iX < m_iXMax; iX++) { boolean bInside = false; /* Loop over the height of the sculpt region bounding-box: */ for (int iY = m_iYMin; iY < m_iYMax; iY++) { /* loop over each crossing point for this column: */ for (int iCross = 0; iCross < aiNumCrossings[iColumn]; iCross++) { if (iY == aaiCrossingPoints[iColumn][iCross]) { /* Each time an edge is cross the point alternates * from outside to inside: */ bInside = !bInside; } } if (bInside == true) { /* The current pixel is inside the sculpt region. Get the * image color from the canvas image and alpha-blend the sculpt color ontop, storing the result in * the canvas image. */ int iImageColor = m_kSculptImage.getRGB(iX, iY); int iNewColor = blendColor(iImageColor, m_iColorSculpt); m_kSculptImage.setRGB(iX, iY, iNewColor); /* The un-blended sculpt color is stored in the opaque * image for point-polygon test later when the sculpt region is applied to the volume. */ m_kSculptImageOpaque.setRGB(iX, iY, m_iColorSculpt); m_bSculptDrawn = true; } } iColumn++; } } /** * Calls disposeLocal. * * @throws Throwable DOCUMENT ME! */ protected void finalize() throws Throwable { this.disposeLocal(false); super.finalize(); } /** * Grab the canvas image, and copy into the m_kSculptImage data members. * * @return DOCUMENT ME! */ protected boolean getFrameBuffer() { int[] pixels; int xDim, yDim; Robot robot; Dimension d = new Dimension(); Point p = new Point(); p.x = 0; p.y = 0; SwingUtilities.convertPointToScreen(p, m_kCanvas3D); d.width = m_kCanvas3D.getWidth(); d.height = m_kCanvas3D.getHeight(); Rectangle currentRectangle = new Rectangle(p, d); /* Using Robot to capture image rectangle and transfering image into * the pixel buffer. */ try { robot = new Robot(); Image imagePix = robot.createScreenCapture(currentRectangle); xDim = currentRectangle.width; yDim = currentRectangle.height; xDim = xDim - (xDim % 4); yDim = yDim - (yDim % 4); pixels = new int[xDim * yDim]; PixelGrabber pgTest = new PixelGrabber(imagePix, 0, 0, xDim, yDim, pixels, 0, xDim); pgTest.grabPixels(); imagePix = null; pgTest = null; } catch (InterruptedException e) { Preferences.debug("Interrupted waiting for pixels!"); return false; } catch (OutOfMemoryError error) { MipavUtil.displayError("VolumeSculpt: unable to allocate enough memory for RGB image"); return false; } catch (AWTException error) { MipavUtil.displayError("Platform doesn't support screen capture."); return false; } int sculptBG = 0; for (int y = 0; y < yDim; y++) { for (int x = 0; x < xDim; x++) { sculptBG = 0xffffffff & pixels[(y * xDim) + x]; sculptBG = 0xff000000 | sculptBG; m_kSculptImage.setRGB(x, y, sculptBG); m_kSculptImageOpaque.setRGB(x, y, sculptBG); m_kSavedImage.setRGB(x, y, sculptBG); } } pixels = null; robot = null; return true; } /** * This function draws a 2D line on the canvas image -- ontop of the currently rendered image. To implement the line * drawing I use the midpoint line algorithm, in Foley and van Dam, originally Bresenham's algorithm. The first part * of the function sets up the step sizes for x and y depending on what type of line is being drawn. The second part * loops over the line, drawing pixels into the canvas image. * * @param iX0 DOCUMENT ME! * @param iY0 DOCUMENT ME! * @param iX1 DOCUMENT ME! * @param iY1 DOCUMENT ME! */ protected void line(int iX0, int iY0, int iX1, int iY1) { if ((iX0 == iX1) && (iY0 == iY1)) { return; } /* incremental steps along the x, and y-directions */ int iXStep, iYStep; /* The slope of the line in the y-direction: */ int iSlopeY = (iY1 - iY0); if (iSlopeY >= 0) { /* The slope is positive in the y direction. */ iYStep = 1; } else { /* The slope is negative in the y direction */ iSlopeY = -iSlopeY; iYStep = -1; } /* The slope of the line in the x-direction: */ int iSlopeX = (iX1 - iX0); if (iSlopeX >= 0) { /* The slope is positive in the x direction */ iXStep = 1; } else { /* The slope is negative in the x direction */ iSlopeX = -iSlopeX; iXStep = -1; } /* Iterators iX,iY: initialize to the first x,y position of the * line: */ int iX = iX0; int iY = iY0; /* partial increments for x, and y */ int iD, iIncrE, iIncrNE; /* The line is vertical.*/ if (iSlopeX == 0) { m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); iY = iY + iYStep; while (iY != iY1) { m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); iY = iY + iYStep; } } /* The line is horixontal. */ else if (iSlopeY == 0) { m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); iX = iX + iXStep; while (iX != iX1) { m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); iX = iX + iXStep; } } /* The line has a slope <= -1 or between 1 and 0 */ else if (iSlopeY < iSlopeX) { iD = (2 * iSlopeY) - iSlopeX; iIncrE = iSlopeY * 2; iIncrNE = 2 * (iSlopeY - iSlopeX); /* Draw the line into the frame buffer until the index reaches * the greatest point in the line: */ m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); iX = iX + iXStep; if (iD > 0) { iD = iD + iIncrNE; iY = iY + iYStep; } else { iD = iD + iIncrE; } while ((iX != iX1) || (iY != iY1)) { m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); iX = iX + iXStep; if (iD > 0) { iD = iD + iIncrNE; iY = iY + iYStep; } else { iD = iD + iIncrE; } } } /* The line has a slope >= 1 or between -1 and 0 */ else { iD = (2 * iSlopeX) - iSlopeY; iIncrE = iSlopeX * 2; iIncrNE = 2 * (iSlopeX - iSlopeY); /* Draw the line into the frame buffer until the index reaches * the greatest point in the line */ m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); iY = iY + iYStep; if (iD > 0) { iX = iX + iXStep; iD = iD + iIncrNE; } else { iD = iD + iIncrE; } while ((iX != iX1) || (iY != iY1)) { m_kSculptImage.setRGB(iX, iY, m_iColorSculpt); iY = iY + iYStep; if (iD > 0) { iX = iX + iXStep; iD = iD + iIncrNE; } else { iD = iD + iIncrE; } } } } /** * This function computes the set of spans indicated by column crossings for the sculpt outline drawn by the user, * by doing a polygon scan conversion in gridded space. The outline must be closed with last point = first point. * * @param aaiCrossingPoints DOCUMENT ME! * @param aiNumCrossings DOCUMENT ME! */ protected void outlineRegion(int[][] aaiCrossingPoints, int[] aiNumCrossings) { /* * nudge the vertices off of the exact integer coords by a factor of 0.1 to avoid vertices on pixel centers, * which would create spans of zero length */ double dNudge = 0.1; double[][][] aaadEdgeList = new double[m_iNumberPoints][2][2]; for (int iPoint = 0; iPoint < (m_iNumberPoints - 1); iPoint++) { aaadEdgeList[iPoint][0][0] = m_aiXPoints[iPoint] - dNudge; aaadEdgeList[iPoint][0][1] = m_aiYPoints[iPoint] - dNudge; aaadEdgeList[iPoint][1][0] = m_aiXPoints[iPoint + 1] - dNudge; aaadEdgeList[iPoint][1][1] = m_aiYPoints[iPoint + 1] - dNudge; } /* * Compute the crossing points for this column and produce spans. */ for (int iColumn = m_iXMin; iColumn <= m_iXMax; iColumn++) { int iIndex = iColumn - m_iXMin; /* for each edge, figure out if it crosses this column and add its * crossing point to the list if so. */ aiNumCrossings[iIndex] = 0; for (int iPoint = 0; iPoint < (m_iNumberPoints - 1); iPoint++) { double dX0 = aaadEdgeList[iPoint][0][0]; double dX1 = aaadEdgeList[iPoint][1][0]; double dY0 = aaadEdgeList[iPoint][0][1]; double dY1 = aaadEdgeList[iPoint][1][1]; double dMinX = (dX0 <= dX1) ? dX0 : dX1; double dMaxX = (dX0 > dX1) ? dX0 : dX1; if ((dMinX < iColumn) && (dMaxX > iColumn)) { /* The edge crosses this column, so compute the * intersection. */ double dDX = dX1 - dX0; double dDY = dY1 - dY0; double dM = (dDX == 0) ? 0 : (dDY / dDX); double dB = (dDX == 0) ? 0 : (((dX1 * dY0) - (dY1 * dX0)) / dDX); double dYCross = (dM * iColumn) + dB; double dRound = 0.5; aaiCrossingPoints[iIndex][aiNumCrossings[iIndex]] = (dYCross < 0) ? (int) (dYCross - dRound) : (int) (dYCross + dRound); aiNumCrossings[iIndex]++; } } /* sort the set of crossings for this column: */ sortCrossingPoints(aaiCrossingPoints[iIndex], aiNumCrossings[iIndex]); } aaadEdgeList = null; } /** * Called when the left mouse button is released, indicating that the sculpt outline is complete, or when the * outline is being drawn and the mouse is fragged outside the canvas area. The function closes the outline, using * the first and last recorded mouse positions. It then fills the outline, by blending the fill color with the * background data on the canvas. Filling is done as a 2D polygon scan conversion so that any closed loop, including * concave and self-intersecting loops, can be processed accurately. * * @param iX int, the x position of the mouse recorded when the mouse button was released. * @param iY int, the y position of the mouse recorded when the mouse button was released. */ protected void processMouseReleased(int iX, int iY) { /* Close the sculpt outline by connecting the last point input: iX,iY * to the first recorded point: m_iFirstX,m_iFirstY. */ if (drawShape == LINES) { line(iX, iY, m_iFirstX, m_iFirstY); /* Store the first point redundantly in the point array: */ m_aiXPoints[m_iNumberPoints] = m_iFirstX; m_aiYPoints[m_iNumberPoints] = m_iFirstY; m_iNumberPoints++; } int[][] aaiCrossingPoints = new int[m_iXMax - m_iXMin + 1][]; int[] aiNumCrossings = new int[m_iXMax - m_iXMin + 1]; for (int i = 0; i < (m_iXMax - m_iXMin + 1); i++) { aaiCrossingPoints[i] = new int[m_iNumberPoints]; } outlineRegion(aaiCrossingPoints, aiNumCrossings); fill(aaiCrossingPoints, aiNumCrossings); m_iNumberPoints = 0; /* Draw the modified image: */ int iCanvasHeight = m_kCanvas3D.getHeight(); int iCanvasWidth = m_kCanvas3D.getWidth(); Graphics kGraphics = m_kCanvas3D.getGraphics(); // m_kCanvas3D.addNotify(); for (int m = 0; m < 1 /* 20 */; m++) { kGraphics.drawImage(m_kSculptImage, 0, 0, m_iSculptImageWidth, m_iSculptImageHeight, 0, 0, iCanvasWidth, iCanvasHeight, new Color(0, 0, 0, 0), m_kCanvas3D); } aaiCrossingPoints = null; aiNumCrossings = null; } /** * Called by the TextureSculptor or VolumeSculptor objects. The function sculpts the original volume data by setting * the value at input iIndex to the mimimum values calculated in CalculateMinMaxValues. * * @param kImageA DOCUMENT ME! * @param kImageB DOCUMENT ME! * @param iIndex DOCUMENT ME! */ protected void sculptImage(ModelImage kImageA, ModelImage kImageB, int iIndex) { /* set the voxel value to zero */ if (kImageA.isColorImage()) { kImageA.set((iIndex * 4) + 0, dAMinAlpha); kImageA.set((iIndex * 4) + 1, dAMinRed); kImageA.set((iIndex * 4) + 2, dAMinGreen); kImageA.set((iIndex * 4) + 3, dAMinBlue); } else { kImageA.set(iIndex, fImageMin); } if (kImageB != null) { if (kImageB.isColorImage()) { kImageB.set((iIndex * 4) + 0, dBMinAlpha); kImageB.set((iIndex * 4) + 1, dBMinRed); kImageB.set((iIndex * 4) + 2, dBMinGreen); kImageB.set((iIndex * 4) + 3, dBMinBlue); } else { kImageB.set(iIndex, fImageBMin); } } } /** * Sorts the edge crossing points in place. * * @param aiList DOCUMENT ME! * @param iNumElements DOCUMENT ME! */ protected void sortCrossingPoints(int[] aiList, int iNumElements) { boolean bDidSwap = true; while (bDidSwap) { bDidSwap = false; for (int iPoint = 0; iPoint < (iNumElements - 1); iPoint++) { if (aiList[iPoint] > aiList[iPoint + 1]) { int iTmp = aiList[iPoint]; aiList[iPoint] = aiList[iPoint + 1]; aiList[iPoint + 1] = iTmp; bDidSwap = true; } } } } /** * Called by the TextureSculptor or VolumeSculptor objects. The function resets the volume data back to the original * values, using the data stored in the m_aiImage_backup data members. * * @param kImageA DOCUMENT ME! * @param kImageB DOCUMENT ME! */ protected void undoSculpt(ModelImage kImageA, ModelImage kImageB) { if (m_aiImageA_backup == null) { return; } /* The extents of the ModelImages: */ int iXBound = kImageA.getExtents()[0]; int iYBound = kImageA.getExtents()[1]; int iZBound = kImageA.getExtents()[2]; int iSliceSize = iXBound * iYBound; int iSize = iXBound * iYBound * iZBound; /* Reset the ModelImage to the original values */ int iMod = iYBound / 10; for (int iY = 0; iY < iYBound; iY++) { /* Update progress bar: */ if (((iY % iMod) == 0) || (iY == (iYBound - 1))) { if (iY == (iYBound - 1)) { m_kProgress.setValue(100); } else { m_kProgress.setValue(Math.round((float) (iY) / (iYBound - 1) * 100)); m_kProgress.update(m_kProgress.getGraphics()); } } int iIndexY = iY * iXBound; for (int iX = 0; iX < iXBound; iX++) { for (int iZ = 0; iZ < iZBound; iZ++) { int iIndexZ = iZ * iSliceSize; int iIndex = iIndexZ + iIndexY + iX; if (kImageA.isColorImage()) { for (int iColor = 0; iColor < 4; iColor++) { kImageA.set((iIndex * 4) + iColor, m_aiImageA_backup[(iIndex * 4) + iColor]); } } else { kImageA.set(iIndex, m_aiImageA_backup[iIndex]); } if (kImageB != null) { if (kImageB.isColorImage()) { for (int iColor = 0; iColor < 4; iColor++) { kImageB.set((iIndex * 4) + iColor, m_aiImageB_backup[(iIndex * 4) + iColor]); } } else { kImageB.set(iIndex, m_aiImageB_backup[iIndex]); } } } } } /* Free the backup variables */ m_aiImageA_backup = null; m_aiImageB_backup = null; } }
public class Livro { private static int ID=0; private final int id; private String titulo; private String autor; private int edicao; public Livro(String titulo, String autor, int edicao) { ID++; this.id = ID; this.titulo = titulo; this.autor = autor; this.edicao = edicao; } public int getId() { return id; } public String getTitulo() { return this.titulo; } public String getAutor() { return this.autor; } public int getEdicao() { return this.edicao; } public String toString() { return "Livro " + id + " [titulo= " + titulo + ", autor= " + autor + ", edicao= " + edicao + "]"; } }
package com.zhongyp.transaction; /** * project: demo * author: zhongyp * date: 2018/3/1 * mail: zhongyp001@163.com */ public interface IStockDao { void insertStock(String sname, int amount); void updateStock(String sname, int amount, boolean isBuy); }
package slimeknights.tconstruct.plugin.jei; import net.minecraft.inventory.Slot; import java.util.ArrayList; import java.util.List; import javax.annotation.Nonnull; import mezz.jei.api.recipe.VanillaRecipeCategoryUid; import mezz.jei.api.recipe.transfer.IRecipeTransferInfo; import slimeknights.tconstruct.tools.common.inventory.ContainerCraftingStation; /** * @author shadowfacts */ public class CraftingStationRecipeTransferInfo implements IRecipeTransferInfo<ContainerCraftingStation> { @Nonnull @Override public Class<ContainerCraftingStation> getContainerClass() { return ContainerCraftingStation.class; } @Nonnull @Override public String getRecipeCategoryUid() { return VanillaRecipeCategoryUid.CRAFTING; } @Override public boolean canHandle(ContainerCraftingStation container) { return true; } @Nonnull @Override public List<Slot> getRecipeSlots(ContainerCraftingStation container) { List<Slot> slots = new ArrayList<>(); for(int i = 1; i < 10; i++) { slots.add(container.getSlot(i)); } return slots; } @Nonnull @Override public List<Slot> getInventorySlots(ContainerCraftingStation container) { List<Slot> slots = new ArrayList<>(); // skip the actual slots of the crafting table for(int i = 10; i < container.inventorySlots.size(); i++) { slots.add(container.getSlot(i)); } return slots; } }
package com.thepoofy.website_searcher.models; /** * Pojo representing a line in the urls.txt file * * @author wvanderhoef */ public class MozData implements Comparable<MozData>{ private int rank; private String url; private int linkingRootDomains; private int externalLinks; private float mozRank; private float mozTrust; public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public int getLinkingRootDomains() { return linkingRootDomains; } public void setLinkingRootDomains(int linkingRootDomains) { this.linkingRootDomains = linkingRootDomains; } public int getExternalLinks() { return externalLinks; } public void setExternalLinks(int externalLinks) { this.externalLinks = externalLinks; } public float getMozRank() { return mozRank; } public void setMozRank(float mozRank) { this.mozRank = mozRank; } public float getMozTrust() { return mozTrust; } public void setMozTrust(float mozTrust) { this.mozTrust = mozTrust; } @Override public int compareTo(MozData arg0) { return this.getRank() - arg0.getRank(); } }
package com.zheng.jvm.parent; /** * <pre> * * File: * * Copyright (c) 2016, globalegrow.com All Rights Reserved. * * Description: * * Revision History * Date, Who, What; * 2019年03月15日 zhenglian Initial. * * </pre> */ public class HelloLoader { // 在拷贝该类到其它目录并制定 public void print() { System.out.println("i'm app loader"); } }
package experiment2; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.WindowConstants; public class Login extends JFrame { private static final long serialVersionUID = 1L; FileReader fileReader; String subname = null; String subpwd=null; JTextField name; JPasswordField password; public Login(){ setVisible(true); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); setTitle("登录界面"); setBounds(300, 200, 300, 150); Container cp=getContentPane(); cp.setLayout(new FlowLayout()); JLabel jl=new JLabel("用户名:"); jl.setBounds(10, 10, 200, 18); name=new JTextField(10); name.setBounds(80, 10, 150, 18); JLabel jl2=new JLabel("密码:"); jl2.setBounds(10, 50, 200, 18); password=new JPasswordField(10); password.setBounds(80, 50, 150, 18); cp.add(jl); cp.add(name); cp.add(jl2); cp.add(password); JButton jb=new JButton("确定"); JRadioButton stu=new JRadioButton("学生"); cp.add(stu); stu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(e.getSource()==stu) { jb.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { readFile1(); } }); } } }); JRadioButton adm=new JRadioButton("管理员"); cp.add(adm); adm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(e.getSource()==adm) { jb.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { readFile2(); } }); } } }); ButtonGroup bg=new ButtonGroup(); bg.add(stu); bg.add(adm); jb.setBounds(80, 80, 60, 18); cp.add(jb); final JButton button = new JButton(); button.setText("重置"); button.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent arg0) { // TODO 自动生成方法存根 name.setText(""); password.setText(""); } }); button.setBounds(150, 80, 60, 18); getContentPane().add(button); } public void readFile1() { try { fileReader = new FileReader("info.txt"); int read = fileReader.read(); subname=name.getText(); subpwd=password.getText(); while(read!=-1){ System.out.print((char)read); read = fileReader.read(); } if(fileReader.toString().contains(subname)&&fileReader.toString().contains(subpwd)){ Model model=new Model(); } else { JOptionPane.showMessageDialog(null, "用户名或密码错误"); } }catch (IOException e) { // TODO Auto-generated catch block System.out.println(e); } } public void readFile2() { try { fileReader = new FileReader("info.txt"); int read = fileReader.read(); subname=name.getText(); subpwd=password.getText(); while(read!=-1){ System.out.print((char)read); read = fileReader.read(); } if(fileReader.toString().contains(subname)&&fileReader.toString().contains(subpwd)){ Information info=new Information(); } else { JOptionPane.showMessageDialog(null, "用户名或密码错误"); } }catch (IOException e) { // TODO Auto-generated catch block System.out.println(e); } } public static void main(String[] args) { Login login = new Login(); login.setSize(150, 200); login.setVisible(true); } }
package pers.lyr.demo.common.dto; /** * @Author lyr * @create 2020/7/14 0:53 */ public class Result<T> { private Boolean flag;//是否成功 private Integer code;//返回码 private String message;//返回消息 private T data;//返回数据 public static<T> Result<T> from(String msg,Integer code,Boolean flag,T data) { return from(msg,code,data).setFlag(flag); } public static <Object> Result<Object> from(String msg,Integer code) { return new Result<Object>().setMessage(msg).setCode(code); } public static<T> Result<T> from(String msg,Integer code,T data) { return Result.<T>from(msg,code) .setData(data); } public Boolean getFlag() { return flag; } public Result<T> setFlag(Boolean flag) { this.flag = flag; return this; } public Integer getCode() { return code; } public Result<T> setCode(Integer code) { this.code = code; return this; } public String getMessage() { return message; } public Result<T> setMessage(String message) { this.message = message; return this; } public T getData() { return data; } public Result<T> setData(T data) { this.data = data; return this; } }
package org.drools.core.beliefsystem.jtms; import org.drools.core.beliefsystem.BeliefSet; import org.drools.core.beliefsystem.BeliefSystem; import org.drools.core.beliefsystem.jtms.JTMSBeliefSetImpl.MODE; import org.drools.core.beliefsystem.simple.SimpleLogicalDependency; import org.drools.core.common.InternalFactHandle; import org.drools.core.common.LogicalDependency; import org.drools.core.common.NamedEntryPoint; import org.drools.core.common.ObjectTypeConfigurationRegistry; import org.drools.core.common.TruthMaintenanceSystem; import org.drools.core.reteoo.ObjectTypeConf; import org.drools.core.spi.Activation; import org.drools.core.spi.PropagationContext; import static org.drools.core.reteoo.PropertySpecificUtil.allSetButTraitBitMask; public class JTMSBeliefSystem<M extends JTMSMode<M>> implements BeliefSystem<M> { public static boolean STRICT = false; private TruthMaintenanceSystem tms; protected NamedEntryPoint defEP; protected NamedEntryPoint negEP; public JTMSBeliefSystem(NamedEntryPoint ep, TruthMaintenanceSystem tms) { this.defEP = ep; this.tms = tms; initMainEntryPoints(); } private void initMainEntryPoints() { negEP = (NamedEntryPoint) defEP.getWorkingMemoryEntryPoint(MODE.NEGATIVE.getId()); } public TruthMaintenanceSystem getTruthMaintenanceSystem() { return this.tms; } public void insert(LogicalDependency<M> node, BeliefSet<M> beliefSet, PropagationContext context, ObjectTypeConf typeConf) { JTMSBeliefSet jtmsBeliefSet = (JTMSBeliefSet) beliefSet; boolean wasEmpty = jtmsBeliefSet.isEmpty(); boolean wasNegated = jtmsBeliefSet.isNegated(); boolean wasUndecided = jtmsBeliefSet.isUndecided(); jtmsBeliefSet.add( node.getMode() ); if ( wasEmpty ) { // Insert Belief if ( ! jtmsBeliefSet.isUndecided() ) { insertBelief( node, typeConf, jtmsBeliefSet, context, wasEmpty, wasNegated, wasUndecided ); } else { defEP.getObjectStore().removeHandle( jtmsBeliefSet.getFactHandle() ); } } else if ( !wasUndecided && jtmsBeliefSet.isUndecided() ) { // Handle Conflict if ( STRICT ) { throw new IllegalStateException( "FATAL : A fact and its negation have been asserted " + jtmsBeliefSet.getFactHandle().getObject() ); } deleteAfterChangedEntryPoint(node, context, typeConf, jtmsBeliefSet, wasNegated); } else { if ( wasUndecided && ! jtmsBeliefSet.isUndecided() ) { insertBelief( node, typeConf, jtmsBeliefSet, context, wasEmpty, wasNegated, wasUndecided ); } } } private void deleteAfterChangedEntryPoint(LogicalDependency<M> node, PropagationContext context, ObjectTypeConf typeConf, JTMSBeliefSet<M> jtmsBeliefSet, boolean wasNegated) { InternalFactHandle fh; if ( wasNegated ) { fh = jtmsBeliefSet.getNegativeFactHandle(); jtmsBeliefSet.setNegativeFactHandle( null ); ((NamedEntryPoint) fh.getEntryPoint()).delete( fh, context.getRuleOrigin(), node.getJustifier() ); } else { fh = jtmsBeliefSet.getPositiveFactHandle(); jtmsBeliefSet.setPositiveFactHandle( null ); NamedEntryPoint nep = (NamedEntryPoint) fh.getEntryPoint() ; nep.getEntryPointNode().retractObject( fh, context, typeConf, nep.getInternalWorkingMemory() ); } } protected void insertBelief(LogicalDependency<M> node, ObjectTypeConf typeConf, JTMSBeliefSet<M> jtmsBeliefSet, PropagationContext context, boolean wasEmpty, boolean wasNegated, boolean isUndecided) { if ( jtmsBeliefSet.isNegated() && ! jtmsBeliefSet.isUndecided() ) { jtmsBeliefSet.setNegativeFactHandle( (InternalFactHandle) negEP.insert( node.getObject() ) ); // As the neg partition is always stated, it'll have no equality key. // However the equality key is needed to stop duplicate LogicalCallbacks, so we manually set it // @FIXME **MDP could this be a problem during derialization, where the jtmsBeliefSet.getNegativeFactHandle().setEqualityKey( jtmsBeliefSet.getFactHandle().getEqualityKey() ); jtmsBeliefSet.setPositiveFactHandle( null ); if ( !(wasNegated || isUndecided) ) { defEP.getObjectStore().removeHandle( jtmsBeliefSet.getFactHandle() ); // Make sure the FH is no longer visible in the default ObjectStore } } else if ( jtmsBeliefSet.isPositive() && ! jtmsBeliefSet.isUndecided() ) { jtmsBeliefSet.setPositiveFactHandle( jtmsBeliefSet.getFactHandle() ); // Use the BeliefSet FH for positive facts jtmsBeliefSet.setNegativeFactHandle( null ); if ( !wasEmpty && (wasNegated || isUndecided ) ) { jtmsBeliefSet.getFactHandle().setObject( node.getObject() ); // Set the Object, as it may have been a negative initialization, before conflict defEP.getObjectStore().addHandle( jtmsBeliefSet.getPositiveFactHandle(), jtmsBeliefSet.getPositiveFactHandle().getObject() ); // Make sure the FH is visible again } if ( typeConf == null ) { typeConf = getObjectTypeConf(jtmsBeliefSet, false); } defEP.insert( jtmsBeliefSet.getPositiveFactHandle(), node.getObject(), node.getJustifier().getRule(), node.getJustifier(), typeConf, null ); } } public void read(LogicalDependency<M> node, BeliefSet<M> beliefSet, PropagationContext context, ObjectTypeConf typeConf) { throw new UnsupportedOperationException( "This is not serializable yet" ); } public void delete(LogicalDependency<M> node, BeliefSet<M> beliefSet, PropagationContext context) { JTMSBeliefSet<M> jtmsBeliefSet = (JTMSBeliefSet<M>) beliefSet; boolean wasUndecided = jtmsBeliefSet.isUndecided(); boolean wasNegated = jtmsBeliefSet.isNegated(); // If the prime object is removed, we need to update the FactHandle, and tell the callback to update boolean primeChanged = false; if ( (jtmsBeliefSet.getPositiveFactHandle() != null && jtmsBeliefSet.getPositiveFactHandle().getObject() == node.getObject()) || (jtmsBeliefSet.getNegativeFactHandle() != null && jtmsBeliefSet.getNegativeFactHandle().getObject() == node.getObject()) ) { primeChanged = true; } beliefSet.remove( node.getMode() ); if ( beliefSet.isEmpty() ) { if ( wasNegated && ! wasUndecided ) { defEP.getObjectStore().addHandle( beliefSet.getFactHandle(), beliefSet.getFactHandle().getObject() ); // was negated, so add back in, so main retract works InternalFactHandle fh = jtmsBeliefSet.getNegativeFactHandle(); ((NamedEntryPoint) fh.getEntryPoint()).delete( fh, context.getRuleOrigin(), node.getJustifier() ); } if ( !(context.getType() == PropagationContext.DELETION && context.getFactHandle() == beliefSet.getFactHandle()) ) { // don't start retract, if the FH is already in the process of being retracted // do not if the FH is the root of the context, it means it's already in the process of retraction InternalFactHandle fh = jtmsBeliefSet.getFactHandle(); ((NamedEntryPoint) fh.getEntryPoint()).delete( fh, context.getRuleOrigin(), node.getJustifier() ); } } else if ( wasUndecided && !jtmsBeliefSet.isUndecided() ) { insertBelief( node, defEP.getObjectTypeConfigurationRegistry().getObjectTypeConf( defEP.getEntryPoint(), node.getObject() ), jtmsBeliefSet, context, false, wasNegated, wasUndecided ); } else if ( primeChanged ) { // we know there must be at least one more of the same type, as they are still in conflict if ( ( wasNegated && !jtmsBeliefSet.isNegated() ) || ( !wasNegated && jtmsBeliefSet.isNegated() ) ) { // Prime has changed between NEG and POS, so update to correct EntryPoint ObjectTypeConf typeConf = getObjectTypeConf(jtmsBeliefSet, wasNegated ); deleteAfterChangedEntryPoint(node, context, typeConf, jtmsBeliefSet, wasNegated); typeConf = null; // must null it, as insertBelief will reset the neg or the pos FH insertBelief( node, typeConf, jtmsBeliefSet, context, false, wasNegated, wasUndecided ); } else { String value; Object object = null; InternalFactHandle fh = null; if ( jtmsBeliefSet.isNegated() ) { value = MODE.NEGATIVE.getId(); fh = jtmsBeliefSet.getNegativeFactHandle(); // Find the new node, and update the handle to it, Negatives iterate from the last for ( JTMSMode entry = (JTMSMode) jtmsBeliefSet.getLast(); entry != null; entry = (JTMSMode) entry.getPrevious() ) { if ( entry.getValue().equals( value ) ) { object = entry.getLogicalDependency().getObject(); break; } } } else { value = MODE.POSITIVE.getId(); fh = jtmsBeliefSet.getPositiveFactHandle(); // Find the new node, and update the handle to it, Positives iterate from the front for ( JTMSMode entry = (JTMSMode) jtmsBeliefSet.getFirst(); entry != null; entry = (JTMSMode) entry.getNext() ) { if ( entry.getValue() == null || entry.getValue().equals( value ) ) { object = entry.getLogicalDependency().getObject(); break; } } } // Equality might have changed on the object, so remove (which uses the handle id) and add back in if ( fh.getObject() != object ) { ((NamedEntryPoint) fh.getEntryPoint()).getObjectStore().updateHandle( fh, object ); ((NamedEntryPoint) fh.getEntryPoint() ).update( fh, true, fh.getObject(), allSetButTraitBitMask(), object.getClass(), null ); } } } } private ObjectTypeConf getObjectTypeConf(JTMSBeliefSet<M> jtmsBeliefSet, boolean neg) { InternalFactHandle fh; NamedEntryPoint nep; ObjectTypeConfigurationRegistry reg; ObjectTypeConf typeConf;// after the delete, get the new FH and its type conf if ( neg ) { fh = jtmsBeliefSet.getNegativeFactHandle(); } else { fh = jtmsBeliefSet.getPositiveFactHandle(); } nep = (NamedEntryPoint) fh.getEntryPoint(); reg = nep.getObjectTypeConfigurationRegistry(); typeConf = reg.getObjectTypeConf( nep.getEntryPoint(), fh.getObject() ); return typeConf; } public BeliefSet newBeliefSet(InternalFactHandle fh) { return new JTMSBeliefSetImpl( this, fh ); } public LogicalDependency newLogicalDependency(Activation<M> activation, BeliefSet<M> beliefSet, Object object, Object value) { JTMSMode<M> mode; if ( value == null ) { mode = new JTMSMode(MODE.POSITIVE.getId(), this); } else if ( value instanceof String ) { if ( MODE.POSITIVE.getId().equals( value ) ) { mode = new JTMSMode(MODE.POSITIVE.getId(), this); } else { mode = new JTMSMode(MODE.NEGATIVE.getId(), this); } } else { mode = new JTMSMode(((MODE)value).getId(), this); } SimpleLogicalDependency dep = new SimpleLogicalDependency(activation, beliefSet, object, mode); mode.setLogicalDependency( dep ); return dep; } }
package com.sjj.util; import java.util.ArrayList; import java.util.List; import org.apache.spark.api.java.function.FlatMapFunction; import org.apache.spark.sql.Row; import org.apache.spark.sql.RowFactory; import scala.Tuple2; public class DStream2Row implements FlatMapFunction<Tuple2<String, Integer>, Row>{ private static final long serialVersionUID = 5481855142090322683L; @Override public Iterable<Row> call(Tuple2<String, Integer> t) throws Exception { List<Row> list = new ArrayList<>(); list.add(RowFactory.create(t._1, t._2)); return list; } }
package at.ac.tuwien.sepm.groupphase.backend.entity; public enum Permissions { admin, employee }
package com.xianzaishi.wms.tmscore.vo; import com.xianzaishi.wms.tmscore.vo.DeliverVO; public class DeliverDO extends DeliverVO { }
class Solution { List<List<Integer>> output; int[] visited; public List<List<Integer>> allPathsSourceTarget(int[][] graph) { output=new ArrayList<>(); visited=new int[graph.length]; ArrayList<Integer> list=new ArrayList<>(); list.add(0); dfs(graph, list, 0, graph.length-1); return output; } public void dfs(int[][] graph, ArrayList<Integer> list, int start, int end){ if(start==end){ output.add(new ArrayList<>(list)); return; } visited[start]=1; for(int edge:graph[start]){ if(visited[edge]==0){ list.add(edge); dfs(graph,list,edge,end); list.remove(list.size()-1); } } visited[start]=0; } }
import com.jgoodies.forms.factories.FormFactory; import com.jgoodies.forms.layout.ColumnSpec; import com.jgoodies.forms.layout.FormLayout; import com.jgoodies.forms.layout.RowSpec; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.plaf.basic.BasicSplitPaneDivider; import javax.swing.plaf.basic.BasicSplitPaneUI; import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.*; import java.nio.channels.FileChannel; public class WorkSpace extends JFrame { private File saveAdress = null; private JSplitPane splitPane; private JPanel contentPane; private JPanel topToolbar; private JPanel bottomToolBar; private TabbedPane tabHolder; private JLabel wordCount; private JCheckBoxMenuItem miniMapMenuItem; private JScrollPane graphic; private FileWalker fileTree; private Compiler compiler; private boolean mapEnabled; /** * Launch the application. */ /** * Create the frame. */ public void settingChange(){ for(int i = tabHolder.getTabCount()-1;i>=0;i--){ Component tester = tabHolder.getComponentAt(i); if(tester instanceof TextEditor){ TextEditor temp = (TextEditor) tester; temp.setMapState(mapEnabled); } } } public WorkSpace(File f) throws IOException { saveAdress = f; compiler = new Compiler(f.getAbsolutePath()); Theme.initialize(); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 800, 450); setMinimumSize(new Dimension(getWidth() / 4 * 3, 10)); JMenuBar menuBar = new JMenuBar(); menuBar.setBorderPainted(false); setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); JMenuItem newProjectMenuItem = new JMenuItem("New Project"); newProjectMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainFrame.newProject(); } }); fileMenu.add(newProjectMenuItem); JMenuItem loadProjectMenuItem = new JMenuItem("Load Project"); loadProjectMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { MainFrame.loadProject(); } }); fileMenu.add(loadProjectMenuItem); fileMenu.add(new JSeparator()); JMenuItem newScriptMenuItem = new JMenuItem("New Script"); newScriptMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { newScript(); } }); fileMenu.add(newScriptMenuItem); JMenuItem loadMenuItem = new JMenuItem("Import Script"); loadMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final File file = loadChooser(); if (file != null) { loadStory(file); } } public void filler() { } }); fileMenu.add(loadMenuItem); fileMenu.add(new JSeparator()); JMenuItem imageMenuItem = new JMenuItem("Import Image"); imageMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { final File file = loadChooser(); System.out.println("IMAGE: " + saveAdress.getAbsolutePath()+"/Images"); try { copyFile(file,new File(saveAdress.getAbsolutePath()+"/Images/"+file.getName())); } catch (IOException e1) { e1.printStackTrace(); } save(); } private void copyFile(File sourceFile, File destFile) throws IOException { if (!sourceFile.exists()) { return; } if (!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); if (destination != null && source != null) { destination.transferFrom(source, 0, source.size()); } if (source != null) { source.close(); } if (destination != null) { destination.close(); } } public void filler() { } }); fileMenu.add(imageMenuItem); fileMenu.add(new JSeparator()); JMenuItem saveMenuItem = new JMenuItem("Save"); saveMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); } }); fileMenu.add(saveMenuItem); JMenuItem exitMenuItem = new JMenuItem("Exit"); exitMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(confirmDialog("Would you like to save before creating a new Story?", "Save")){ File file = saveStory(); save(); } System.exit(0); } public void filler(){ } }); fileMenu.add(exitMenuItem); /*final JMenu projectMenu = new JMenu("Project"); menuBar.add(projectMenu); JMenuItem structureMenuItem = new JMenuItem("Structure"); structureMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { projectMenu(); } }); projectMenu.add(structureMenuItem); JMenuItem engineMenuItem = new JMenuItem("Engine"); projectMenu.add(engineMenuItem); JMenuItem informationMenuItem = new JMenuItem("Information"); projectMenu.add(informationMenuItem); JMenuItem versionMenuItem = new JMenuItem("Version History"); projectMenu.add(versionMenuItem);*/ JMenu optionMenu = new JMenu("Option"); menuBar.add(optionMenu); final JCheckBoxMenuItem inverseMenuItem = new JCheckBoxMenuItem("Inverse"); inverseMenuItem.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (inverseMenuItem.isSelected()) Theme.setInverse(true); else Theme.setInverse(false); Theme.drawTheme(); } }); optionMenu.add(inverseMenuItem); miniMapMenuItem = new JCheckBoxMenuItem("Minimap"); miniMapMenuItem.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent itemEvent) { if (miniMapMenuItem.isSelected()) mapEnabled = true; else mapEnabled = false; settingChange(); } }); optionMenu.add(miniMapMenuItem); JMenuItem spellcheckMenuItem = new JMenuItem("Spell Check"); //optionMenu.add(spellcheckMenuItem); JMenuItem syntaxMenuItem = new JMenuItem("Syntax Check"); //optionMenu.add(syntaxMenuItem); JMenu scriptMenu = new JMenu("Script"); //menuBar.add(scriptMenu); JMenuItem checkBugMenuItem = new JMenuItem("Check Bug"); scriptMenu.add(checkBugMenuItem); JMenuItem cleanMenuItem = new JMenuItem("Clean "); scriptMenu.add(cleanMenuItem); JMenu organizeMenuItem = new JMenu("Organize by.."); //scriptMenu.add(organizeMenuItem); JMenuItem depthMenuItem = new JMenuItem("Depth"); organizeMenuItem.add(depthMenuItem); JMenuItem chronologicalMenuItem = new JMenuItem("Chronological"); organizeMenuItem.add(chronologicalMenuItem); JMenuItem branchCheckMenuItem = new JMenuItem("Branch Check"); //scriptMenu.add(branchCheckMenuItem); JCheckBoxMenuItem storyModeMenuItem = new JCheckBoxMenuItem("Story Mode"); //scriptMenu.add(storyModeMenuItem); contentPane = new JPanel(){ @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Theme.getColor("borderColor")); g.fillRect(0, 0, contentPane.getWidth(), contentPane.getHeight()); } public void filler(){ } }; contentPane.setBorder(null); Theme.register(contentPane); setContentPane(contentPane); contentPane.setLayout(new FormLayout(new ColumnSpec[]{ ColumnSpec.decode("default:grow"), ColumnSpec.decode("default:grow"),}, new RowSpec[]{ RowSpec.decode("15dlu"), RowSpec.decode("default:grow"), RowSpec.decode("15dlu"),})); topToolbar = new JPanel(){ @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Theme.getColor("backgroundColor")); g.fillRect(0, 0, topToolbar.getWidth(), topToolbar.getHeight()); g.setColor(Theme.getColor("borderColor")); g.drawRect(0,0, topToolbar.getWidth()-1, topToolbar.getHeight()-1); } public void filler(){ } }; Theme.register(topToolbar); topToolbar.setLayout(new FormLayout(new ColumnSpec[]{ ColumnSpec.decode("center:5dlu"), ColumnSpec.decode("center:15dlu"), ColumnSpec.decode("center:1dlu"), ColumnSpec.decode("default:grow"), ColumnSpec.decode("center:1dlu"), ColumnSpec.decode("center:15dlu"), ColumnSpec.decode("center:1dlu"), ColumnSpec.decode("center:15dlu"), ColumnSpec.decode("center:1dlu"), ColumnSpec.decode("center:15dlu"), ColumnSpec.decode("center:5dlu"),}, new RowSpec[]{ RowSpec.decode("15dlu"),})); contentPane.add(topToolbar, "1, 1, 2, 1, fill, fill"); IconButtons fileButton = new IconButtons("F"){ BufferedImage icon = ImageIO.read(new FileInputStream("Images/fileIcon.png")); @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D graphics = (Graphics2D) g.create(); graphics.drawImage(icon, 0, 0, getWidth(),getHeight(),null); graphics.dispose(); } }; fileButton.addActionListener(new ActionListener() { boolean closed = false; @Override public void actionPerformed(ActionEvent e) { if (!closed) { fileTree.setVisible(false); splitPane.setDividerSize(0); closed = true; } else { fileTree.setVisible(true); splitPane.setDividerSize(10); closed = false; splitPane.resetToPreferredSizes(); } } }); Theme.register(fileButton); topToolbar.add(fileButton, "2,1"); IconButtons runButton = new IconButtons("R"){ BufferedImage icon = ImageIO.read(new FileInputStream("Images/runIcon.png")); @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D graphics = (Graphics2D) g.create(); graphics.drawImage(icon, 0, 0, getWidth(),getHeight(),null); graphics.dispose(); } }; runButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); Process proc = null; try { String name = compiler.getBuildAddress(); String engine = compiler.getEngineAddress(); File[] listOfFiles = new File(name).listFiles(); String finalScript = ""; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isDirectory()) { if (listOfFiles[i].getName().equals("Script")) { File[] scriptFiles = listOfFiles[i].listFiles(); for (int s = 0; s < scriptFiles.length; s++) { if (!scriptFiles[s].isHidden()) { if (scriptFiles[s].isFile() && scriptFiles[s].exists()) { BufferedReader reader = new BufferedReader(new FileReader(scriptFiles[s] .getAbsolutePath())); String text; while ((text = reader.readLine()) != null) { finalScript += text + "\n"; } } } } } } } BufferedWriter writer = null; String build = ""; if (new File(compiler.getBuildAddress()).isFile()) build = new File(compiler.getBuildAddress()).getParentFile().getAbsolutePath(); else build = compiler.getBuildAddress(); build += "/result"; writer = new BufferedWriter(new FileWriter(build)); writer.write(finalScript); writer.close(); System.out.println("RUNNING FILE IN: \"" + build + "\""); System.out.println("RUNNING ENGINE IN: \"" + engine + "\""); proc = Runtime.getRuntime().exec("java -jar " + engine + " " + build); } catch (IOException e1) { e1.printStackTrace(); } InputStream in = proc.getInputStream(); InputStream err = proc.getErrorStream(); } public void filler() { } }); Theme.register(runButton); topToolbar.add(runButton, "6,1"); IconButtons buildButton = new IconButtons("B"){ BufferedImage icon = ImageIO.read(new FileInputStream("Images/buildIcon.png")); @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D graphics = (Graphics2D) g.create(); graphics.drawImage(icon, 0, 0, getWidth(),getHeight(),null); graphics.dispose(); } }; buildButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { save(); try { String name = compiler.getBuildAddress(); String engine = compiler.getEngineAddress(); File[] listOfFiles = new File(name).listFiles(); String finalScript =""; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isDirectory()) { if (listOfFiles[i].getName().equals("Script")) { File[] scriptFiles = listOfFiles[i].listFiles(); for (int s = 0; s < scriptFiles.length; s++) { if (!scriptFiles[s].isHidden()) { if(scriptFiles[s].isFile()&&scriptFiles[s].exists()){ BufferedReader reader = new BufferedReader(new FileReader(scriptFiles[s] .getAbsolutePath())); String text; while((text = reader.readLine()) != null) { finalScript+=text+"\n"; } } } } } } } BufferedWriter writer = null; String build = ""; if(new File(compiler.getBuildAddress()).isFile()) build = new File(compiler.getBuildAddress()).getParentFile().getAbsolutePath(); else build = compiler.getBuildAddress(); build +="/result"; writer = new BufferedWriter(new FileWriter(build)); writer.write(finalScript); writer.close(); //System.out.println("RUNNING FILE IN: \"" + build + "\""); //System.out.println("RUNNING ENGINE IN: \"" + engine + "\""); } catch (IOException e1) { e1.printStackTrace(); } } }); Theme.register(buildButton); topToolbar.add(buildButton, "8,1"); IconButtons storyButton = new IconButtons("S"){ BufferedImage icon = ImageIO.read(new FileInputStream("Images/storyIcon.png")); @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D graphics = (Graphics2D) g.create(); graphics.drawImage(icon, 0, 0, getWidth(),getHeight(),null); graphics.dispose(); } }; storyButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { TextEditor temp = (TextEditor) tabHolder.getCurrentComponent(); //temp.getMinimap().draw(); } }); Theme.register(storyButton); //topToolbar.add(storyButton, "10,1"); splitPane = new JSplitPane(); splitPane.setUI(new BasicSplitPaneUI() { public BasicSplitPaneDivider createDefaultDivider() { final JLabel test = new JLabel("TEST"); test.setOpaque(false); test.setPreferredSize(new Dimension(10, Integer.MAX_VALUE)); BasicSplitPaneDivider divider = new BasicSplitPaneDivider(this) { public int getDividerSize() { if (getOrientation() == JSplitPane.HORIZONTAL_SPLIT) { return test.getPreferredSize().width; } return Integer.MAX_VALUE; } @Override public void paint(Graphics g) { g.setColor(Theme.getColor("borderColor")); g.fillRect(0, 0, getWidth(), getHeight()); super.paint(g); } }; divider.setBackground(Color.RED); divider.add(test); return divider; } public void filler() { } }); splitPane.setBorder(null); splitPane.setContinuousLayout(true); contentPane.add(splitPane, "1, 2, 2, 1, fill, fill"); graphic = new JScrollPane(); graphic.getHorizontalScrollBar().setUnitIncrement(10); graphic.getVerticalScrollBar().setUnitIncrement(10); graphic.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); graphic.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); fileTree = new FileWalker(saveAdress, this); fileTree.setPreferredSize(new Dimension(getWidth() / 4, getHeight())); Theme.register(fileTree); splitPane.setLeftComponent(fileTree); ScriptDrawer drawingCanvas = new ScriptDrawer(); graphic.getViewport().scrollRectToVisible(new Rectangle(3000, 3000, 100, 100)); drawingCanvas.setBorder(null); drawingCanvas.setBackground(new Color(60, 111, 153)); graphic.setViewportView(drawingCanvas); tabHolder = new TabbedPane(); tabHolder.setBorder(null); splitPane.setRightComponent(tabHolder); bottomToolBar = new JPanel(){ @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Theme.getColor("backgroundColor")); g.fillRect(0, 0, bottomToolBar.getWidth(), bottomToolBar.getHeight()); g.setColor(Theme.getColor("borderColor")); g.drawRect(0,0, bottomToolBar.getWidth()-1, bottomToolBar.getHeight()-1); } public void filler(){ } }; bottomToolBar.setLayout(new FormLayout(new ColumnSpec[]{ FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("center:15dlu"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("pref:grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("center:pref:grow"), FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,}, new RowSpec[]{ RowSpec.decode("default:grow"),})); contentPane.add(bottomToolBar, "1, 3, 2, 1, fill, fill"); wordCount = new JLabel("TEST"); wordCount.setFont(Theme.getDefaultFont()); Theme.register(wordCount); bottomToolBar.add(wordCount, "6, 1"); initializeTabs(f); pack(); setVisible(true); setTitle(saveAdress.getName()); setLocationRelativeTo(null); } public void projectMenu(){ final JDialog project = new JDialog(); project.setModal(true); project.setTitle("Project Structure"); project.setSize(new Dimension(500, 300)); project.setLocationRelativeTo(null); project.setResizable(false); JPanel contentPane = new JPanel(){ @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Theme.getColor("backgroundColor")); g.fillRect(0, 0, project.getWidth(), project.getHeight()); g.setColor(Theme.getColor("borderColor")); g.drawRect(0,0, project.getWidth()-1, project.getHeight()-1); } public void filler(){ } }; contentPane.setLayout(new FormLayout(new ColumnSpec[]{ FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("pref:grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("center:15dlu"), FormFactory.RELATED_GAP_COLSPEC,}, new RowSpec[]{ RowSpec.decode("center:5dlu"), RowSpec.decode("default:grow"), RowSpec.decode("default:grow"), RowSpec.decode("center:20dlu"), RowSpec.decode("default:grow"), RowSpec.decode("default:grow"), RowSpec.decode("center:20dlu"), RowSpec.decode("default:grow"), RowSpec.decode("default:grow"), RowSpec.decode("center:20dlu"), RowSpec.decode("default:grow"),})); project.setContentPane(contentPane); final JLabel sLocation = new JLabel("Script Location:"); sLocation.setForeground(Theme.getColor("defaultColor")); contentPane.add(sLocation, "2,2"); final JTextField sLocField = new JTextField(); sLocField.setText(compiler.getScriptAddress()); contentPane.add(sLocField, "2,3"); JButton sLocButton = new JButton(" ... "); sLocButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { File name = loadChooser(); if(name!=null) { sLocField.setText(name.getAbsolutePath()); compiler.setScriptAddress(name.getAbsolutePath()); } } public void filler(){ } }); sLocButton.setForeground(Theme.getColor("defaultColor")); sLocButton.setBorder(BorderFactory.createLineBorder(Theme.getColor("nullColor"), 1)); contentPane.add(sLocButton, "4,3"); JLabel imageLocation = new JLabel("Image Location:"); imageLocation.setForeground(Theme.getColor("defaultColor")); contentPane.add(imageLocation, "2,4"); final JTextField iLocField = new JTextField(); iLocField.setText(compiler.getImageAddress()); contentPane.add(iLocField, "2,5"); JButton iLocButton = new JButton(" ... "); iLocButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { File name = loadChooser(); if(name!=null) { iLocField.setText(name.getAbsolutePath()); compiler.setImageAddress(name.getAbsolutePath()); } } public void filler(){ } }); iLocButton.setForeground(Theme.getColor("defaultColor")); iLocButton.setBorder(BorderFactory.createLineBorder(Theme.getColor("nullColor"), 1)); contentPane.add(iLocButton, "4,5"); JLabel buildLocation = new JLabel("Build Location:"); buildLocation.setForeground(Theme.getColor("defaultColor")); contentPane.add(buildLocation, "2,6"); final JTextField bLocField = new JTextField(); bLocField.setText(compiler.getBuildAddress()); contentPane.add(bLocField, "2,7"); JButton bLocButton = new JButton(" ... "); bLocButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { File name = loadChooser(); if(name!=null) { bLocField.setText(name.getAbsolutePath()); compiler.setBuildAddress(name.getAbsolutePath()); } } public void filler(){ } }); bLocButton.setForeground(Theme.getColor("defaultColor")); bLocButton.setBorder(BorderFactory.createLineBorder(Theme.getColor("nullColor"), 1)); contentPane.add(bLocButton, "4,7"); project.setVisible(true); } public void updateWordCount(String i){ wordCount.setText(i); } public void rename(File f){ String name = (String)JOptionPane.showInputDialog( this, "Type a New Name: ", "Rye Bard", JOptionPane.PLAIN_MESSAGE, null, null, null); if(name!=null) { File result; for(int i = tabHolder.getTabCount()-1;i>=0;i--){ Component tester = tabHolder.getComponentAt(i); if(tester instanceof TextEditor){ TextEditor temp = (TextEditor) tabHolder.getComponentAt(i); if(temp.getAddress().equals(f)){ //temp. } } } f.renameTo(new File(f.getParentFile().getAbsolutePath()+"/"+name)); } } public void newScript(){ String name = newFile(); if(name!=null) { tabHolder.addTab(name, new TextEditor(name, new File(saveAdress.getAbsolutePath() + "/Script" + "/" + name),this)); } save(); } public void newScript(File f){ String name = newFile(); if(name!=null) { tabHolder.addTab(name, new TextEditor(name,new File(f+"/"+name),this)); } save(); } public void save(){ File file = new File(saveAdress.getAbsolutePath()+"/Script"); if(file!=null) { for(int i = tabHolder.getTabCount()-1;i>=0;i--){ Component tester = tabHolder.getComponentAt(i); if(tester instanceof TextEditor){ TextEditor temp = (TextEditor) tabHolder.getComponentAt(i); Database.save(temp.getAddress(), temp.getReader().getText()); } } } fileTree.updateTree(); } public void initializeTabs(final File f){ final WorkSpace k = this; Thread t = new Thread(new Runnable() { @Override public void run() { File[] listOfFiles = f.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isDirectory()) { if (listOfFiles[i].getName().equals("Script")) { File[] scriptFiles = listOfFiles[i].listFiles(); for (int s = 0; s < scriptFiles.length; s++) { if (!scriptFiles[s].isHidden()) { final String name = scriptFiles[s].getName(); if(scriptFiles[s].isFile()&&scriptFiles[s].exists()){ tabHolder.addTab(name, new TextEditor(name,scriptFiles[s], k)); TextEditor temp = (TextEditor) tabHolder.getCurrentComponent(); temp.getReader().overrideText(Database.load(scriptFiles[s])); } } } } else if (listOfFiles[i].getName().equals("Pictures")) { File[] pictureFiles = f.listFiles(); for (int p = 0; p<pictureFiles.length;p++){ } } } } //tabHolder.addTab("Layout", graphic); mapEnabled = false; miniMapMenuItem.setSelected(false); tabHolder.revalidate(); tabHolder.repaint(); settingChange(); } }); t.start(); } public String newFile(){ String k = (String)JOptionPane.showInputDialog( this, "Name your File: ", "Rye Bard", JOptionPane.PLAIN_MESSAGE, null, null, null); return k; } public boolean confirmDialog(String content, String title){ int n = JOptionPane.showConfirmDialog(this, content , title, JOptionPane.YES_NO_OPTION,JOptionPane.PLAIN_MESSAGE); if(n==JOptionPane.NO_OPTION) { return false; } else{ return true; } } public File saveStory(){ JFileChooser fc = new JFileChooser(Database.getSaveFiles()); int returnVal = fc.showDialog(this, "Save"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); return file; } return null; } public void loadStory(File f){ String name = f.getName(); tabHolder.addTab(name, new TextEditor(name,f,this)); TextEditor temp = (TextEditor) tabHolder.getCurrentComponent(); temp.getReader().overrideText(Database.load(f)); repaint(); } public File loadChooser(){ JFileChooser fc = new JFileChooser(Database.getSaveFiles()){ @Override protected JDialog createDialog(Component parent) throws HeadlessException { // intercept the dialog created by JFileChooser JDialog dialog = super.createDialog(null); dialog.setModal(true); // set modality (or setModalityType) return dialog; } }; int returnVal = fc.showDialog(this, "Load"); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); return file; } return null; } class TabbedPane extends JPanel{ private JPanel tabBar; private JPanel view; private JPanel drag = new JPanel(); private Tab previousTab; private Tab selectedTab; private JPanel glass = new JPanel(); private int xDrag = 0; private int startDrag = 0; CardLayout card = new CardLayout(){ @Override public void show(Container c, String n){ super.show(c, n); for(Component temp : tabBar.getComponents()){ if(n.equals(temp.getName())){ previousTab = selectedTab; if(previousTab!=null) previousTab.deselect(); selectedTab = (Tab) temp; selectedTab.select(); repaint(); } } } public void filler(){ } }; public TabbedPane(){ setLayout(new FormLayout(new ColumnSpec[]{ ColumnSpec.decode("default:grow"),}, new RowSpec[]{ RowSpec.decode("15dlu"), RowSpec.decode("3dlu"), RowSpec.decode("default:grow"),})); tabBar = new JPanel(){ @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Theme.getColor("backgroundColor")); g.fillRect(0, 0, tabBar.getWidth(), tabBar.getHeight()); g.setColor(Theme.getColor("borderColor")); g.drawRect(0,0,tabBar.getWidth()-1, tabBar.getHeight()-1); } public void filler(){ } }; tabBar.setLayout(new BoxLayout(tabBar, BoxLayout.X_AXIS)); add(tabBar, "1, 1, fill, fill"); JPanel seperator = new JPanel(){ @Override public void paintComponent(Graphics g){ g.setColor(Theme.getColor("backgroundColor")); g.fillRect(0, 0, this.getWidth(), this.getHeight()); } public void filler(){ } }; seperator.setBorder(null); add(seperator, "1,2,fill,fill"); view = new JPanel(){ @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Theme.getColor("backgroundColor")); g.fillRect(0, 0, view.getWidth(), view.getHeight()); g.setColor(Theme.getColor("borderColor")); g.drawRect(0,0,view.getWidth()-1, view.getHeight()-1); } public void filler(){ } }; view.setLayout(card); add(view, "1, 3, fill, fill"); Theme.register(this); setGlassPane(glass); } public void renameTab(Tab t, String name){ t.renameTab(name); repaint(); } public void addTab(final String name, final JComponent c){ final Tab addedTab = new Tab(c,name); boolean exists = false; for(Component temp : tabBar.getComponents()){ if(temp instanceof Tab) if(addedTab.getName().equals(temp.getName())) { card.show(view,name); exists = true; } } if(exists==false){ tabBar.add(addedTab); view.add(c, name); addedTab.addComponentListener(new ComponentAdapter() { @Override public void componentHidden(ComponentEvent componentEvent) { super.componentHidden(componentEvent); removeTab(addedTab); } public void filler() { } }); addedTab.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent mouseEvent) { super.mousePressed(mouseEvent); card.show(view, name); Point location = new Point(mouseEvent.getComponent().getLocation().x + mouseEvent.getPoint().x, 0); if (tabBar.getComponentAt(location) instanceof Tab) { Tab compare = (Tab) tabBar.getComponentAt(location); drag.setBackground(Theme.getColor("highlightColor")); xDrag = mouseEvent.getXOnScreen(); startDrag = compare.getLocationOnScreen().x; glass.add(drag); glass.setOpaque(false); glass.setVisible(true); glass.setLayout(null); drag.setSize(compare.getWidth(), compare.getHeight()); drag.setLocation(startDrag - (xDrag - mouseEvent.getXOnScreen()) - contentPane.getLocationOnScreen().x, drag.getHeight()); } } @Override public void mouseReleased(MouseEvent mouseEvent) { super.mouseReleased(mouseEvent); card.show(view, name); xDrag = -1; startDrag = -1; glass.setVisible(false); glass.setLayout(null); glass.remove(drag); } }); addedTab.addMouseMotionListener(new MouseAdapter() { int order = -2; Tab compare; boolean dragStart = false; @Override public void mouseDragged(MouseEvent mouseEvent) { super.mouseDragged(mouseEvent); Point location = new Point(mouseEvent.getComponent().getLocation().x + mouseEvent.getPoint().x, 0); if (compare != null && compare.equals(tabBar.getComponentAt(location))) { drag.setLocation(startDrag - (xDrag - mouseEvent.getXOnScreen()) - contentPane.getLocationOnScreen().x, drag.getHeight()); } else { if (tabBar.getComponentAt(location) instanceof Tab) compare = (Tab) tabBar.getComponentAt(location); if (order != tabBar.getComponentZOrder(compare)) { order = tabBar.getComponentZOrder(compare); if (order != -1) { tabBar.setComponentZOrder(addedTab, order); tabBar.revalidate(); tabBar.repaint(); } } } } }); view.revalidate(); card.show(view, name); } } public void removeTab(Tab c){ Tab previous = null; for(Component temp : tabBar.getComponents()){ Tab tab = (Tab) temp; if(tab.equals(c) && previous != null){ card.show(view,previous.getName()); previous.select(); } previous = tab; } tabBar.remove(c); view.remove(c.getSubstance()); } public int getTabCount(){ return tabBar.getComponentCount(); } public Component getCurrentComponent(){ return selectedTab.getSubstance(); } public Component getComponentAt(int i){ int threshhold = tabBar.getComponentCount(); Tab t = (Tab) tabBar.getComponent(i); if(threshhold-1<i||!(t instanceof Tab)){ return null; } return t.getSubstance(); } public void showComponent(int i){ int threshhold = tabBar.getComponents().length; if(threshhold-1>=i){ Component[] c = tabBar.getComponents(); Tab test = (Tab) c[threshhold]; card.show(view,test.getName()); } } @Override public void paintComponent(Graphics g){ super.paintComponent(g); for(Component temp : tabBar.getComponents()){ if(temp instanceof Tab) ((Tab) temp).redraw(); } } private class Tab extends JPanel{ JComponent substance; JLabel name; JLabel exit; boolean dragged = false; boolean selected = false; public Tab(JComponent c, String n){ substance = c; Theme.register(this); setBorder(BorderFactory.createLineBorder(Theme.getColor("borderColor"))); setLayout(new FormLayout(new ColumnSpec[]{ ColumnSpec.decode("default:grow"), FormFactory.RELATED_GAP_COLSPEC, ColumnSpec.decode("10dlu"),}, new RowSpec[]{ RowSpec.decode("default:grow"),})); setBackground(Color.WHITE); name = new JLabel(); name.setHorizontalAlignment(SwingConstants.CENTER); name.setFont(Theme.getDefaultFont().deriveFont(12f)); name.setText(n); add(name, "1,1"); exit = new JLabel("x"); exit.addMouseListener(new MouseAdapter() { @Override public void mouseExited(MouseEvent mouseEvent) { super.mouseExited(mouseEvent); exit.setForeground(Theme.getColor("borderColor")); } @Override public void mouseEntered(MouseEvent mouseEvent) { super.mouseEntered(mouseEvent); exit.setForeground(Theme.getColor("defaultColor")); } @Override public void mouseReleased(MouseEvent mouseEvent) { super.mouseReleased(mouseEvent); setVisible(false); } }); exit.setForeground(Theme.getColor("borderColor")); exit.setHorizontalAlignment(SwingConstants.CENTER); add(exit,"3,1"); } public void select(){ selected = true; redraw(); } public void deselect(){ selected = false; redraw(); } public String getName(){ return name.getText(); } public void renameTab(String n){ name.setText(n); redraw(); repaint(); } public JComponent getSubstance(){ return substance; } public void redraw(){ name.setForeground(Theme.getColor("defaultColor")); exit.setForeground(Theme.getColor("borderColor")); setBorder(BorderFactory.createLineBorder(Theme.getColor("borderColor"))); if(selected) { setBackground(Theme.getColor("backgroundColor")); } else { setBackground(Theme.getColor("secondaryColor")); } } } } }
package pv260.customeranalysis.interfaces; import pv260.customeranalysis.exceptions.GeneralException; import java.util.List; public interface Storage { <T> T find(Class<T> type, long key); int update(Object record) throws GeneralException; int persist(Object record) throws GeneralException; int persist(List<Object> records) throws GeneralException; }
package pt.sinfo.testDrive.exception; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.http.HttpStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class BookingNotFoundException extends TestDriveException { public BookingNotFoundException() { super(); } }
package com.binarysprite.evemat.page.transaction; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.wicket.AttributeModifier; import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.navigation.paging.PagingNavigator; import org.apache.wicket.markup.repeater.Item; import org.apache.wicket.markup.repeater.data.DataView; import org.apache.wicket.model.IModel; import org.apache.wicket.model.Model; import com.binarysprite.evemat.Constants; import com.binarysprite.evemat.entity.WalletTransaction; import com.binarysprite.evemat.page.FramePage; import com.binarysprite.evemat.page.transaction.data.WalletTransactionModelObject; import com.binarysprite.evemat.panel.PaginationPanel; import com.google.inject.Inject; /** * 取引情報を表示するウェブページクラスです。 * * @author Tabunoki * */ public class TransactionPage extends FramePage { /** * */ private static final long serialVersionUID = 1086855179809928708L; /** * */ public static final String WICKET_ID_TRANSACTION_DATA_VIEW = "transactionDataView"; /** * */ public static final String WICKET_ID_WHEN_LABEL = "whenLabel"; /** * */ public static final String WICKET_ID_TYPE_NAME_LABEL = "typeNameLabel"; /** * */ public static final String WICKET_ID_PRICE_LABEL = "priceLabel"; /** * */ public static final String WICKET_ID_QUANTITY_LABEL = "quantityLabel"; /** * */ public static final String WICKET_ID_CLIENT_LABEL = "clientLabel"; /** * */ public static final String WICKET_ID_STATION_LABEL = "stationLabel"; /** * */ public static final String WICKET_ID_PAGING_NAVIGATOR = "pagingNavigator"; /** * トランザクションのデータプロバイダです。 */ private final SortableDataProvider<WalletTransactionModelObject, String> transactionDataProvider = new SortableDataProvider<WalletTransactionModelObject, String>() { /** * {@inheritDoc} */ @Override public Iterator<? extends WalletTransactionModelObject> iterator(long first, long count) { List<WalletTransaction> walletTransactions = transactionPageService.select(first, count); List<WalletTransactionModelObject> walletTransactionsModelObjects = new ArrayList<WalletTransactionModelObject>(); for (WalletTransaction walletTransaction : walletTransactions) { walletTransactionsModelObjects.add(new WalletTransactionModelObject(walletTransaction)); } return walletTransactionsModelObjects.iterator(); } /** * {@inheritDoc} */ @Override public IModel<WalletTransactionModelObject> model(WalletTransactionModelObject walletTransaction) { return new Model<WalletTransactionModelObject>(walletTransaction); } /** * {@inheritDoc} */ @Override public long size() { return transactionPageService.count(); } }; /** * トランザクションのデータビューです。 */ private final DataView<WalletTransactionModelObject> transactionDataView = new DataView<WalletTransactionModelObject>( WICKET_ID_TRANSACTION_DATA_VIEW, transactionDataProvider, 100) { /** * {@inheritDoc} */ @Override protected void populateItem(Item<WalletTransactionModelObject> item) { final WalletTransactionModelObject object = item.getModelObject(); /* * コンポーネントの生成 */ final Label whenLabel = new Label( WICKET_ID_WHEN_LABEL, Constants.DATE_TIME_FORMAT.format(object.getTransactionDateTime().getTime())); final Label typeNameLabel = new Label( WICKET_ID_TYPE_NAME_LABEL, object.getTypeName()); final Label priceLabel = new Label( WICKET_ID_PRICE_LABEL, Constants.PRICE_FORMAT.format(object.getPrice())); final Label quantityLabel = new Label( WICKET_ID_QUANTITY_LABEL, Constants.QUANTITY_FORMAT.format(object.getQuantity())); final Label clientLabel = new Label( WICKET_ID_CLIENT_LABEL, object.getClientName()); final Label stationLabel = new Label( WICKET_ID_STATION_LABEL, object.getStationName()); /* * コンポーネントの編集 */ if (object.getTransactionType().equals("sell")) { priceLabel.add(new AttributeModifier("class", "sell-price")); } else { priceLabel.add(new AttributeModifier("class", "buy-price")); } quantityLabel.add(new AttributeModifier("class", "quantity")); /* * コンポーネントの組立 */ item.add(whenLabel); item.add(typeNameLabel); item.add(priceLabel); item.add(quantityLabel); item.add(clientLabel); item.add(stationLabel); } }; /** * */ @Inject private TransactionPageService transactionPageService; /** * */ public TransactionPage() { super(); /* * コンポーネントの生成 */ final Label title = new Label(WICKET_ID_PAGE_TITLE_LABEL, "Transaction"); final PagingNavigator pagingNavigator = new PaginationPanel(WICKET_ID_PAGING_NAVIGATOR, transactionDataView); /* * コンポーネントの編集 */ /* * コンポーネントの組立 */ add(title); add(transactionDataView); add(pagingNavigator); } }
package com.bot.updaters; import com.bot.currencies.Market; import com.bot.enums.City; import com.bot.enums.Commands; import com.bot.enums.MarketType; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import java.io.IOException; import java.util.*; public class AuctionUpdater { private final String usdUrl = "https://minfin.com.ua/currency/auction/usd/buy/"; private final String eurUrl = "https://minfin.com.ua/currency/auction/eur/buy/"; private final String rubUrl = "https://minfin.com.ua/currency/auction/rub/buy/"; private List<City> cities = new ArrayList<>(Arrays.asList(City.values())); public Map<City, Market> update(Commands currency) { Map<City, Market> result = new HashMap<>(); for (City city : cities) { try { result.put(city, getMarket(getFullUrl(currency, city))); } catch (IOException e) { e.printStackTrace(); } } return result; } private String getFullUrl(Commands currency, City city) { switch (currency) { case USD: return usdUrl + city.getEndOfUrl(); case EURO: return eurUrl + city.getEndOfUrl(); case RUB: return rubUrl + city.getEndOfUrl(); default: return ""; } } public Market getMarket(String url) throws IOException { Document html = Jsoup.connect(url).get(); List<String> list = html.body().getElementsByClass("au-mid-buysell").eachText(); System.out.println(url); return new Market(getFloatFromString(list.get(0)), getFloatFromString(list.get(1).substring(0, 25)), MarketType.AUCTION); } private float getFloatFromString(String string) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < string.length(); i++) { if (Character.isDigit(string.charAt(i)) || string.charAt(i) == ',') { if (string.charAt(i) == ',') sb.append('.'); else sb.append(string.charAt(i)); } } return Float.parseFloat(sb.toString()); } }
package io.dcbn.backend.evidence_formula.services; import de.fraunhofer.iosb.iad.maritime.datamodel.Vessel; import io.dcbn.backend.evidence_formula.services.exceptions.ParameterSizeMismatchException; import io.dcbn.backend.evidence_formula.services.exceptions.SymbolNotFoundException; import io.dcbn.backend.evidence_formula.services.exceptions.TypeMismatchException; import io.dcbn.backend.evidence_formula.services.visitors.FunctionWrapper; import lombok.Setter; import java.util.*; /** * This provides the DSL Evaluation with the required predefined functions. */ public class FunctionProvider { protected Map<String, FunctionWrapper> functions; protected Set<Vessel> correlatedVessels; protected Set<String> correlatedAois; @Setter protected int currentTimeSlice; @Setter protected Vessel currentVessel; /** * Creates a new FunctionProvider without any predefined functions. */ public FunctionProvider() { this(new HashMap<>()); } /** * Creates a new FunctionProvider with the given predefined functions. * * @param functions the map containing the predefined functions. */ public FunctionProvider(Map<String, FunctionWrapper> functions) { this.functions = functions; correlatedVessels = new HashSet<>(); correlatedAois = new HashSet<>(); } /** * Calls the predefined function under the given name. * * @param name the name of the function to call. * @param parameters the parameters of the function. * @return the return value of the called function. * @throws SymbolNotFoundException when no function with the given name is found. * @throws ParameterSizeMismatchException when the number of parameters that the function is * called with does not match the number of expected * parameters. * @throws TypeMismatchException when the parameters of the function call do not match * the functions expected parameters. */ public Object call(String name, List<Object> parameters) { if (!functions.containsKey(name)) { throw new SymbolNotFoundException(name); } FunctionWrapper wrapper = functions.get(name); List<Class<?>> expectedTypes = wrapper.getExpectedParameterTypes(); if (parameters.size() != expectedTypes.size()) { throw new ParameterSizeMismatchException(name, expectedTypes.size(), parameters.size()); } for (int i = 0; i < parameters.size(); ++i) { if (!expectedTypes.get(i).isInstance(parameters.get(i))) { throw new TypeMismatchException(expectedTypes.get(i), parameters.get(i).getClass()); } } return wrapper.getFunction().apply(parameters); } /** * Resets the correlated vessel and area of interest sets. */ public void reset() { correlatedVessels.clear(); correlatedAois.clear(); } /** * Returns an unmodifiable set of vessels which where included by the previously evaluated functions. * * @return an unmodifiable set of vessels which where included by the previously evaluated functions. */ public Set<Vessel> getCorrelatedVessels() { return correlatedVessels; } /** * Returns an unmodifiable set of areas of interest which where included by the previously evaluated functions. * * @return an unmodifiable set of areas of interest which where included by the previously evaluated functions. */ public Set<String> getCorrelatedAois() { return correlatedAois; } }
package examples; public class example4 { static int calcular(int[] calc) { calc[1] = 10; //caucou alteracao na area na posicao 1 return (calc[0] + calc[1] + calc[2]); } public static void main(String[] args) { int[] v = {1, 2, 3}; System.out.println("Array antes " + v[0] + ", " + v[1] + ", " + v[2]); System.out.println("Soma da array = " + calcular(v)); System.out.println("Array antes " + v[0] + ", " + v[1] + ", " + v[2]); } }
public class Solution { public void print1ToMaxOfDigitals(int n) { int[] ints = new int[n]; boolean isEnd = false; while (!isEnd) { if (ints[n-1]!=9) { ints[n-1]++; }else { int index = plusIndex(ints); if (index!=-1) { ints[index]++; ints[n-1] = 0; }else break; } StringBuilder stringBuilder = new StringBuilder(n + 1); boolean isPre = true; for (Integer num:ints) { if (!num.equals(0)) { isPre = false; } if (!isPre) stringBuilder.append(num); } System.out.println(stringBuilder.toString()); } } public static void main(String[] args) { Solution solution = new Solution(); solution.print1ToMaxOfDigitals(3); } private int plusIndex(int[] array) { // 从后往前遍历,寻找第一个不为9的数的位置 // System.out.println("plusIndex()测试"+Arrays.toString(array)); int i = array.length - 1; while (i>=0) { if (array[i]!=9) return i; i--; } return -1; } }
package palamarchuk.bcalendargroups; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import palamarchuk.bcalendargroups.adapters.EventMembersAdapter; import palamarchuk.bcalendargroups.adapters.GroupMembersAdapter; import palamarchuk.bcalendargroups.adapters.SearchPeopleAdapter; public class EventMembers extends Activity { // private SearchPeopleAdapter searchPeopleAdapter; // private GroupMembersAdapter groupMembersAdapter; // // private GroupMembers.LoadGroupMembers loadGroupMembers; // private GroupMembers.SearchUsersAndAdd searchUsersAndAdd; private ListView eventMembersListView; private EventMembersAdapter eventMembersAdapter; // private Button eventMembersAddMember; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event_members); // groupMembersAdapter = new GroupMembersAdapter(getActivity(), // R.layout.group_member_item); eventMembersAdapter = new EventMembersAdapter(getActivity(), R.layout.event_member_item); eventMembersListView = (ListView) findViewById(R.id.eventMembersListView); eventMembersListView.setAdapter(eventMembersAdapter); // eventMembersAddMember = (Button) findViewById(R.id.eventMembersAddMember); // eventMembersAddMember.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // try { // loadGroupMembers.loadGroupMembers(SingleGroup.getGroupId(getActivity())); // } catch (JSONException e) { // e.printStackTrace(); // throw new RuntimeException(e); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // throw new RuntimeException(e); // } // } // }); // // loadGroupMembers = new GroupMembers.LoadGroupMembers(getActivity(), groupMembersAdapter); // searchUsersAndAdd = new GroupMembers.SearchUsersAndAdd(getActivity(), searchPeopleAdapter); try { getEventMembers(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(e); } } private Activity getActivity() { return EventMembers.this; } ArrayList<EventMembersAdapter.OneEventMember> oneEventMembers = new ArrayList<EventMembersAdapter.OneEventMember>(); private void getEventMembers() throws UnsupportedEncodingException, JSONException { final QueryMaster.OnCompleteListener onEventLoadComplete = new QueryMaster.OnCompleteListener() { @Override public void complete(String serverResponse) { QueryMaster.alert(getActivity(), serverResponse); try { JSONObject jsonObject = new JSONObject(serverResponse); if (QueryMaster.isSuccess(jsonObject)) { JSONArray jsonArray = jsonObject.getJSONArray("data"); eventMembersAdapter.add(jsonArray); } else { QueryMaster.toast(getActivity(), "Нет участников"); } } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override public void error(int errorCode) { QueryMaster.alert(getActivity(), "error"); } }; GroupAssignmentActions.getEventMembers(getActivity(), onEventLoadComplete, SingleGroup.getGroupId(getActivity()), SingleEvent.getEventId(getActivity())); } }
package com.nisira.core.dao; import com.nisira.core.entity.*; import java.util.List; import android.database.sqlite.SQLiteDatabase; import com.nisira.core.database.DataBaseClass; import android.content.ContentValues; import android.database.Cursor; import com.nisira.core.util.ClaveMovil; import java.util.ArrayList; import java.util.LinkedList; import java.text.SimpleDateFormat; import java.util.Date; public class DordenliquidaciongastoDao extends BaseDao<Dordenliquidaciongasto> { public DordenliquidaciongastoDao() { super(Dordenliquidaciongasto.class); } public DordenliquidaciongastoDao(boolean usaCnBase) throws Exception { super(Dordenliquidaciongasto.class, usaCnBase); } public void mezclarLocal(Dordenliquidaciongasto obj)throws Exception{ if(obj !=null){ List<Dordenliquidaciongasto> lst= listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? AND LTRIM(RTRIM(t0.IDORDEN))=? AND LTRIM(RTRIM(t0.ITEM))=?",obj.getIdempresa().trim(),obj.getIdorden().trim(),obj.getItem().trim()); if(lst.isEmpty()) insertar(obj); else actualizar(obj); } } public List<Dordenliquidaciongasto> listar(Dordenliquidaciongasto obj)throws Exception{ List<Dordenliquidaciongasto> lst= listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? AND LTRIM(RTRIM(t0.IDORDEN))=? ORDER BY LTRIM(RTRIM(t0.ITEM)) ",obj.getIdempresa().trim(),obj.getIdorden().trim()); return lst; } public List<Dordenliquidaciongasto> listarxOrdenLG(Ordenliquidaciongasto obj)throws Exception{ List<Dordenliquidaciongasto> lst= listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? AND LTRIM(RTRIM(t0.IDORDEN))=? ORDER BY LTRIM(RTRIM(t0.ITEM)) ",obj.getIdempresa().trim(),obj.getIdorden().trim()); return lst; } public List<Dordenliquidaciongasto> ListarxOrdenLiq(Ordenliquidaciongasto obj)throws Exception{ if (obj != null){ List<Dordenliquidaciongasto> lst = listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? AND LTRIM(RTRIM(t0.IDORDEN))=? ",obj.getIdempresa().trim(),obj.getIdorden().trim()); Concepto_cuentaDao dao = new Concepto_cuentaDao(); int i=0; for(Dordenliquidaciongasto item:lst){ List<Concepto_cuenta> lista = dao.listar("LTRIM(RTRIM(t0.IDEMPRESA)) =? AND LTRIM(RTRIM(t0.IDCONCEPTO))=?",item.getIdempresa().trim(),item.getIdconcepto().trim()); if(!lst.isEmpty()){ item.setDescripcion_concepto(lista.get(0).getDescripcion()); lst.set(i,item); } i++; } return lst; } return null; } public Boolean insert(Dordenliquidaciongasto dordenliquidaciongasto) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",dordenliquidaciongasto.getIdempresa()); initialValues.put("IDORDEN",dordenliquidaciongasto.getIdorden()); initialValues.put("ITEM",dordenliquidaciongasto.getItem()); initialValues.put("GLOSA",dordenliquidaciongasto.getGlosa()); initialValues.put("IDCONCEPTO",dordenliquidaciongasto.getIdconcepto()); initialValues.put("IDCUENTA",dordenliquidaciongasto.getIdcuenta()); initialValues.put("IDCCOSTO",dordenliquidaciongasto.getIdccosto()); initialValues.put("IDTIPOMOV",dordenliquidaciongasto.getIdtipomov()); initialValues.put("IDCLIEPROV",dordenliquidaciongasto.getIdclieprov()); initialValues.put("IDDOCUMENTO",dordenliquidaciongasto.getIddocumento()); initialValues.put("SERIE",dordenliquidaciongasto.getSerie()); initialValues.put("NUMERO",dordenliquidaciongasto.getNumero()); initialValues.put("FECHA",dateFormat.format(dordenliquidaciongasto.getFecha() ) ); initialValues.put("IDDESTINO",dordenliquidaciongasto.getIddestino()); initialValues.put("IDMONEDA",dordenliquidaciongasto.getIdmoneda()); initialValues.put("TCMONEDA",dordenliquidaciongasto.getTcmoneda()); initialValues.put("TCAMBIO",dordenliquidaciongasto.getTcambio()); initialValues.put("IDREGIMEN",dordenliquidaciongasto.getIdregimen()); initialValues.put("AFECTO", String.valueOf(dordenliquidaciongasto.getAfecto())); initialValues.put("INAFECTO", String.valueOf(dordenliquidaciongasto.getInafecto())); initialValues.put("PIMPUESTO",dordenliquidaciongasto.getPimpuesto()); initialValues.put("IMPUESTO", String.valueOf(dordenliquidaciongasto.getImpuesto())); initialValues.put("IMPORTE", String.valueOf(dordenliquidaciongasto.getImporte())); initialValues.put("OTROS",dordenliquidaciongasto.getOtros()); initialValues.put("IDCONSUMIDOR",dordenliquidaciongasto.getIdconsumidor()); initialValues.put("NUMERO_RCOMPRAS",dordenliquidaciongasto.getNumero_rcompras()); initialValues.put("IDMEDIDA",dordenliquidaciongasto.getIdmedida()); initialValues.put("IDPRODUCTO",dordenliquidaciongasto.getIdproducto()); initialValues.put("ITEMALMACEN",dordenliquidaciongasto.getItemalmacen()); initialValues.put("PRODUCTO",dordenliquidaciongasto.getProducto()); initialValues.put("VENTANA",dordenliquidaciongasto.getVentana()); initialValues.put("CANTIDAD",dordenliquidaciongasto.getCantidad()); initialValues.put("IDSIEMBRA",dordenliquidaciongasto.getIdsiembra()); initialValues.put("IDCAMPANA",dordenliquidaciongasto.getIdcampana()); initialValues.put("IDORDENPRODUCCION",dordenliquidaciongasto.getIdordenproduccion()); initialValues.put("IDLOTEPRODUCCION",dordenliquidaciongasto.getIdloteproduccion()); resultado = mDb.insert("DORDENLIQUIDACIONGASTO",null,initialValues)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } public Boolean update(Dordenliquidaciongasto dordenliquidaciongasto,String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ContentValues initialValues = new ContentValues(); initialValues.put("IDEMPRESA",dordenliquidaciongasto.getIdempresa()) ; initialValues.put("IDORDEN",dordenliquidaciongasto.getIdorden()) ; initialValues.put("ITEM",dordenliquidaciongasto.getItem()) ; initialValues.put("GLOSA",dordenliquidaciongasto.getGlosa()) ; initialValues.put("IDCONCEPTO",dordenliquidaciongasto.getIdconcepto()) ; initialValues.put("IDCUENTA",dordenliquidaciongasto.getIdcuenta()) ; initialValues.put("IDCCOSTO",dordenliquidaciongasto.getIdccosto()) ; initialValues.put("IDTIPOMOV",dordenliquidaciongasto.getIdtipomov()) ; initialValues.put("IDCLIEPROV",dordenliquidaciongasto.getIdclieprov()) ; initialValues.put("IDDOCUMENTO",dordenliquidaciongasto.getIddocumento()) ; initialValues.put("SERIE",dordenliquidaciongasto.getSerie()) ; initialValues.put("NUMERO",dordenliquidaciongasto.getNumero()) ; initialValues.put("FECHA",dateFormat.format(dordenliquidaciongasto.getFecha() ) ) ; initialValues.put("IDDESTINO",dordenliquidaciongasto.getIddestino()) ; initialValues.put("IDMONEDA",dordenliquidaciongasto.getIdmoneda()) ; initialValues.put("TCMONEDA",dordenliquidaciongasto.getTcmoneda()) ; initialValues.put("TCAMBIO",dordenliquidaciongasto.getTcambio()) ; initialValues.put("IDREGIMEN",dordenliquidaciongasto.getIdregimen()) ; initialValues.put("AFECTO", String.valueOf(dordenliquidaciongasto.getAfecto())) ; initialValues.put("INAFECTO", String.valueOf(dordenliquidaciongasto.getInafecto())) ; initialValues.put("PIMPUESTO",dordenliquidaciongasto.getPimpuesto()) ; initialValues.put("IMPUESTO", String.valueOf(dordenliquidaciongasto.getImpuesto())) ; initialValues.put("IMPORTE", String.valueOf(dordenliquidaciongasto.getImporte())) ; initialValues.put("OTROS",dordenliquidaciongasto.getOtros()) ; initialValues.put("IDCONSUMIDOR",dordenliquidaciongasto.getIdconsumidor()) ; initialValues.put("NUMERO_RCOMPRAS",dordenliquidaciongasto.getNumero_rcompras()) ; initialValues.put("IDMEDIDA",dordenliquidaciongasto.getIdmedida()) ; initialValues.put("IDPRODUCTO",dordenliquidaciongasto.getIdproducto()) ; initialValues.put("ITEMALMACEN",dordenliquidaciongasto.getItemalmacen()) ; initialValues.put("PRODUCTO",dordenliquidaciongasto.getProducto()) ; initialValues.put("VENTANA",dordenliquidaciongasto.getVentana()) ; initialValues.put("CANTIDAD",dordenliquidaciongasto.getCantidad()) ; initialValues.put("IDSIEMBRA",dordenliquidaciongasto.getIdsiembra()) ; initialValues.put("IDCAMPANA",dordenliquidaciongasto.getIdcampana()) ; initialValues.put("IDORDENPRODUCCION",dordenliquidaciongasto.getIdordenproduccion()) ; initialValues.put("IDLOTEPRODUCCION",dordenliquidaciongasto.getIdloteproduccion()) ; resultado = mDb.update("DORDENLIQUIDACIONGASTO",initialValues,where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public Boolean delete(String where) { Boolean resultado = false; SQLiteDatabase mDb = SQLiteDatabase.openDatabase(DataBaseClass.PATH_DATABASE,null, SQLiteDatabase.NO_LOCALIZED_COLLATORS); try{ resultado = mDb.delete("DORDENLIQUIDACIONGASTO",where,null)>0; } catch (Exception e) { }finally { mDb.close(); } return resultado; } }
package com.worldchip.bbpawphonechat.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import com.easemob.chat.EMMessage; import com.worldchip.bbpawphonechat.R; public class ContextMenuActivity extends Activity{ private int mPosition; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); int type = getIntent().getIntExtra("type", -1); mPosition = getIntent().getIntExtra("position", -1); if(type == EMMessage.Type.TXT.ordinal()){ setContentView(R.layout.context_menu_for_text); }else if (type == EMMessage.Type.LOCATION.ordinal()) { setContentView(R.layout.context_menu_for_location); } else if (type == EMMessage.Type.IMAGE.ordinal()) { setContentView(R.layout.context_menu_for_image); } else if (type == EMMessage.Type.VOICE.ordinal()) { setContentView(R.layout.context_menu_for_voice); } else if (type == EMMessage.Type.VIDEO.ordinal()) { setContentView(R.layout.context_menu_for_video); } setFinishOnTouchOutside(true); } public void copy(View view){ setResult(PhoneChatActivity.RESULT_CODE_COPY, new Intent().putExtra("position", mPosition)); finish(); } public void delete(View view){ setResult(PhoneChatActivity.RESULT_CODE_DELETE, new Intent().putExtra("position", mPosition)); finish(); } /*public void forward(View view){ setResult(PhoneChatActivity.RESULT_CODE_FORWARD, new Intent().putExtra("position", mPosition)); finish(); }*/ /* public void open(View v){ setResult(PhoneChatActivity.RESULT_CODE_OPEN, new Intent().putExtra("position", mPosition)); finish(); } public void download(View v){ setResult(PhoneChatActivity.RESULT_CODE_DWONLOAD, new Intent().putExtra("position", mPosition)); finish(); } public void toCloud(View v){ setResult(PhoneChatActivity.RESULT_CODE_TO_CLOUD, new Intent().putExtra("position", mPosition)); finish(); }*/ }
/* * 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 proyecto.dsoo; /** * * @author ASUS */ import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author ASUS */ public class Pacientes { private String Id; private String Nombre; private String Apellidos; private String Edad; public Pacientes() { } public Pacientes(String Id, String Nombre, String Apellidos, String Edad){ this.Id = Id; this.Nombre = Nombre; this.Apellidos = Apellidos; this.Edad = Edad; } public String getId() { return Id; } public String getNombre() { return Nombre; } public String getApellidos() { return Apellidos; } public String getEdad() { return Edad; } public void setId(String Id) { this.Id = Id; } public void setNombre(String Nombre) { this.Nombre = Nombre; } public void setApellidos(String Apellidos) { this.Apellidos = Apellidos; } public void setEdad(String Edad) { this.Edad = Edad; } public boolean agregar(){ Connection con = null; Statement stmt = null; PreparedStatement pstmt = null; CallableStatement cstmt = null; boolean resultado = false; try{ con = Connect.getConexion(); String sql = "INSERT INTO paciente(Nombre, Apellidos, Edad) values('" + Nombre +"','"+Apellidos +"','"+Edad+ "')"; stmt = con.createStatement(); int res = stmt.executeUpdate(sql); if(res == 1){ resultado = true; } con.close(); }catch(SQLException ex) { Logger.getLogger(ProyectoDSOO.class.getName()).log(Level.SEVERE, null, ex); } return resultado; } public boolean eliminar(){ boolean resultado = false; Connection con = null; con = Connect.getConexion(); PreparedStatement pstm ; try { pstm = con.prepareStatement("delete FROM paciente where ID = " + Id ); int res = pstm.executeUpdate(); if(res == 1) resultado = true; con.close(); } catch (SQLException ex) { //setMensaje("Error:" +ex.getMessage()); System.out.println("ERROR" + ex.getMessage()); } return resultado; } public boolean modificar(){ Connection con = null; Statement stmt = null; PreparedStatement pstmt = null; CallableStatement cstmt = null; boolean resultado = false; try{ con = Connect.getConexion(); String sql = "UPDATE paciente SET Nombre = '" + Nombre + "', Apellidos = '" + Apellidos + "', Edad = '" + Edad + "'Where ID = " + Id; stmt = con.createStatement(); int res = stmt.executeUpdate(sql); if(res == 1){ resultado = true; } con.close(); }catch(SQLException ex) { Logger.getLogger(ProyectoDSOO.class.getName()).log(Level.SEVERE, null, ex); } return resultado; } public ArrayList<Pacientes> getPacientes(){ ArrayList<Pacientes> grupo = new ArrayList<Pacientes>(); Pacientes Pac; Connection con = null; Statement stmt = null; ResultSet rs = null; try { con = Connect.getConexion(); stmt = con.createStatement(); rs = stmt.executeQuery("select * from paciente"); while(rs.next()){ String Tempid = rs.getString("Id"); String TempNom = rs.getString("Nombre"); String Tempapell = rs.getString("Apellido"); String TempEd = rs.getString("Edad"); Pac = new Pacientes(Tempid, TempNom, Tempapell, TempEd); grupo.add(Pac); } con.close(); } catch (SQLException ex) { Logger.getLogger(ProyectoDSOO.class.getName()).log(Level.SEVERE, null, ex); } return grupo; } public Vector<String> RowDent(Pacientes temp){ Vector<String> Pac = new Vector<String>(); Pac.add(temp.getId()); Pac.add(temp.getNombre()); Pac.add(temp.getApellidos()); Pac.add(temp.getEdad()); return Pac; } }
import gov.nih.mipav.model.file.*; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.plugins.*; // needed to load PlugInAlgorithm / PlugInView / PlugInFile interface import gov.nih.mipav.view.*; import java.io.IOException; /** * Converts cheshire overlays in the given file to VOIs. * * @see PlugInAlgorithm */ // This is a Generic type of PlugIn which does not require a source image to run. public class PlugInAVISkip implements PlugInGeneric { //~ Static fields/initializers ------------------------------------------------------------------------------------- //~ Instance fields ------------------------------------------------------------------------------------------------ /** Dialog for this plugin. */ private PlugInDialogAVISkip aviSkipDialog; private String inputFileName; private String directory; private String outputFileName; private float captureTime; private float skipTime; private FileAvi aviFile; int framesToCapture; int framesToSkip; boolean AVIF_HASINDEX; boolean AVIF_MUSTUSEINDEX; //~ Methods -------------------------------------------------------------------------------------------------------- /** * Defines body of run method, which was declared in the interface. Run method creates dialog which obtains * directory, input file name, output file name, capture time in seconds, and skip time in seconds. * * @see ViewUserInterface * @see ModelImage * @see ViewJFrameImage */ public void run() { aviSkipDialog = new PlugInDialogAVISkip(false, this); } /** * Runs the plugin. */ public void runPlugin() { if (aviSkipDialog.isSuccessfulExit()) { directory = aviSkipDialog.getDirectory(); Preferences.debug("directory = " + directory + "\n"); inputFileName = aviSkipDialog.getInputFileName(); Preferences.debug("input fileName = " + inputFileName + "\n"); outputFileName = aviSkipDialog.getOutputFileName(); Preferences.debug("output fileName = " + outputFileName + "\n"); captureTime = aviSkipDialog.getCaptureTime(); Preferences.debug("capture time = " + captureTime + "\n"); skipTime = aviSkipDialog.getSkipTime(); Preferences.debug("skip time = " + skipTime + "\n"); try { aviFile = new FileAvi(inputFileName, directory); } catch(IOException e) { MipavUtil.displayError("IOException on aviFile = new FileAvi(inputFileName, directory"); return; } aviFile.setOutputFileName(outputFileName); aviFile.setCaptureTime(captureTime); aviFile.setSkipTime(skipTime); try { aviFile.readWriteImage(); } catch (IOException e) { MipavUtil.displayError("IOException on aviFile.readWriteImage()"); return; } Preferences.debug("Completed aviFile.readWriteImage()\n"); } else { // Do nothing since individual error is already displayed. } return; } }
package repository.lecture; import org.apache.ibatis.session.SqlSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository public class LectureDeleteRepository { String namespace = "lectureMapper"; @Autowired private SqlSession sqlSession; public void reposit(Long num) { String statement = namespace + ".deleteLec"; sqlSession.delete(statement, num); } } //
package com.najasoftware.fdv.service; import android.content.Context; import android.util.Log; import com.najasoftware.fdv.model.CategoriaProduto; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.List; import livroandroid.lib.utils.FileUtils; /** * Created by Lemoel Marques - NajaSoftware on 02/05/2016. * lemoel@gmail.com */ public class CategoriaProdutoService { private static final boolean LOG_ON = false; private static final String TAG = "CategoriaService"; public static List<CategoriaProduto> getCategorias(Context context) throws IOException { try { String fileName = String.format("categorias_fdv.json"); Log.d(TAG,"Abrindo arquivo: " + fileName); //Lê o arquivo da memoria interna String json = FileUtils.readFile(context,fileName,"UTF-8"); if(json == null) { Log.d(TAG,"Arquivo " + fileName + " Não encontrado"); return null; } List<CategoriaProduto> categorias = parserJson(context,json); return categorias; } catch (Exception e) { Log.e(TAG, "Erro ao ler os produtos: " + e.getMessage(),e); return null; } } private static List<CategoriaProduto> parserJson(Context context, String json) throws IOException { List<CategoriaProduto> categorias = new ArrayList<CategoriaProduto>(); try { JSONObject root = new JSONObject(json); JSONObject obj = root.getJSONObject("categorias"); JSONArray jsonCategorias = obj.getJSONArray("categoria"); for(int i = 0; i< jsonCategorias.length(); i++) { JSONObject jsonCategoria = jsonCategorias.getJSONObject(i); CategoriaProduto ct = new CategoriaProduto(); //Lê informações de cada produto ct.setId(jsonCategoria.optLong("id")); ct.setNome(jsonCategoria.optString("nome")); ct.setUrlFoto(jsonCategoria.optString("url_foto")); if (LOG_ON) { Log.d(TAG, "Categoria " + ct.getNome()); } categorias.add(ct); } if (LOG_ON) { Log.d(TAG,categorias.size() + " encontrados. "); } } catch (JSONException e) { throw new IOException(e.getMessage(),e); } return categorias; } }
package arrays; // Create a program using arrays that sorts a list of integers in descending order. // Descending order is highest value to lowest. // In other words if the array had the values in it 106, 26, 81, 5, 15 your program // should // ultimately have an array with 106,81,26, 15, 5 in it. // Set up the program so that the numbers to sort are read in from the keyboard. // Implement the following methods - getIntegers, printArray, and sortIntegers // getIntegers returns an array of entered integers from keyboard // printArray prints out the contents of the array // and sortIntegers should sort the array and return a new array containing the sorted numbers // you will have to figure out how to copy the array elements from the passed array into a new // array and sort them and return the new sorted array. import java.util.Arrays; import java.util.Scanner; public class ReserveSorting { static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int[] intArray = getIntgers(5); printArray(intArray); System.out.println("The sorted Array is : "+Arrays.toString(sortIntegers(intArray))); //Using bubble sort System.out.println("The sorted Array is : "+Arrays.toString(sortIntegersV1(intArray))); } @Deprecated private static int[] sortIntegers(int[] intArray) { int[] sortedArray = Arrays.copyOf(intArray,intArray.length); int temp =0; for(int j=0;j<sortedArray.length;j++){ System.out.println("Count = "+j); for(int i=0;i<(sortedArray.length)-1;i++){ if(sortedArray[i]<sortedArray[i+1]){ temp = sortedArray[i]; sortedArray[i] = sortedArray[i+1]; sortedArray[i+1] = temp; } } } return sortedArray; } public static int[] sortIntegersV1(int[] intArray){ // Implementing the sorting using bubble sort // Here you'll have an outer loop which keeps the tab of if the // iteration went successfully without swapping. In other words // The while loop initiates one swapping per iteration only if the // previous iteration happened without a swap. Hence, have a flag // called isSorted which checks if the previous iteration went without // swapping. // Time complexity is O(n^2) int[] sortedArray = Arrays.copyOf(intArray,intArray.length); int temp = 0; boolean isSorted = false; int counter =0; while(!isSorted){ //Set the initial value of isSorted to true so that we assume that this // iteration is going to execute without swapping isSorted = true; counter++; for(int i=0; i<sortedArray.length-1 /*-1 due to last element check is not required*/; i++){ //Checking if the values of the adjacent elements are sorted properly if(sortedArray[i]<sortedArray[i+1]){ //Initiating a swap temp=sortedArray[i]; sortedArray[i] = sortedArray[i+1]; sortedArray[i+1] = temp; //++++Very IMPORTANT++++++ // Set the flag "isSorted" to false indicating that a swap has occured. isSorted = false; } } } System.out.println("Counter = "+counter); return sortedArray; } private static void printArray(int[] intArray) { if(intArray.length==0){ System.out.println("Nothing to print...."); }else{ for(int i=0;i<intArray.length;i++){ System.out.println("Element in index "+i+" has a value of " +intArray[i]); } } } private static int[] getIntgers(int size) { System.out.println("Enter "+size+ " integer values \r"); int[] intArray = new int[size]; for(int i=0; i<size;i++){ intArray[i] = scanner.nextInt(); scanner.nextLine(); } return intArray; } }
package com.joalib.fault.action; import java.util.Enumeration; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.joalib.DTO.ActionForward; import com.joalib.DTO.FaultDTO; import com.joalib.fault.svc.FaultWriteService; import com.oreilly.servlet.MultipartRequest; import com.oreilly.servlet.multipart.DefaultFileRenamePolicy; public class FaultWriteAction implements Action { @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward=null; ServletContext context = request.getServletContext(); //���� �������� servletContext�� �޾ƿ���, String uploadPath = request.getRealPath("faultImage"); int size = 10*1024*1024; //�뷮 ��û�� ��뷮�� ������ źź�ؾ��Ѵ�. 10*1024*1024 : 10�ް� String filename=""; String origfilename=""; String fault_title=""; String fault_text=""; String member_id=""; try{ MultipartRequest multi = new MultipartRequest(request,uploadPath,size,"UTF-8",new DefaultFileRenamePolicy()); Enumeration files=multi.getFileNames(); //file�� �̸��� �����ðž�. //������ �޾ƿ��� fault_title = multi.getParameter("fault_title"); fault_text = multi.getParameter("fault_text"); member_id = multi.getParameter("member_id"); String file1 =(String)files.nextElement(); filename=multi.getFilesystemName(file1); //�̰��� DB�� �� ���� �̸� origfilename= multi.getOriginalFileName(file1); }catch(Exception e){ e.printStackTrace(); } //System.out.println("fault_title: "+fault_title+"/ fault_text: "+fault_text+"/ member_id: "+member_id+"/ filename: "+filename); //DTO ���� FaultDTO dto = new FaultDTO(); dto.setFault_title(fault_title); dto.setFault_text(fault_text); dto.setMember_id(member_id); dto.setFault_attach(filename); System.out.println("Action: "+uploadPath+filename); FaultWriteService svc = new FaultWriteService(); if(svc.faultWrite(dto)) { forward = new ActionForward(); forward.setRedirect(true); forward.setPath("boardPointCharge.po"); } return forward; } }
package io.flyingmongoose.brave.activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import io.flyingmongoose.brave.R; public class ActivHistoryMap extends AppCompatActivity implements View.OnClickListener { private MapView mvHistoryMap; private String name; private String panicId; private String panicDate; private String cellNumber; private boolean locationAvailable; private Double locationLat; private Double locationLon; private Button btnReportUser; private final String TAG = "ActivHistoryMap"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history_map); //Hide status notification bar getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); mvHistoryMap = (MapView) findViewById(R.id.mvHistoryMap); mvHistoryMap.onCreate(savedInstanceState); Intent receivedIntent = getIntent(); name = receivedIntent.getStringExtra("name"); panicId = receivedIntent.getStringExtra("panicId"); panicDate = receivedIntent.getStringExtra("panicDate"); cellNumber = receivedIntent.getStringExtra("cellNumber"); locationAvailable = receivedIntent.getBooleanExtra("locationAvailable", false); if(locationAvailable) { locationLat = receivedIntent.getDoubleExtra("locationLat", 0); locationLon = receivedIntent.getDoubleExtra("locationLon", 0); } else { Toast.makeText(this, "Unfortunately a location was never made available for this panic", Toast.LENGTH_LONG).show(); } //Setup Map mvHistoryMap.onResume(); try { MapsInitializer.initialize(this.getApplicationContext()); } catch(Exception e) { e.printStackTrace(); } mvHistoryMap.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { if(locationAvailable) { googleMap.addMarker(new MarkerOptions().position(new LatLng(locationLat, locationLon))); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(locationLat, locationLon), 12f)); } } }); TextView txtvName = (TextView) findViewById(R.id.txtvHistoryMapName); txtvName.setText(name); txtvName.setSelected(true); TextView txtvDate = (TextView) findViewById(R.id.txtvHistoryMapDate); txtvDate.setText(panicDate); txtvDate.setSelected(true); TextView txtvCellNumber = (TextView) findViewById(R.id.txtvHistoryMapNumber); txtvCellNumber.setText(cellNumber); txtvCellNumber.setSelected(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { //Add report button if panic user's name differs form logged in user if(!name.equalsIgnoreCase(ActivHome.currentUser.getString("name"))) { btnReportUser = new Button(this); btnReportUser.setText("Report"); btnReportUser.setTextColor(getResources().getColor(R.color.White)); btnReportUser.setBackground(getResources().getDrawable(R.drawable.selector_btn_report_user)); btnReportUser.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.report_user), null, null, null); btnReportUser.setOnClickListener(this); menu.add(Menu.NONE, 0, Menu.NONE, "Report").setActionView(btnReportUser).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); //Add report button to action bar } return true; } @Override public void onClick(View v) { if(v == btnReportUser) { //Report user Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "support@panic-sec.org", null)); intent.putExtra(Intent.EXTRA_SUBJECT, "Report User"); intent.putExtra(Intent.EXTRA_TEXT, "User being reported: \nPanic ID: " + panicId + "\nPanic Date: " + panicDate + "\nUser's Name: " + name + "\nUser's Number: " + cellNumber + "\n\nYour reason for reporting this user:\n\n"); startActivity(Intent.createChooser(intent, "Report User")); } } @Override protected void onRestart() { super.onRestart(); mvHistoryMap.onResume(); } @Override protected void onPause() { super.onPause(); mvHistoryMap.onPause(); } @Override protected void onDestroy() { super.onDestroy(); mvHistoryMap.onDestroy(); } @Override public void onLowMemory() { super.onLowMemory(); mvHistoryMap.onLowMemory(); } }
package assignment4; import java.util.*; /** * Social Network consists of methods that filter users matching a * condition. * * DO NOT change the method signatures and specifications of these methods, but * you should implement their method bodies, and you may add new public or * private methods or classes if you like. */ public class SocialNetwork { /** * Get K most followed Users. * * @param tweets * list of tweets with distinct ids, not modified by this method. * @param k * integer of most popular followers to return * @return the set of usernames who are most mentioned in the text of the tweets. * A username-mention is "@" followed by a Twitter username (as * defined by Tweet.getName()'s spec). * The username-mention cannot be immediately preceded or followed by any * character valid in a Twitter username. * For this reason, an email address like ethomaz@utexas.edu does NOT * contain a mention of the username. * Twitter usernames are case-insensitive, and the returned set may * include a username at most once. */ public static List<String> findKMostFollower(List<Tweets> tweets, int k) { List<String> mostFollowers = new ArrayList<>(); List<User> map = createMap(tweets); for(int i = 0; i < k; i++){ User user = findMostFollowers(map); if(user == null){ break; } mostFollowers.add(user.getUsername()); } return mostFollowers; } //Create a map with all followers set private static List<User> createMap(List<Tweets> tweets) { List<User> users = new ArrayList<>(); User tweeter; for(Tweets tweet : tweets){ //verify id try{ Filter.validId(tweet.getId()); }catch (Exception e){ continue; } //Attempt to find the user try { tweeter = findUser(users, Filter.validName(tweet.getName())); }catch(Exception e){ continue; } if(!users.contains(tweeter)) { users.add(tweeter); } Set<String> mentions; //Find the mentions in a tweet try { mentions = findUsernames(tweet); } catch (Exception e) { //null string continue; } for(String mention : mentions){ //Don't add if tweeting at themselves if(!mention.toLowerCase().equals(tweeter.username.toLowerCase())) { User mentioned = findUser(users, mention); if(!users.contains(mentioned)) { users.add(mentioned); } mentioned.addFollower(tweeter); } } } return users; } //Find max # of followers in the set of users. Once found return the user with that # of followers and remove it from the set public static User findMostFollowers(List<User> users){ Iterator<User> it = users.iterator(); int max = -1; User temp = null; while(it.hasNext()){ User user = it.next(); if(user.getNumFollowers() > max){ temp = user; max = user.getNumFollowers(); } } users.remove(temp); return temp; } //Determine if a user exists with this username. If yes, return a reference, if not, create it. private static User findUser(List<User> users, String username){ username = username.toLowerCase(); for(User user : users){ if(user.getUsername().equals(username)){ return user; } } return new User(username); } /** * Find all cliques in the social network. * * @param tweets * list of tweets with distinct ids, not modified by this method. * * @return list of set of all cliques in the graph */ public List<Set<String>> findCliques(List<Tweets> tweets) { List<Set<String>> result = new ArrayList<Set<String>>(); Set<User> graph = createGraph(tweets); Set<Set<User>> cliques = new HashSet<>(); //default clique is one member (each user) for(User user : graph){ Set<User> clique = new HashSet<>(); clique.add(user); cliques.add(clique); } //If user can be added, keep clique that doesn't include, and add clique that does include List<Set<User>> tempCliques = new ArrayList<Set<User>>(cliques); for(User user : graph){ ListIterator<Set<User>> it = tempCliques.listIterator(); while(it.hasNext()){ //placeholder for members in clique List<User> tempList = new ArrayList<>(it.next()); //placeholder for placeholder List<User> trueTempList = new ArrayList<>(tempList); if(isMutualFriends(trueTempList, user)) { //Create a new clique that includes the new member Set<User> temp = new HashSet<>(tempList); temp.add(user); it.add(temp); } } } cliques.addAll(tempCliques); cleanCliques(cliques); for(Set<User> clique : cliques){ Set<String> usernames = new HashSet<>(); for(User member : clique){ usernames.add(member.getUsername()); } result.add(usernames); } return result; } //Removes subset cliques and equivalent graphs, and single person cliques private static void cleanCliques(Set<Set<User>> cliques){ Iterator<Set<User>> it = cliques.iterator(); while(it.hasNext()){ Set<User> testPoint = it.next(); //If only one member in clique, delete it if(testPoint.size() <= 1){ it.remove(); continue; } //if it is a subset delete it, don't delete if testing against same clique for(Set<User> clique : cliques){ if(clique.containsAll(testPoint) && (clique != testPoint)){ it.remove(); break; } } } } //Determines if user is friends with all members of a clique private static boolean isMutualFriends(List<User> clique, User user){ if(clique.size() == 0){ return true; } if(findRealFriends(clique.get(0)).contains(user)){ clique.remove(0); return isMutualFriends(clique, user); } else { return false; } } //Returns all "real" friends of a user private static Set<User> findRealFriends(User user){ Set<User> realFriends = new HashSet<>(); for(User friend : user.getFriends()){ if(user.areFriends(friend)){ realFriends.add(friend); } } return realFriends; } //Create a graph with all friends mapped private static Set<User> createGraph(List<Tweets> tweets) { Set<User> users = new HashSet<>(); User tweeter; for(Tweets tweet : tweets){ //verify id try{ Filter.validId(tweet.getId()); }catch (Exception e){ continue; } //Attempt to find the user try { tweeter = findUser(users, Filter.validName(tweet.getName())); }catch(Exception e){ continue; } users.add(tweeter); Set<String> mentions; //Find the mentions in a tweet try { mentions = findUsernames(tweet); } catch (Exception e) { //null string continue; } for(String mention : mentions){ //Don't add if tweeting at themselves if(!mention.toLowerCase().equals(tweeter.getUsername().toLowerCase())) { User mentioned = findUser(users, mention); users.add(mentioned); tweeter.addFriend(mentioned); } } } return users; } //Find all mentions in a tweet private static Set<String> findUsernames(Tweets tweet) throws Exception { Set<String> usernames = new HashSet<>(); String[] text; //Split text by spaces try { text = Filter.validText(tweet.getText()).split(" "); }catch(NullPointerException n){ throw new Exception("illegal text"); } for(String phrase : text){ if(phrase.contains("@")){ try{ usernames.add(validUsername(phrase)); } catch (Exception e) { continue; } } } return usernames; } //Determine if a username is valid private static String validUsername(String username) throws Exception{ char c = username.charAt(0); if(c == '@'){ //test the rest of the handle try { return Filter.validName(username.substring(1, username.length())); }catch (Exception e){ throw new Exception("illegal username"); } } else { //should never get here throw new Exception("illegal username"); } } //Determine if a user exists with this username. If yes, return a reference, if not, create it. private static User findUser(Set<User> users, String username){ username = username.toLowerCase(); for(User user : users){ if(user.getUsername().equals(username)){ return user; } } return new User(username); } static class User{ private String username; private Set<User> friends; private Set<User> followers; User(String name){ username = name.toLowerCase(); friends = new HashSet<>(); followers = new HashSet<>(); } //Determine if 2 individuals are friends public boolean areFriends(User person2){ return friends.contains(person2) && person2.getFriends().contains(this); } //Add a "supposed" friend public void addFriend(User person){ friends.add(person); } //sets and gets public void setFriends(Set<User> friends) { this.friends = friends; } public void setUsername(String username) { this.username = username; } public void setFollowers(Set<User> followers) { this.followers = followers; } public String getUsername() { return username; } public Set<User> getFriends() { return friends; } public Set<User> getFollowers() { return followers; } public int getNumFollowers() { return followers.size(); } public void addFollower(User tweeter) { followers.add(tweeter); } } }
class Test{ static{ System.out.println("1.静态代码块***************"); } public Test(){ System.out.println("2.构造方法####################"); } { System.out.println("3.代码块&&&&&&&&&&&&&&&&&"); } } public class May{ public static void main(String[] args){ new Test(); new Test(); new Test(); } }
package spacewar; import java.io.IOException; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.springframework.web.socket.TextMessage; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; public class SpacewarGame { public final static SpacewarGame INSTANCE = new SpacewarGame(); private final static int FPS = 30; private final static int MAXSALAS = 10; private final static int MAXLINECHAT = 15; private final static long TICK_DELAY = 1000 / FPS; public final static boolean DEBUG_MODE = true; public final static boolean VERBOSE_MODE = true; public final static int MAXTHREADS = 100; public final int MAXPUNTUACIONES = 10; ObjectMapper mapper = new ObjectMapper(); private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); // GLOBAL GAME ROOM public SalaObject[] salas = new SalaObject[MAXSALAS]; // necesitamos agilizar las lecturas y // las pocas escrituras estan protegidas con sinchronized, // para que estas no requieren copiar todo de nuevo // además, necesitamos controlar su tamaño maximo private Deque<String> chat = new ArrayDeque<String>();// necesitamos que esten ordenados por llegada y no usamos // blockindeque pues necesitamos controlar el tamaño private Set<String> nombres = ConcurrentHashMap.newKeySet(); private Map<String, Player> players = new ConcurrentHashMap<>(); private AtomicInteger numPlayers = new AtomicInteger(); private SpacewarGame() { } // gestion chat public synchronized void insertChat(String chatLine) { if (chat.size() >= MAXLINECHAT) { chat.pollFirst(); } chat.addLast(chatLine); } // Gestion salas public synchronized int createSala(int NJUGADORES, String MODOJUEGO, String NOMBRE, Player CREADOR) { int indiceSalaLibre = getSalaLibre(); if (indiceSalaLibre != -1) { if (MODOJUEGO.equals("Classic")) { salas[indiceSalaLibre] = new classicSala(NJUGADORES, MODOJUEGO, NOMBRE, CREADOR, indiceSalaLibre); } else if (MODOJUEGO.equals("Battle Royal")) { salas[indiceSalaLibre] = new royaleSala(NJUGADORES, MODOJUEGO, NOMBRE, CREADOR, indiceSalaLibre); } } return indiceSalaLibre; } public synchronized boolean joinSalaMatchmaking(Player player) { ObjectNode msg = mapper.createObjectNode(); for (SalaObject sala : salas) { if (sala != null && !sala.isInProgress()) { float media = sala.getMediaSala(); float pMedia = player.getMedia(); if (((0 <= media && media < 0.2f) && (0 <= pMedia && pMedia < 0.2f)) || ((0.2 <= media && media <= 0.4) && (0.2 <= pMedia && pMedia <= 0.4)) || ((0.4 < media && media <= 1) && (0.4 < pMedia && pMedia <= 1))) { try { msg.put("event", "MATCHMAKING SUCCESS"); msg.put("indiceSala", sala.getIndice()); player.getSession().sendMessage(new TextMessage(msg.toString())); } catch (IOException e) { } sala.joinSala(player); return true; } } } try { msg.put("event", "MATCHMAKING FAIL"); player.getSession().sendMessage(new TextMessage(msg.toString())); } catch (IOException e) { } return false; } private int getSalaLibre() {// Comprueba el primer indice de salas que esté libre for (int i = 0; i < salas.length; i++) { if (salas[i] == null) { return i; } } return -1; } public void removeSala(String NOMBRE) { for (int i = 0; i < salas.length; i++) { if (salas[i] != null && salas[i].getCreador().equals(NOMBRE)) { salas[i].drainPermitsOfSala(); for (Player player : salas[i].getPlayers()) { if (!player.getNombre().equals(salas[i].getCreador())) { try { ObjectNode msg = mapper.createObjectNode(); msg.put("event", "CANCEL SALA BY HOST"); msg.put("indiceSala", i); player.getSession().sendMessage(new TextMessage(msg.toString())); } catch (IOException e) { } } } salas[i] = null; } } } // gestion de nombres en el servidor public String addNombre(String nombre) { if (nombres.add(nombre)) { return nombre; } return ""; } public boolean removeNombre(String nombre) { return nombres.remove(nombre); } // gestion jugadores en salas y mensajes al cliente public void addPlayer(Player player) { players.put(player.getSession().getId(), player); int count = numPlayers.getAndIncrement(); if (count == 0) { this.startMenuLoop(); } } public Collection<Player> getPlayers() { return players.values(); } public void removePlayer(Player player) { players.remove(player.getSession().getId()); int count = this.numPlayers.decrementAndGet(); if (count == 0) { this.stopMenuLoop(); } } public void startMenuLoop() { scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleAtFixedRate(() -> tick(), TICK_DELAY, TICK_DELAY, TimeUnit.MILLISECONDS); } public void stopMenuLoop() { if (scheduler != null) { scheduler.shutdown(); } } private void broadcast(String message) { for (Player player : getPlayers()) { try { if (!player.getInMatch()) { player.getSession().sendMessage(new TextMessage(message.toString())); } } catch (Throwable ex) { System.err.println("Execption sending message to player " + player.getSession().getId()); ex.printStackTrace(System.err); removePlayer(player); } } } public void broadcastLostPlayer(String message) { for (Player player : getPlayers()) { try { player.getSession().sendMessage(new TextMessage(message.toString())); } catch (Throwable ex) { System.err.println("Execption sending message to player " + player.getSession().getId()); ex.printStackTrace(System.err); removePlayer(player); } } } private ObjectNode putSalaNull() { ObjectNode jsonSala = mapper.createObjectNode(); jsonSala.put("nPlayers", 0); jsonSala.put("nombre", ""); jsonSala.put("modoJuego", ""); jsonSala.put("inProgress", false); return jsonSala; } public void checkAndRemoveSalas() { for (int i = 0; i < salas.length; i++) { if (salas[i] != null && salas[i].getNumberPlayersWaiting() <= 0) { salas[i] = null; } } } public void tick() { ObjectNode json = mapper.createObjectNode(); ArrayNode arrayNodeSalas = mapper.createArrayNode(); ArrayNode arrayNodeChat = mapper.createArrayNode(); ArrayNode arrayNodePuntuaciones = mapper.createArrayNode(); for (SalaObject sala : salas) { if (sala != null) { if (sala.getNumberPlayersWaiting() > 0) { ObjectNode jsonSala = mapper.createObjectNode(); jsonSala.put("nPlayers", sala.getNumberPlayersWaiting()); jsonSala.put("nombre", sala.getNombreSala()); jsonSala.put("modoJuego", sala.getModoJuego()); jsonSala.put("inProgress", sala.isInProgress()); jsonSala.put("creador", sala.getCreador()); arrayNodeSalas.addPOJO(jsonSala); } else { arrayNodeSalas.addPOJO(putSalaNull()); } } else { arrayNodeSalas.addPOJO(putSalaNull()); } } checkAndRemoveSalas(); Iterator<String> chatI = chat.iterator(); for (int i = 0; i < MAXLINECHAT; i++) { if (chatI.hasNext()) { arrayNodeChat.add(chatI.next()); } else { arrayNodeChat.add(""); } } // Para mostrar las puntuaciones en el menu Player[] play = getBetterPlayers(); for(int i=0;i<MAXPUNTUACIONES;i++) { if(play[i]!=null) { ObjectNode jsonPuntuacion = mapper.createObjectNode(); jsonPuntuacion.put("pos",i); jsonPuntuacion.put("nombreJugador", play[i].getNombre()); jsonPuntuacion.put("media", play[i].getMedia()); arrayNodePuntuaciones.addPOJO(jsonPuntuacion); } } json.put("event", "MENU STATE UPDATE"); json.putPOJO("salas", arrayNodeSalas); json.putPOJO("chat", arrayNodeChat); json.putPOJO("puntuaciones", arrayNodePuntuaciones); this.broadcast(json.toString()); } public Player[] getBetterPlayers() { ArrayList<Player> play = new ArrayList<Player>(players.values()); Collections.sort(play, new Comparator<Player>() { @Override public int compare(Player p, Player p1) { return Float.compare(p1.getMedia(), p.getMedia()); } }); Player []mejores=new Player[MAXPUNTUACIONES]; for(int i=0;i<MAXPUNTUACIONES;i++) { if(play.size()>i) { mejores[i]=play.get(i); } } return mejores; } public void handleCollision() { } }
package com.sun.tools.xjc.generator.annotation.spec; import javax.xml.bind.annotation.XmlNsForm; import javax.xml.bind.annotation.XmlSchema; import com.sun.codemodel.JAnnotationWriter; public interface XmlSchemaWriter extends JAnnotationWriter<XmlSchema> { XmlSchemaWriter location(String value); XmlSchemaWriter namespace(String value); XmlNsWriter xmlns(); XmlSchemaWriter elementFormDefault(XmlNsForm value); XmlSchemaWriter attributeFormDefault(XmlNsForm value); }
/* * 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 modelDao.jpa; import dao.JpaDao; import model.Road; import modelDao.RoadDao; /** * * @author Team Foufou */ public class JpaRoadDao extends JpaDao<Road> implements RoadDao { private static JpaRoadDao instance; /** * Default Constructor */ public JpaRoadDao() { super(Road.class); } /** * * @return */ public static JpaRoadDao getInstance() { if (instance == null) { instance = new JpaRoadDao(); } return instance; } }
public class Algorithm1 extends Algorithm { private long l = 0L; public String getName() { return "1"; } public long getL() { return l; } public void f(long n) { l = n; } }
package com.in.Firstcompleteproject.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import com.in.Firstcompleteproject.dto.CreateDto; import com.in.Firstcompleteproject.dto.loginDto; import com.in.Firstcompleteproject.entity.Employee; import com.in.Firstcompleteproject.repository.EmployeeRepository; import com.in.Firstcompleteproject.response.ApiResponse; import com.in.Firstcompleteproject.service.EmployeeServiceImpl; @RunWith(MockitoJUnitRunner.Silent.class) public class EmployeeControllerTest { @Mock EmployeeServiceImpl employeeserviceimpl; @InjectMocks EmployeeController employeecontroller; CreateDto createdto; Employee employee; loginDto logindto ; @Before public void setup() { employee = new Employee(); employee.setEmail("tukari@gmail.com"); employee.setFirstName("ashish"); employee.setLastName("kumar"); employee.setPassword("Ashish@123"); employee.setPhoneNo(1234567891); employee.setId(6); createdto = new CreateDto(); createdto.setEmail("tukari@gmail.com"); createdto.setFirstName("ashish"); createdto.setLastName("kumar"); createdto.setPassword("Ashish@123"); createdto.setPhoneNo(1234567891); createdto.setId(6); logindto = new loginDto(); logindto.setEmail("tukari@gmail.com"); logindto.setPassword("Ashish@123"); } @Test public void creatRegistrationTest() { Mockito.when(employeeserviceimpl.creatRegistration(Mockito.any())).thenReturn(employee); ResponseEntity<String> res = employeecontroller.CreateRegistration(createdto); String s= res.toString(); assertNotNull(res); assertEquals("<200 OK OK,success registration,[]>", s); } @Test public void LoginTest() { Mockito.when(employeeserviceimpl.login(Mockito.any())).thenReturn(employee); ResponseEntity<String> res = employeecontroller.login(logindto); String s= res.toString(); assertNotNull(res); assertEquals("<200 OK OK,success login,[]>", s); } }
/** * */ package pl.edu.agh.cyberwej.business.integrationTests; import java.util.LinkedList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import pl.edu.agh.cyberwej.business.services.api.GroupMembershipService; import pl.edu.agh.cyberwej.business.services.api.GroupService; import pl.edu.agh.cyberwej.business.services.api.InvitationService; import pl.edu.agh.cyberwej.business.services.api.PaybackService; import pl.edu.agh.cyberwej.business.services.api.PaymentService; import pl.edu.agh.cyberwej.business.services.api.UserService; import pl.edu.agh.cyberwej.data.objects.Group; import pl.edu.agh.cyberwej.data.objects.Invitation; import pl.edu.agh.cyberwej.data.objects.User; /** * @author Pita * */ public abstract class BaseIntegrationTest { @Autowired private GroupService groupService; @Autowired private UserService userService; @Autowired private GroupMembershipService groupMembershipService; @Autowired private InvitationService invitationService; @Autowired private PaymentService paymentService; @Autowired private PaybackService paybackService; private int userNr = 3; protected final List<Integer> usersIds = new LinkedList<Integer>(); protected final List<String> usersLogins = new LinkedList<String>(); protected int groupId; protected String groupName; protected void createGroup(LinkedList<User> users) { Group group = TestObjectsFactory.getMockGroup(); getGroupService().saveGroupWithItsMembers(group, users, users.get(0)); groupId = group.getId(); groupName = group.getName(); } protected void createUsers() { User user = null; for (int i = 0; i < getUserNr(); i++) { user = TestObjectsFactory.getMockUser(); getUserService().saveUser(user); usersIds.add(user.getId()); usersLogins.add(user.getLogin()); } } protected LinkedList<User> retrieveUsers() { LinkedList<User> users = new LinkedList<User>(); for (Integer userId : usersIds) { users.add(getUserService().getUserById(userId)); } return users; } protected void acceptAllInvitations() { LinkedList<User> users = retrieveUsers(); // iterate over all users except owner of the group for (int i = 1; i < users.size(); i++) { User user = users.get(i); List<Invitation> inviationsForUser = getInvitationService().getInviationsForUser(user, true); Invitation invitation = inviationsForUser.get(0); getInvitationService().acceptInvitation(invitation, true); } } public PaymentService getPaymentService() { return paymentService; } public void setPaymentService(PaymentService paymentService) { this.paymentService = paymentService; } public GroupService getGroupService() { return groupService; } public void setGroupService(GroupService groupService) { this.groupService = groupService; } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public GroupMembershipService getGroupMembershipService() { return groupMembershipService; } public void setGroupMembershipService(GroupMembershipService groupMembershipService) { this.groupMembershipService = groupMembershipService; } public InvitationService getInvitationService() { return invitationService; } public void setInvitationService(InvitationService invitationService) { this.invitationService = invitationService; } public int getUserNr() { return userNr; } public void setUserNr(int userNr) { this.userNr = userNr; } public PaybackService getPaybackService() { return paybackService; } public void setPaybackService(PaybackService paybackService) { this.paybackService = paybackService; } }
package moe.tristan.easyfxml.model.beanmanagement; import static moe.tristan.easyfxml.TestUtils.isSpringSingleton; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import moe.tristan.easyfxml.EasyFxmlAutoConfiguration; @ContextConfiguration(classes = EasyFxmlAutoConfiguration.class) @RunWith(SpringRunner.class) public class ControllerManagerTest { @Autowired private ApplicationContext context; @Test public void testLinkage() { final ControllerManager manager = this.context.getBean(ControllerManager.class); assertThat(manager).isNotNull(); } @Test public void testSingleton() { assertThat(isSpringSingleton(this.context, ControllerManager.class)).isTrue(); } }
package com.android.juan.volleytester; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import android.widget.Toast; import com.android.juan.volleytester.Volley.GetVolleyRequest; import com.android.juan.volleytester.Volley.VolleyListener; import com.android.juan.volleytester.Volley.VolleyManager; import com.android.juan.volleytester.Volley.VolleyRequest; import org.json.JSONException; import org.json.JSONObject; public class MainActivity extends AppCompatActivity { private VolleyManager volleyManager; private ProgressDialog pd; private TextView tvBody, tvTitle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initialization(); fetchData(); } private void initialization() { tvBody = (TextView) findViewById(R.id.body); tvTitle = (TextView) findViewById(R.id.title); volleyManager = VolleyManager.getInstance(this.getApplicationContext()); pd = new ProgressDialog(this); pd.setMessage("Waiting"); pd.setCancelable(false); pd.setIndeterminate(true); } private void fetchData(){ // Put Link Here GetVolleyRequest request = new GetVolleyRequest("http://jsonplaceholder.typicode.com"); //Parameter Here request.putParams("posts", "1"); pd.setTitle("Waiting..."); pd.show(); request.setListener(new VolleyListener() { @Override public void onSuccess(VolleyRequest request, JSONObject response) { //Process Data Here int userID,ID; String title,body; try { title = response.getString("title"); tvTitle.setText(title); } catch (JSONException e) { e.printStackTrace(); } try { body = response.getString("body"); tvBody.setText(body); } catch (JSONException e) { e.printStackTrace(); } Log.d("",""); if (pd != null) { pd.dismiss(); } } @Override public void onError(VolleyRequest request, String errorMessage) { Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_SHORT).show(); if (pd != null) { pd.dismiss(); } } }); //Decide Protocol (GET or POST) volleyManager.createRequest(request, Protocol.GET); } }
package com.vepo.task.dao.impl; import java.util.List; import com.vepo.task.dao.TaskDAO; import com.vepo.task.entidade.TaskEntity; import com.vepo.utils.HibernateUtil; public class TaskDAOImpl implements TaskDAO{ private Boolean isTest = false; public TaskDAOImpl() { this.isTest = false; } public TaskDAOImpl(Boolean isTest) { this.isTest = isTest; } private void openSession() { if(!this.isTest) { HibernateUtil.openSession(); HibernateUtil.beginTransaction(); } } private void closeSession() { if(!isTest) { HibernateUtil.commitTransaction(); HibernateUtil.closeSession(); } } @Override public long save(TaskEntity enTask) { openSession(); long id = (Long) HibernateUtil.getSession().save(enTask); closeSession(); return id; } @Override public TaskEntity getTask(long id) { openSession(); TaskEntity taskEntity; try{ taskEntity = (TaskEntity) HibernateUtil.getSession().load(TaskEntity.class, id); } catch (org.hibernate.ObjectNotFoundException e) { closeSession(); return null; } closeSession(); return taskEntity; } @Override public List<TaskEntity> list() { openSession(); List lista = HibernateUtil.getSession().createQuery("from TaskEntity").list(); closeSession(); return lista; } @Override public TaskEntity remove(TaskEntity enTask) { openSession(); HibernateUtil.getSession().delete(enTask); closeSession(); return enTask; } @Override public TaskEntity update(TaskEntity enTask) { openSession(); HibernateUtil.getSession().update(enTask); closeSession(); return enTask; } }
package containers; public enum Alignment { TOP_LEFT, TOP_CENTER, TOP_RIGHT, LEFT, CENTER, RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT; @Override public String toString() { return super.toString(); } public static Alignment parseAlignment(String alignment){ Alignment A = CENTER; for(int i = 0; i < values().length; i++){ if(values()[i].toString().equals(alignment)){ A = values()[i]; break; } } return A; } public static int getX(float width, Alignment A){ int x = 0; int w = (int) width; switch(A){ case TOP_LEFT:x = -(w / 2);break; case TOP_CENTER:x = 0;break; case TOP_RIGHT:x = (w / 2);break; case LEFT:x = -(w / 2);break; case CENTER:x = 0;break; case RIGHT:x = (w / 2);break; case BOTTOM_LEFT:x = -(w / 2);break; case BOTTOM_CENTER:x = 0;break; case BOTTOM_RIGHT:x = (w / 2);break; } return x; } public static int getY(float height, Alignment A){ int y = 0; int h = (int) height; switch(A){ case TOP_LEFT:y = (h / 2);break; case TOP_CENTER:y = (h / 2);break; case TOP_RIGHT:y = (h / 2);break; case LEFT:y = 0;break; case CENTER:y = 0;break; case RIGHT:y = 0;break; case BOTTOM_LEFT:y = -(h / 2);break; case BOTTOM_CENTER:y = -(h / 2);break; case BOTTOM_RIGHT:y = -(h / 2);break; } return y; } }
package in.msmartpay.agent.dmr2Moneytrasfer; /** * Created by Smartkinda on 6/18/2017. */ public class BankDetailsModel { private String RecipientId; private String RecipientIdType; private String BeneName; private String Account; private String Ifsc; private String BankName; private String BeneMobile; private String IMPS; private String NEFT; private String Channel; //========================================================================== public String getRecipientId() { return RecipientId; } public void setRecipientId(String recipientId) { RecipientId = recipientId; } public String getRecipientIdType() { return RecipientIdType; } public void setRecipientIdType(String recipientIdType) { RecipientIdType = recipientIdType; } public String getBeneName() { return BeneName; } public void setBeneName(String beneName) { BeneName = beneName; } public String getAccount() { return Account; } public void setAccount(String account) { Account = account; } public String getIfsc() { return Ifsc; } public void setIfsc(String ifsc) { Ifsc = ifsc; } public String getBankName() { return BankName; } public void setBankName(String bankName) { BankName = bankName; } public String getBeneMobile() { return BeneMobile; } public void setBeneMobile(String beneMobile) { BeneMobile = beneMobile; } public String getIMPS() { return IMPS; } public void setIMPS(String IMPS) { this.IMPS = IMPS; } public String getNEFT() { return NEFT; } public void setNEFT(String NEFT) { this.NEFT = NEFT; } public String getChannel() { return Channel; } public void setChannel(String channel) { Channel = channel; } }
import java.io.*; import java.util.*; public class HuffmanCode { public static void main(String[] args) { HashMap<Character, String> result = new HashMap<Character, String>(); // 최종적으로 만들어지는 허프만코드들을 저장하는공간 HeapPriorityQueue tree = new HeapPriorityQueue(); // 허프만 코드를 구현하는데 필요한 우선순위 큐 선언 HashMap<Character, Integer> huf = new HashMap<Character, Integer>(); // 문자열과 가중치가 들어가 구성하는 해쉬맵 허프만트리를 구현하기위해 쓰이는 공간 String word = ""; try { BufferedReader in = new BufferedReader(new FileReader("data06_huffman.txt")); String line = in.readLine(); System.out.println("Input data : "); while (line != null) { StringTokenizer parser = new StringTokenizer(line, " ,:;-.?!"); while (parser.hasMoreTokens()) { word = parser.nextToken(); System.out.println(word); for (int i = 0; i < word.length(); i++) { char temp = word.charAt(i); if (huf.containsKey(temp)) huf.put(temp, huf.get(temp) + 1); else huf.put(temp, 1);// 해쉬맵을 이용해서 문자를 읽으면서 가중치를 더한다 최초이면 // 1로지정 이미 있는 거라면 +1을 해준다. }} line = in.readLine(); } in.close(); } catch (IOException e) {} for (char Cha : huf.keySet()) { // 현재 해쉬맵에 있는 문자를 한개씩 읽으면서 인쇄할방법을 찾다가 for문기능중 ':'가 있다는걸 알았다 Cha에 // huf.keyset값을 한개씩 넣으면서 진행하는 for문이다 Huffman temp = new Huffman(Cha, huf.get(Cha)); tree.add(temp);// 그와 동시에 그값들을 우선순위 큐에 추가한다. } Huffman code = new Huffman(' ', 0); code = code.maketree(tree, tree.size());// 우선순위 큐를 이용하여 허프만트리를 만든다. makecode(code, "", result);// 만들어진 허프만 트리를 이용하여 허프만코드를 만든다. System.out.println("\nOutPutData : "); for (char Cha : result.keySet()) { System.out.println(Cha + " : " + result.get(Cha)); } // 허프만 코드를 출력한다 } public static class HeapPriorityQueue { private static final int CAPACITY = 100; private Comparable[] a; private int size; public HeapPriorityQueue() { this(CAPACITY); } public HeapPriorityQueue(int capacity) { a = new Comparable[capacity]; } public void add(Object object) { if (!(object instanceof Comparable)) throw new IllegalArgumentException(); Comparable<?> x = (Comparable<?>) object; if (size == a.length) resize(); int i = size++; while (i > 0) { int j = i; i = (i - 1) / 2; if (a[i].compareTo(x) <= 0) { a[j] = x; return;//이번엔 Min Heap이다 CompareTo는 a[i]의 빈도수에서 x의 빈도수를 뺀것이다 그값이 0보다 작으면 minheap을 만족하기때문에 그대로 저장하고 리턴한다. } a[j] = a[i]; } a[i] = x; } public Object best() { if (size == 0) throw new java.util.NoSuchElementException(); return a[0]; }//최대값을 가져온다 public Object remove() { Object best = best(); a[0] = a[--size]; heapify(0, size); return best; }//Min값을 꺼내면서 다시 heapify한다 public int size() { return size; } private void heapify(int i, int n) { Comparable ai = a[i]; while (i < n / 2) { int j = 2 * i + 1; if (j + 1 < n && a[j + 1].compareTo(a[j]) <= 0) ++j; if (a[j].compareTo(ai) >= 0) break; a[i] = a[j]; i = j; } a[i] = ai; }//heapify부분이다 max와 부등호만 반대로하면된다 private void resize() { Comparable[] aa = new Comparable[2 * a.length]; System.arraycopy(a, 0, aa, 0, a.length); a = aa; } } public static class Huffman implements Comparable<Object> { char alphabet; int freq; Huffman lchild; Huffman rchild; public Huffman(char A, int B) { this.alphabet = A; this.freq = B; } public int compareTo(Object object) { if (!(object instanceof Huffman)) throw new IllegalArgumentException(); Huffman that = (Huffman) object; return this.freq - that.freq;// 두개의 가중치를 비교하는 compareTo함수이다 } public Huffman maketree(HeapPriorityQueue A, int n) {// 우선순위 큐인 tree를 이용하여서 // 최종적으로 사용할 허프만 트리를 // 구현하는 과정이다 for (int i = 1; i < n; i++) { Huffman temp = new Huffman(' ', 0); temp.lchild = (Huffman) A.remove(); temp.rchild = (Huffman) A.remove();// string값이 공백이고 왼쪽오른쪽 자식이 현재 // 우선순위큐에있는 최소가중치 두개를 뽑아서 만든다. temp.freq = temp.rchild.freq + temp.lchild.freq;// 해당 가중치는 자식두개를 // 더한값으로 한다 A.add(temp);// 그리고 그 트리도 다시 들어가서 허프만코드를 구성한다 } // 총 갯수가 n개라면 n-1번하면 모두 완성된다. return (Huffman) A.remove();// 그럼 최종적으로있는 루트에있는 트리가 허프만트리가 구현되었으니 리턴한다 } } public static void makecode(Huffman A, String S, HashMap<Character, String> B) { if (A == null) return; makecode(A.rchild, S + "1", B);// 오른쪽 자식으로 갈경우 '1'스트링을 더하고 계속 실행 makecode(A.lchild, S + "0", B);// 왼쪽 자식으로 갈경우 '0'스트링을 더하고 계속 실행 if (A.alphabet != ' ') {// 만약 허프만코드의 문자가 공백이아니라면 해당문자열에 도착하였음으로 그값을 해쉬맵인 // B에 저장한다 B.put(A.alphabet, S);// 순회하는 방식으로 코드를 구현하였다. } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.mnorrman.datastorageproject; /** * * @author Mikael */ public enum ServerState { NOTRUNNING (0x30), CONNECTING (0x31), CHKINTEG (0x32), CLEANING (0x33), SYNCHRONIZING (0x34), INDEXING (0x35), RUNNING (0x36), IDLE (0x37), CLOSING (0x3F); private final byte value; private ServerState(int byteValue) { this.value = (byte)byteValue; } public byte getValue(){ return value; } public static ServerState getState(byte value){ ServerState[] val = values(); for(int b = 0; b < val.length; b++){ if(val[b].getValue() == value) return val[b]; } return null; } }
package com.beacon.demo; public class BeaconModel { String beaconName; String distance; public String getBeaconName() { return beaconName; } public void setBeaconName(String beaconName) { this.beaconName = beaconName; } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } }
package C16_ProgramacionGenerica; public class ClassGenerica<T> { private T objeto; public ClassGenerica() { objeto = null; } public void setObjeto(T nuevoValor) { objeto = nuevoValor; } public T getObjeto() { return objeto; } }
package edu.gyaneshm.ebay_product_search; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.view.WindowManager; import edu.gyaneshm.ebay_product_search.adapters.ViewPageAdapter; import edu.gyaneshm.ebay_product_search.fragments.SearchFragment; import edu.gyaneshm.ebay_product_search.fragments.WishListFragment; public class MainActivity extends AppCompatActivity { private ViewPageAdapter mViewPageAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); setContentView(R.layout.main_activity_layout); getSupportActionBar().setElevation(0); ViewPager viewPager = findViewById(R.id.main_container); setUpViewPager(); viewPager.setAdapter(mViewPageAdapter); TabLayout tabLayout = findViewById(R.id.main_tabs); tabLayout.setupWithViewPager(viewPager); } private void setUpViewPager() { mViewPageAdapter = new ViewPageAdapter(this, getSupportFragmentManager()); mViewPageAdapter.addFragment(new SearchFragment(), R.string.tab_text_1); mViewPageAdapter.addFragment(new WishListFragment(), R.string.tab_text_2); } }
package com.example.mauricio.simpleDagger2WithMockito; import android.content.Intent; import io.paperdb.Paper; /** * Created by mauricio on 8/30/16. */ public class MyApplication extends android.app.Application { private static NossaCaixaDeFerramentas caixaDeFerramentas; @Override public void onCreate() { super.onCreate(); caixaDeFerramentas = DaggerNossaCaixaDeFerramentas.builder() .martelos(new Martelos()) .build(); Paper.init(this); startSevices(); } private void startSevices() { startService(new Intent(this, MainService.class)); } public static NossaCaixaDeFerramentas getCaixaDeFerramentas(){ return caixaDeFerramentas; } }
package com.biotag.vehiclenumberscanning.NFC; import android.nfc.Tag; import android.nfc.tech.MifareClassic; import android.util.Log; import org.apache.commons.lang3.StringUtils; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Map; /** * Created by Administrator on 2017-10-18. */ public class NFCTool { private final String TAG = this.getClass().getSimpleName(); private MifareClassic mc = null; private Map<String,byte[]> mKeyMap = null; private byte[] defalutKey = {(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF}; public CardInfo readTag(Tag tag){ boolean isMifareClassic = false; CardInfo cardInfo = new CardInfo(); for(String tech:tag.getTechList()){ if(tech.equals("android.nfc.tech.MifareClassic")){ isMifareClassic = true; } } if(tag == null){ android.util.Log.i(TAG, "writeToNFC: detectedTag == null"); return null; } if(!isMifareClassic){ android.util.Log.i(TAG, "readMifareClassic: detectTag not include MifareClassic"); } mc = MifareClassic.get(tag); if(mc == null){ android.util.Log.i(TAG, "writeToNFC: mc == null"); return null; } boolean result = false; try { mc.connect(); byte[] uid = mc.getTag().getId(); mKeyMap = M1Key.CalculateKey(uid); if(mKeyMap == null){ mc.close(); return null; } byte[] keyB = mKeyMap.get(Constants.KEYB); Log.i(TAG, "readTag: keyB = " + Utils.bytesToHexString(keyB)); cardInfo.setCardID(Utils.bytesToHexString(uid).toUpperCase()); result = readIDGroupID(cardInfo); if(!result){ mc.close(); return null; } result = readIDCard(cardInfo); if(!result){ mc.close(); return null; } result = readStaffNo(cardInfo); if(!result){ mc.close(); return null; } result = readStaffName(cardInfo); if(!result){ mc.close(); return null; } result = readCompanyName(cardInfo); if(!result){ mc.close(); return null; } result = readAreaNow(cardInfo); if(!result){ mc.close(); return null; } result = readLastModifiedTime(cardInfo); if(!result){ mc.close(); return null; } result = readAreaNo(cardInfo); if(!result){ mc.close(); return null; } result = readSeatNo(cardInfo); if(!result){ mc.close(); return null; } result = readImageUrl(cardInfo); if(!result){ mc.close(); return null; } cardInfo.printInfo(); return cardInfo; } catch (Exception e) { e.printStackTrace(); return null; }finally { try { mc.close(); } catch (Exception e) { e.printStackTrace(); } } } private boolean doAuthenticate(int sector){ if(mc == null){ Log.i(TAG, "doAuthenticate: mc == null"); } try { if(mc.isConnected()){ boolean auth = mc.authenticateSectorWithKeyB(sector,mKeyMap.get(Constants.KEYB)); if(auth){ return true; } auth = mc.authenticateSectorWithKeyB(sector,defalutKey); if(auth){ return true; } } return false; } catch (Exception e) { e.printStackTrace(); return false; } } private boolean readIDGroupID(CardInfo cardInfo){ int sector = Constants.IDGROUPIDCARDTYPE_SECTOR; ByteArrayInputStream bais = null; try { if(doAuthenticate(sector) ){ Log.i(TAG, "readIDGroupID: doAuthenticate success"); byte[] data = mc.readBlock(mc.sectorToBlock(sector)); String IDtmp = Utils.bytesToHexString(data).toUpperCase(); String ID = IDtmp.substring(0, 8) + "-" + IDtmp.substring(8, 12) + "-" + IDtmp.substring(12, 16) + "-" + IDtmp.substring(16, 20) + "-" + IDtmp.substring(20, 32); Log.i(TAG, "readIDGroupID: ID = " + ID); cardInfo.setID(ID.trim()); data = mc.readBlock(mc.sectorToBlock(sector) + 1); bais = new ByteArrayInputStream(data); byte[] GroupIDByte = new byte[4]; bais.read(GroupIDByte); int GroupID = (int)Utils.byteArrayToLong(GroupIDByte); cardInfo.setGroupID(GroupID); int CardType = bais.read(); cardInfo.setCardType(CardType); }else{ Log.i(TAG, "readIDGroupID: doAuthenticate fail"); return false; } }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readIDCard(CardInfo cardInfo){ int sector = Constants.IDCARD_SECTOR; ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector); int end = mc.sectorToBlock(sector) + 3; baos = new ByteArrayOutputStream(); for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } bais = new ByteArrayInputStream(baos.toByteArray()); int IdCard_type = bais.read(); cardInfo.setIdCard_type(IdCard_type); int IdCardByteLen = bais.read(); byte[] IdCardByte = new byte[IdCardByteLen]; bais.read(IdCardByte); String IdCard = new String(IdCardByte,"utf-8"); cardInfo.setIdCard(IdCard); }else{ Log.i(TAG, "readIDCard: doAuthenticate fail"); return false; } }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readStaffNo(CardInfo cardInfo) { int sector = Constants.STAFFNO_SECTOR; ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector); int end = mc.sectorToBlock(sector) + 3; baos = new ByteArrayOutputStream(); for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } bais = new ByteArrayInputStream(baos.toByteArray()); int StaffNoLen = bais.read(); byte[] StaffNoByte = new byte[StaffNoLen]; bais.read(StaffNoByte); String StaffNo = new String(StaffNoByte,"utf-8"); cardInfo.setStaffNo(StaffNo); }else{ Log.i(TAG, "readStaffNo: doAuthenticate fail"); return false; } }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readStaffName(CardInfo cardInfo){ ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { int sector = Constants.STAFFNAME_SECTORA; baos = new ByteArrayOutputStream(); for (;sector <= Constants.STAFFNAME_SECTORB;sector ++){ if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector); int end = mc.sectorToBlock(sector) + 3; for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } }else{ Log.i(TAG, "readStaffName: doAuthenticate fail"); return false; } } bais = new ByteArrayInputStream(baos.toByteArray()); int StaffNameByteLen = bais.read(); byte[] StaffNameByte = new byte[StaffNameByteLen]; bais.read(StaffNameByte); String StaffName = new String(StaffNameByte,"utf-8"); cardInfo.setStaffName(StaffName); }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readCompanyName(CardInfo cardInfo){ ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { int sector = Constants.COMPANYNAME_SECTORA; baos = new ByteArrayOutputStream(); for (;sector <= Constants.COMPANYNAME_SECTORB;sector ++){ if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector); int end = mc.sectorToBlock(sector) + 3; for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } }else{ Log.i(TAG, "readStaffName: doAuthenticate fail"); return false; } } bais = new ByteArrayInputStream(baos.toByteArray()); int CompanyNameByteLen = bais.read(); byte[] CompanyNameByte = new byte[CompanyNameByteLen]; bais.read(CompanyNameByte); String CompanyName = new String(CompanyNameByte,"utf-8"); cardInfo.setCompanyName(CompanyName); }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readAreaNow(CardInfo cardInfo) { int sector = Constants.AREANOW_SECTOR; ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector); int end = mc.sectorToBlock(sector) + 3; baos = new ByteArrayOutputStream(); for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } bais = new ByteArrayInputStream(baos.toByteArray()); int AreaNowByteLen = bais.read(); byte[] AreaNowByte = new byte[AreaNowByteLen]; bais.read(AreaNowByte); String AreaNow = new String(AreaNowByte,"utf-8"); cardInfo.setAreaNow(AreaNow.trim()); }else{ Log.i(TAG, "readStaffNo: doAuthenticate fail"); return false; } }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readLastModifiedTime(CardInfo cardInfo) { int sector = Constants.LASTMODIFIEDTIME_SECTOR; ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector); int end = mc.sectorToBlock(sector) + 3; baos = new ByteArrayOutputStream(); for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } bais = new ByteArrayInputStream(baos.toByteArray()); int LastModifiedTimeByteLen = bais.read(); byte[] LastModifiedTimeByte = new byte[LastModifiedTimeByteLen]; bais.read(LastModifiedTimeByte); String LastModifiedTime = new String(LastModifiedTimeByte,"utf-8"); cardInfo.setLastModifiedTime(LastModifiedTime); }else{ Log.i(TAG, "readStaffNo: doAuthenticate fail"); return false; } }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readAreaNo(CardInfo cardInfo) { int sector = Constants.AREANO_SECTOR; ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector); int end = mc.sectorToBlock(sector) + 1; baos = new ByteArrayOutputStream(); for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } bais = new ByteArrayInputStream(baos.toByteArray()); int AreaNoByteLen = bais.read(); byte[] AreaNoByte = new byte[AreaNoByteLen]; bais.read(AreaNoByte); String AreaNo = new String(AreaNoByte,"utf-8"); AreaNo = AreaNo.replaceAll("[^A-Z]",""); String[] strArray = AreaNo.split(""); AreaNo = StringUtils.join(strArray," "); Log.i(TAG, "readAreaNo: AreaNo = " + AreaNo); cardInfo.setAreaNo(AreaNo.trim()); }else{ Log.i(TAG, "readStaffNo: doAuthenticate fail"); return false; } }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readSeatNo(CardInfo cardInfo) { int sector = Constants.SEAT_NO; ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector) + 1; int end = mc.sectorToBlock(sector) + 3; baos = new ByteArrayOutputStream(); for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } bais = new ByteArrayInputStream(baos.toByteArray()); int SeatNoByteLen = bais.read(); byte[] SeatNoByte = new byte[SeatNoByteLen]; bais.read(SeatNoByte); String SeatNo = new String(SeatNoByte,"utf-8"); Log.i(TAG, "readAreaNo: SeatNo = " + SeatNo); cardInfo.setSeatNo(SeatNo.trim()); }else{ Log.i(TAG, "readStaffNo: doAuthenticate fail"); return false; } }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } private boolean readImageUrl(CardInfo cardInfo) { int sector = Constants.IMAGEURL_SECTOR; ByteArrayOutputStream baos = null; ByteArrayInputStream bais = null; try { if(doAuthenticate(sector) ){ int start = mc.sectorToBlock(sector); int end = mc.sectorToBlock(sector) + 3; baos = new ByteArrayOutputStream(); for (int i = start;i < end;i++) { byte[] data = mc.readBlock(i); baos.write(data); } bais = new ByteArrayInputStream(baos.toByteArray()); int ImageUrlByteLen = bais.read(); byte[] ImageUrlByte = new byte[ImageUrlByteLen]; bais.read(ImageUrlByte); String ImageUrl = new String(ImageUrlByte,"utf-8"); ImageUrl = ImageUrl.replaceAll(" ",""); Log.i(TAG, "readImageUrl: ImageUrl = " + ImageUrl); cardInfo.setImageUrl(ImageUrl); }else{ Log.i(TAG, "readImageUrl: doAuthenticate fail"); return false; } }catch (Exception e){ e.printStackTrace(); return false; }finally { try { if(bais != null)bais.close(); if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } return true; } public boolean WriteAreaNow(String AreaNow){ int sector = Constants.AREANOW_SECTOR; ByteArrayOutputStream baos = null; try{ mc.connect(); if(doAuthenticate(sector)){ baos = new ByteArrayOutputStream(); byte[] AreaNowByte = AreaNow.getBytes("utf-8"); baos.write(AreaNowByte.length); baos.write(AreaNowByte); int end = 16 - baos.size(); for(int i = 0; i < end;i ++){ baos.write(0); } mc.writeBlock(mc.sectorToBlock(sector),baos.toByteArray()); } mc.close(); return true; }catch(Exception e){ e.printStackTrace(); return false; }finally { try { if(baos != null)baos.close(); } catch (Exception e) { e.printStackTrace(); } } } }
import java.util.Scanner; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author mati */ public class Ej4 { public static void main (String args[]) { float num1, num2; Scanner intro = new Scanner(System.in); System.out.println("Introduzca un numero:"); num1 = intro.nextFloat (); System.out.println("Introduzca un segundo:"); num2 = intro.nextFloat (); if (num1<num2) System.out.println(+num1+" es menor que "+num2); else if (num2<num1) System.out.println(+num2+" es menor que "+num1); else System.out.println(+num2+" es igual que "+num1); } }
import java.util.Arrays; import java.util.Stack; import java.lang.reflect.*; /** * Created by vomin on 12/4/2017. */ public class Bu2 { public static byte[] binary(int a) { byte[] bin = new byte[8]; Arrays.fill(bin, (byte) 0x00); if (a != 0) { int N = Math.abs(a); int k = 0; while (N != 0) { int kk = N & 1; bin[k++] = Byte.parseByte(String.valueOf(N & 1)); N >>= 1; } for (int i = 0; i < 4; i++) { byte temp = bin[i]; bin[i] = bin[7 - i]; bin[7 - i] = temp; } } return bin; } public static void bu2(byte[] binArr) { boolean flag = false; for (int i = 7; i >= 0; i--) { if (flag) { binArr[i] = binArr[i] == 0 ? (byte) 1 : 0; } if (!flag && binArr[i] == 1) { flag = true; } } } public static int bu2To10(byte[] binArr) { boolean soAm = false; if (binArr[0] == (byte) 1) { bu2(binArr); soAm = true; } int n = 0; for (int i = 7; i >= 0; i--) { n += (int) Math.pow(2, 8 - i - 1) * binArr[i]; } return soAm ? -n : n; } static class Other{ private String str; public void setStr(String str){ this.str = str; } } public static void main(String[] Args) throws NoSuchFieldException, IllegalAccessException { Other t = new Other(); t.setStr("test private dsdsds"); Field field = Other.class.getDeclaredField("str"); field.setAccessible(true); System.out.print((String)field.get(t)); } }
package cn.swsk.rgyxtqapp; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.ScrollView; import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; import cn.swsk.rgyxtqapp.adapter.AnquanItemsAdapter2; import cn.swsk.rgyxtqapp.bean.TEquip; import cn.swsk.rgyxtqapp.bean.WareHouseT; import cn.swsk.rgyxtqapp.custom.InnerLV; import cn.swsk.rgyxtqapp.utils.CommonUtils; import cn.swsk.rgyxtqapp.utils.HttpUtils; import cn.swsk.rgyxtqapp.utils.JsonTools; import cn.swsk.rgyxtqapp.utils.PushUtils; /** * Created by apple on 16/3/3. */ public class AnquanChangeStatus extends AnquanguanliBaseActivity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener { public ListView lv; public AnquanItemsAdapter2 dapter; private Button save; private RadioGroup rg; private RadioButton rb02, rb03; private Observer dataObs = new Observer() { @Override public void update(Observable observable, Object data) { List<TEquip> list = (List<TEquip>) data; if (list.size() == 0) { rb02.setChecked(false); rb03.setChecked(false); return; } if (rb02.isChecked() || rb03.isChecked()) return; String estatus; if(list.get(0).getStatus()==0){ estatus=list.get(0).getEstatus(); }else estatus = list.get(0).getStatus()+""; if ("2".equals(estatus)) { rb02.setChecked(true); }else if("3".equals(estatus)){ rb03.setChecked(true); }else{ CommonUtils.toast("数据不符合变更条件 !",AnquanChangeStatus.this); } } }; @Override protected void onCreate(Bundle savedInstanceState) { resid=R.layout.anquan_changestatus; super.onCreate(savedInstanceState); save = (Button) findViewById(R.id.save); save.setOnClickListener(this); rg = (RadioGroup) findViewById(R.id.rg01); rg.setOnCheckedChangeListener(this); rb02 = (RadioButton) findViewById(R.id.rb02); rb03 = (RadioButton) findViewById(R.id.rb03); lv = (ListView)findViewById(R.id.lv); lv.setAdapter(dapter=new AnquanItemsAdapter2(this)); ((InnerLV) lv).setParentScrollView((ScrollView) findViewById(R.id.sc01)); lv.requestDisallowInterceptTouchEvent(true); chooseType(); loadData(); } public void chooseType(){ if(PushUtils.sWareHouse==null){ rb02.setChecked(true); rb03.setVisibility(View.GONE); }else{ rb03.setChecked(true); rg.getChildAt(1).setVisibility(View.GONE); rg.getChildAt(3).setVisibility(View.GONE); rb02.setVisibility(View.GONE); } } @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if (checkedId == R.id.rb04) { } else if (checkedId == R.id.rb06 || checkedId == R.id.rb07) { Intent intent = new Intent(); intent.setClass(this, MalfunctionActivity.class); intent.putExtra("title", checkedId == R.id.rb06 ? "故障销毁" : "故障归还"); startActivityForResult(intent, 2); } } @Override public void onClick(View v) { if (v == this.save) { final View rb = rg.findViewById(rg.getCheckedRadioButtonId()); int id = rg.getCheckedRadioButtonId(); if (rb == null) { CommonUtils.toast("请选择变更的状态", this); return; } if (id == R.id.rb04&&false) { } else if (id == R.id.rb06 || id == R.id.rb07) { } else { saveWithState("loginName=" + CommonUtils.UrlEnc (PushUtils.getUserName()) + "&type=" + rb.getTag()); } } } private void saveWithState(String path) { try { path = PushUtils.getServerIP(this) + "rgyx/AppManageSystem/StatusChange?" + path; String data = JsonTools.getJsonStr(dapter.infolist); if (data == null || data.length() < 8) { CommonUtils.toast("无提交的数据", this); return; } HashMap<String, String> map = new HashMap<>(); map.put("list", data); HashMap<String, File> files = new HashMap<>(); HttpUtils.commonRequest4(path, this, map, files, new HttpUtils.RequestCB() { @Override public void cb(Map<String, Object> map, String resp, int type) { if (type == 0) { loadData(); CommonUtils.toast("保存成功", AnquanChangeStatus.this); } } }); } catch (Exception e) { } } private void loadData(){ int type = 2; if(PushUtils.sWareHouse!=null){ type = 1; } String path = PushUtils.getServerIP(this)+"rgyx/AppManageSystem/StatusList?loginName="+ CommonUtils.UrlEnc (PushUtils.getUserName()) + "&type=" + type; HttpUtils.commonRequest2(path, this, new HttpUtils.RequestCB() { @Override public void cb(Map<String, Object> map, String resp, int type) { if(type==0){ List<WareHouseT> list = JsonTools.getWareHouseT(resp); dapter.setInfos(list); } } }); } @Override protected void onResume() { super.onResume(); // dapter.obsable.addObserver(dataObs); } @Override protected void onPause() { super.onPause(); // dapter.obsable.deleteObserver(dataObs); } }
package gromcode.main.lesson23; public class StreamValidator {//extends Validator { public StreamValidator(String name) { //super(name); } // @Override // public boolean validate() { // // //logic // // return true; // } }
package com.legaoyi.message.rest; import java.util.List; import java.util.Map; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.legaoyi.common.exception.BizProcessException; import com.legaoyi.common.util.Result; import com.legaoyi.message.service.MessageService; import com.legaoyi.persistence.jpa.service.GeneralService; import com.legaoyi.platform.model.Device; import com.legaoyi.platform.rest.BaseController; import com.legaoyi.platform.service.DeviceService; @RestController("messageController") @RequestMapping(produces = {"application/json"}) public class MessageController extends BaseController { @Autowired @Qualifier("messageService") private MessageService messageService; @Autowired @Qualifier("deviceService") private DeviceService deviceService; @Autowired @Qualifier("generalService") private GeneralService service; @RequestMapping(value = "/heartbeat/{clinetId}/{messageId}", method = RequestMethod.GET) public Result heartbeat(@PathVariable String clinetId, @PathVariable String messageId, @RequestHeader(name = "_enterpriseId") String enterpriseId) throws Exception { this.messageService.setHeartbeat(clinetId, messageId); return new Result(); } @RequestMapping(value = "/video/808/{deviceId}", method = RequestMethod.POST) public Result startJtt808Video(@PathVariable String deviceId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestParam String clinetId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.start808Video(enterpriseId, deviceId, clinetId, messageBody, gatewayId)); } throw new BizProcessException("非法请求"); } @RequestMapping(value = "/video/808/{deviceId}", method = RequestMethod.DELETE) public Result stopJtt808Video(@PathVariable String deviceId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestParam String clinetId, @RequestParam String channelId) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } this.messageService.stop808Video(enterpriseId, deviceId, channelId, clinetId, gatewayId); return new Result(); } throw new BizProcessException("非法请求"); } @RequestMapping(value = "/talk/1078/{deviceId}", method = RequestMethod.POST) public Result startLiveTalk(@PathVariable String deviceId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestParam String clinetId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.start1078Talk(enterpriseId, deviceId, clinetId, messageBody, gatewayId)); } throw new BizProcessException("非法请求"); } @RequestMapping(value = "/video/1078/{deviceId}", method = RequestMethod.POST) public Result startLiveVideo(@PathVariable String deviceId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestParam String clinetId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.start1078Video(enterpriseId, deviceId, clinetId, messageBody, gatewayId)); } throw new BizProcessException("非法请求"); } @RequestMapping(value = "/video/1078/{deviceId}", method = RequestMethod.PUT) public Result stopLiveVideo(@PathVariable String deviceId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestParam String clinetId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } this.messageService.stop1078Video(enterpriseId, deviceId, clinetId, messageBody, gatewayId); return new Result(); } throw new BizProcessException("非法请求"); } @RequestMapping(value = "/deviceDownMessage/{deviceId}/{messageId}", method = RequestMethod.POST) public Result sendMessage(@PathVariable String deviceId, @PathVariable String messageId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.send(enterpriseId, deviceId, messageId, messageBody, gatewayId)); } throw new BizProcessException("非法请求"); } @RequestMapping(value = "/deviceDownMessage/fence/{deviceId}/{messageId}", method = RequestMethod.POST) public Result sendFenceMessage(@PathVariable String deviceId, @PathVariable String messageId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.setFence(enterpriseId, deviceId, messageId, messageBody, gatewayId)); } throw new BizProcessException("非法请求"); } @RequestMapping(value = "/deviceDownMessage/fence/{deviceId}/{messageId}/{ids}", method = RequestMethod.DELETE) public Result sendDelFenceMessage(@PathVariable String deviceId, @PathVariable String messageId, @PathVariable String ids, @RequestHeader(name = "_enterpriseId") String enterpriseId) throws Exception { if (StringUtils.isBlank(ids)) { throw new BizProcessException("非法请求"); } Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.delFence(enterpriseId, deviceId, messageId, ids.split(","), gatewayId)); } throw new BizProcessException("非法请求"); } @RequestMapping(value = "/batch/deviceDownMessage/{messageId}", method = RequestMethod.POST) public Result batchSendMessage(@PathVariable String messageId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestBody Map<String, Object> messageBody) throws Exception { List<?> list = messageService.batchSend(enterpriseId, messageId, messageBody); return new Result(list); } @RequestMapping(value = "/deviceDownMessage/{id}/state", method = RequestMethod.GET) public Result getDeviceDownMessageState(@PathVariable String id, @RequestHeader(name = "_enterpriseId") String enterpriseId) throws Exception { String[] ids = id.split(","); if (ids.length > 10) { throw new BizProcessException("每次最多允许查询10条消息的状态"); } return new Result(this.messageService.getDeviceDownMessageState(enterpriseId, ids)); } /** * 强制终端下线 * * @param deviceId * @param enterpriseId * @return * @throws Exception */ @RequestMapping(value = "/device/offline/{deviceId}", method = RequestMethod.DELETE) public Result forceOffline(@PathVariable String deviceId, @RequestHeader(name = "_enterpriseId") String enterpriseId) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (!StringUtils.isBlank(gatewayId)) { int status = this.deviceService.getStatus(deviceId, gatewayId); if (status == 3) { this.messageService.forceOffline(device.getSimCode(), gatewayId); } } return new Result(); } throw new BizProcessException("非法请求"); } /** * 解除网关黑名单 * * @param id * @return * @throws Exception */ @RequestMapping(value = "/gateway/blacklist/{ids}", method = RequestMethod.DELETE) public Result removeBlacklist(@PathVariable String ids) throws Exception { String[] arr = ids.split(","); for (String id : arr) { messageService.removeBlacklist(id); } return new Result(); } /** * 上传文件指令 * * @param deviceId * @param messageId * @param enterpriseId * @param messageBody * @return * @throws Exception */ @RequestMapping(value = "/message/uploadFile/{deviceId}/{messageId}", method = RequestMethod.POST) public Result uploadFile(@PathVariable String deviceId, @PathVariable String messageId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.uploadFile(enterpriseId, deviceId, messageId, messageBody, gatewayId)); } throw new BizProcessException("非法请求"); } /** * 上传文件指令 * * @param deviceId * @param messageId * @param enterpriseId * @param messageBody * @return * @throws Exception */ @RequestMapping(value = "/message/uploadControl/{deviceId}/{messageId}", method = RequestMethod.POST) public Result uploadControl(@PathVariable String deviceId, @PathVariable String messageId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.uploadControl(enterpriseId, deviceId, messageId, messageBody, gatewayId)); } throw new BizProcessException("非法请求"); } /** * 历史音视频资源查询指令 * * @param deviceId * @param messageId * @param enterpriseId * @param messageBody * @return * @throws Exception */ @RequestMapping(value = "/message/fileResource/{deviceId}/{messageId}", method = RequestMethod.POST) public Result queryFileResource(@PathVariable String deviceId, @PathVariable String messageId, @RequestHeader(name = "_enterpriseId") String enterpriseId, @RequestBody Map<String, Object> messageBody) throws Exception { Device device = (Device) this.service.get(Device.ENTITY_NAME, deviceId); if (device != null && device.getEnterpriseId().startsWith(enterpriseId)) { String gatewayId = this.deviceService.getGateway(deviceId); if (StringUtils.isBlank(gatewayId) || this.deviceService.getStatus(deviceId, gatewayId) != 3) { throw new BizProcessException("车辆不在线"); } return new Result(this.messageService.queryFileResource(enterpriseId, deviceId, messageId, messageBody, gatewayId)); } throw new BizProcessException("非法请求"); } }
// SPDX-License-Identifier: BSD-3-Clause // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) package org.xbill.DNS; import java.io.IOException; import java.io.Serializable; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.TreeMap; /** * A DNS Zone. This encapsulates all data related to a Zone, and provides convenient lookup methods. * * @author Brian Wellington */ public class Zone implements Serializable { private static final long serialVersionUID = -9220510891189510942L; /** A primary zone */ public static final int PRIMARY = 1; /** A secondary zone */ public static final int SECONDARY = 2; private Map<Name, Object> data; private Name origin; private Object originNode; private RRset NS; private SOARecord SOA; private boolean hasWild; class ZoneIterator implements Iterator<RRset> { private final Iterator<Map.Entry<Name, Object>> zentries; private RRset[] current; private int count; private boolean wantLastSOA; ZoneIterator(boolean axfr) { synchronized (Zone.this) { zentries = data.entrySet().iterator(); } wantLastSOA = axfr; RRset[] sets = allRRsets(originNode); current = new RRset[sets.length]; for (int i = 0, j = 2; i < sets.length; i++) { int type = sets[i].getType(); if (type == Type.SOA) { current[0] = sets[i]; } else if (type == Type.NS) { current[1] = sets[i]; } else { current[j++] = sets[i]; } } } @Override public boolean hasNext() { return current != null || wantLastSOA; } @Override public RRset next() { if (!hasNext()) { throw new NoSuchElementException(); } if (current == null) { wantLastSOA = false; return oneRRset(originNode, Type.SOA); } RRset set = current[count++]; if (count == current.length) { current = null; while (zentries.hasNext()) { Map.Entry<Name, Object> entry = zentries.next(); if (entry.getKey().equals(origin)) { continue; } RRset[] sets = allRRsets(entry.getValue()); if (sets.length == 0) { continue; } current = sets; count = 0; break; } } return set; } @Override public void remove() { throw new UnsupportedOperationException(); } } private void validate() throws IOException { originNode = exactName(origin); if (originNode == null) { throw new IOException(origin + ": no data specified"); } RRset rrset = oneRRset(originNode, Type.SOA); if (rrset == null || rrset.size() != 1) { throw new IOException(origin + ": exactly 1 SOA must be specified"); } SOA = (SOARecord) rrset.rrs().get(0); NS = oneRRset(originNode, Type.NS); if (NS == null) { throw new IOException(origin + ": no NS set specified"); } } private void maybeAddRecord(Record record) throws IOException { int rtype = record.getType(); Name name = record.getName(); if (rtype == Type.SOA && !name.equals(origin)) { throw new IOException("SOA owner " + name + " does not match zone origin " + origin); } if (name.subdomain(origin)) { addRecord(record); } } /** * Creates a Zone from the records in the specified master file. * * @param zone The name of the zone. * @param file The master file to read from. * @see Master */ public Zone(Name zone, String file) throws IOException { data = new TreeMap<>(); if (zone == null) { throw new IllegalArgumentException("no zone name specified"); } try (Master m = new Master(file, zone)) { Record record; origin = zone; while ((record = m.nextRecord()) != null) { maybeAddRecord(record); } } validate(); } /** * Creates a Zone from an array of records. * * @param zone The name of the zone. * @param records The records to add to the zone. * @see Master */ public Zone(Name zone, Record[] records) throws IOException { data = new TreeMap<>(); if (zone == null) { throw new IllegalArgumentException("no zone name specified"); } origin = zone; for (Record record : records) { maybeAddRecord(record); } validate(); } private void fromXFR(ZoneTransferIn xfrin) throws IOException, ZoneTransferException { synchronized (this) { data = new TreeMap<>(); } origin = xfrin.getName(); xfrin.run(); if (!xfrin.isAXFR()) { throw new IllegalArgumentException("zones can only be created from AXFRs"); } for (Record record : xfrin.getAXFR()) { maybeAddRecord(record); } validate(); } /** * Creates a Zone by doing the specified zone transfer. * * @param xfrin The incoming zone transfer to execute. * @see ZoneTransferIn */ public Zone(ZoneTransferIn xfrin) throws IOException, ZoneTransferException { fromXFR(xfrin); } /** * Creates a Zone by performing a zone transfer to the specified host. * * @see ZoneTransferIn */ public Zone(Name zone, int dclass, String remote) throws IOException, ZoneTransferException { ZoneTransferIn xfrin = ZoneTransferIn.newAXFR(zone, remote, null); xfrin.setDClass(dclass); fromXFR(xfrin); } /** Returns the Zone's origin */ public Name getOrigin() { return origin; } /** Returns the Zone origin's NS records */ public RRset getNS() { return NS; } /** Returns the Zone's SOA record */ public SOARecord getSOA() { return SOA; } /** Returns the Zone's class */ public int getDClass() { return DClass.IN; } private synchronized Object exactName(Name name) { return data.get(name); } private synchronized RRset[] allRRsets(Object types) { if (types instanceof List) { @SuppressWarnings("unchecked") List<RRset> typelist = (List<RRset>) types; return typelist.toArray(new RRset[0]); } else { RRset set = (RRset) types; return new RRset[] {set}; } } private synchronized RRset oneRRset(Object types, int type) { if (type == Type.ANY) { throw new IllegalArgumentException("oneRRset(ANY)"); } if (types instanceof List) { @SuppressWarnings("unchecked") List<RRset> list = (List<RRset>) types; for (RRset set : list) { if (set.getType() == type) { return set; } } } else { RRset set = (RRset) types; if (set.getType() == type) { return set; } } return null; } private synchronized RRset findRRset(Name name, int type) { Object types = exactName(name); if (types == null) { return null; } return oneRRset(types, type); } private synchronized void addRRset(Name name, RRset rrset) { if (!hasWild && name.isWild()) { hasWild = true; } Object types = data.get(name); if (types == null) { data.put(name, rrset); return; } int rtype = rrset.getType(); if (types instanceof List) { @SuppressWarnings("unchecked") List<RRset> list = (List<RRset>) types; for (int i = 0; i < list.size(); i++) { RRset set = list.get(i); if (set.getType() == rtype) { list.set(i, rrset); return; } } list.add(rrset); } else { RRset set = (RRset) types; if (set.getType() == rtype) { data.put(name, rrset); } else { LinkedList<RRset> list = new LinkedList<>(); list.add(set); list.add(rrset); data.put(name, list); } } } private synchronized void removeRRset(Name name, int type) { Object types = data.get(name); if (types == null) { return; } if (types instanceof List) { @SuppressWarnings("unchecked") List<RRset> list = (List<RRset>) types; for (int i = 0; i < list.size(); i++) { RRset set = list.get(i); if (set.getType() == type) { list.remove(i); if (list.size() == 0) { data.remove(name); } return; } } } else { RRset set = (RRset) types; if (set.getType() != type) { return; } data.remove(name); } } private synchronized SetResponse lookup(Name name, int type) { if (!name.subdomain(origin)) { return SetResponse.ofType(SetResponse.NXDOMAIN); } int labels = name.labels(); int olabels = origin.labels(); for (int tlabels = olabels; tlabels <= labels; tlabels++) { boolean isOrigin = tlabels == olabels; boolean isExact = tlabels == labels; Name tname; if (isOrigin) { tname = origin; } else if (isExact) { tname = name; } else { tname = new Name(name, labels - tlabels); } Object types = exactName(tname); if (types == null) { continue; } /* If this is a delegation, return that. */ if (!isOrigin) { RRset ns = oneRRset(types, Type.NS); if (ns != null) { return new SetResponse(SetResponse.DELEGATION, ns); } } /* If this is an ANY lookup, return everything. */ if (isExact && type == Type.ANY) { SetResponse sr = new SetResponse(SetResponse.SUCCESSFUL); for (RRset set : allRRsets(types)) { sr.addRRset(set); } return sr; } /* * If this is the name, look for the actual type or a CNAME. * Otherwise, look for a DNAME. */ if (isExact) { RRset rrset = oneRRset(types, type); if (rrset != null) { return new SetResponse(SetResponse.SUCCESSFUL, rrset); } rrset = oneRRset(types, Type.CNAME); if (rrset != null) { return new SetResponse(SetResponse.CNAME, rrset); } } else { RRset rrset = oneRRset(types, Type.DNAME); if (rrset != null) { return new SetResponse(SetResponse.DNAME, rrset); } } /* We found the name, but not the type. */ if (isExact) { return SetResponse.ofType(SetResponse.NXRRSET); } } if (hasWild) { for (int i = 0; i < labels - olabels; i++) { Name tname = name.wild(i + 1); Object types = exactName(tname); if (types == null) { continue; } if (type == Type.ANY) { SetResponse sr = new SetResponse(SetResponse.SUCCESSFUL); for (RRset set : allRRsets(types)) { sr.addRRset(expandSet(set, name)); } return sr; } else { RRset rrset = oneRRset(types, type); if (rrset != null) { return new SetResponse(SetResponse.SUCCESSFUL, expandSet(rrset, name)); } } } } return SetResponse.ofType(SetResponse.NXDOMAIN); } private RRset expandSet(RRset set, Name tname) { RRset expandedSet = new RRset(); for (Record r : set.rrs()) { expandedSet.addRR(r.withName(tname)); } for (RRSIGRecord r : set.sigs()) { expandedSet.addRR(r.withName(tname)); } return expandedSet; } /** * Looks up Records in the Zone. The answer can be a {@code CNAME} instead of the actual requested * type and wildcards are expanded. * * @param name The name to look up * @param type The type to look up * @return A SetResponse object * @see SetResponse */ public SetResponse findRecords(Name name, int type) { return lookup(name, type); } /** * Looks up Records in the zone, finding exact matches only. * * @param name The name to look up * @param type The type to look up * @return The matching RRset * @see RRset */ public RRset findExactMatch(Name name, int type) { Object types = exactName(name); if (types == null) { return null; } return oneRRset(types, type); } /** * Adds an RRset to the Zone * * @param rrset The RRset to be added * @see RRset */ public void addRRset(RRset rrset) { Name name = rrset.getName(); addRRset(name, rrset); } /** * Adds a Record to the Zone * * @param r The record to be added * @see Record */ public <T extends Record> void addRecord(T r) { Name name = r.getName(); int rtype = r.getRRsetType(); synchronized (this) { RRset rrset = findRRset(name, rtype); if (rrset == null) { rrset = new RRset(r); addRRset(name, rrset); } else { rrset.addRR(r); } } } /** * Removes a record from the Zone * * @param r The record to be removed * @see Record */ public void removeRecord(Record r) { Name name = r.getName(); int rtype = r.getRRsetType(); synchronized (this) { RRset rrset = findRRset(name, rtype); if (rrset == null) { return; } if (rrset.size() == 1 && rrset.first().equals(r)) { removeRRset(name, rtype); } else { rrset.deleteRR(r); } } } /** Returns an Iterator over the RRsets in the zone. */ public Iterator<RRset> iterator() { return new ZoneIterator(false); } /** * Returns an Iterator over the RRsets in the zone that can be used to construct an AXFR response. * This is identical to {@link #iterator} except that the SOA is returned at the end as well as * the beginning. */ public Iterator<RRset> AXFR() { return new ZoneIterator(true); } private void nodeToString(StringBuffer sb, Object node) { RRset[] sets = allRRsets(node); for (RRset rrset : sets) { rrset.rrs().forEach(r -> sb.append(r).append('\n')); rrset.sigs().forEach(r -> sb.append(r).append('\n')); } } /** Returns the contents of the Zone in master file format. */ public synchronized String toMasterFile() { StringBuffer sb = new StringBuffer(); nodeToString(sb, originNode); for (Map.Entry<Name, Object> entry : data.entrySet()) { if (!origin.equals(entry.getKey())) { nodeToString(sb, entry.getValue()); } } return sb.toString(); } /** Returns the contents of the Zone as a string (in master file format). */ @Override public String toString() { return toMasterFile(); } }
package javaAssigns; import java.io.IOException; public class Nice { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub // Perimeters p=new Perimeters(); Areas a=new Areas(); // p.Perimeters(7); // p.Perimeters(2, 9); // p.Perimeters(4, "square"); a.circle(); a.square(); a.rectangle(); } }
package fj.swsk.cn.eqapp.subs.setting.C; import android.app.Activity; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.PopupWindow; import fj.swsk.cn.eqapp.R; /** * Created by xul on 2016/8/6. */ public class SelectItemPopupWindow extends PopupWindow { private ListView mListView; public SelectItemPopupWindow(Activity context) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View mMenuView = inflater.inflate(R.layout.bottom_listview, null); mListView = (ListView)mMenuView.findViewById(R.id.lvResults); this.setContentView(mMenuView); //设置SelectPicPopupWindow弹出窗体的宽 this.setWidth(LayoutParams.FILL_PARENT); //设置SelectPicPopupWindow弹出窗体的高 this.setHeight(LayoutParams.WRAP_CONTENT); //设置SelectPicPopupWindow弹出窗体可点击 this.setFocusable(true); //设置SelectPicPopupWindow弹出窗体动画效果 this.setAnimationStyle(R.style.PopupAnimation); //实例化一个ColorDrawable颜色为半透明 ColorDrawable dw = new ColorDrawable(0xb0000000); //设置SelectPicPopupWindow弹出窗体的背景 this.setBackgroundDrawable(dw); } public void setOnItemClickListener(ListView.OnItemClickListener itemOnClick){ mListView.setOnItemClickListener(itemOnClick); } public void setListViewAdapter(BaseAdapter adapter){ mListView.setAdapter(adapter); adapter.notifyDataSetChanged(); } }
/* * 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 org.rdcit.tools; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import static java.nio.file.StandardCopyOption.REPLACE_EXISTING; import static org.rdcit.tools.Statics.*; /** * * @author sa841 */ public class TemplateFactory { public static void setWorkingRepository() { } public static void createCrfTemplate(File outputFile) { try { Files.copy(Paths.get(OC_DESIGN_TEMPLATE.toURI()), Paths.get(outputFile.toURI()), REPLACE_EXISTING); } catch (IOException ex) { System.out.println(ex.getMessage()); } } public static void createSctoTemplate(File outputFile) { try { Files.copy(Paths.get(SCTO_DESIGN_TEMPLATE.toURI()), Paths.get(outputFile.toURI()), REPLACE_EXISTING); } catch (IOException ex) { System.out.println(ex.getMessage()); } } public static void deleteTempFiles() { File directory = new File(workingRepository); for (File f : directory.listFiles()) { if((!f.getName().equals(OC_DESIGN_TEMPLATE.getName())) && (!f.getName().equals(SCTO_DESIGN_TEMPLATE.getName()))) if (f.getName().endsWith(".xls") || f.getName().endsWith(".xlsx") ) { f.delete(); } } } }
/** * FileName: TextServiceImpl * Author: 陈江超 * Date: 2019/7/22 11:32 * Description: 文章操作实现 */ package com.github.service.impl; import com.alibaba.fastjson.JSON; import com.github.dao.TextDao; import com.github.dao.UserDao; import com.github.dao.impl.TextDaoImpl; import com.github.dao.impl.UserDaoImpl; import com.github.domain.*; import com.github.service.TextService; import java.util.ArrayList; import java.util.List; /** * 〈一句话功能简述〉<br> * 〈文章操作实现〉 * * @author 陈江超 * @create 2019/7/22 * @since 1.0.0 */ public class TextServiceImpl implements TextService { TextDao textDao = new TextDaoImpl(); @Override public void createText(Text text) { textDao.createText(text); } @Override public Boolean addComment(comment comments) { int commentid = textDao.addCommentToText(comments); if (commentid != -1){ return textDao.addComment(comments, commentid); }else { System.out.println("存储评论到数据库错误,报错点(TextServiceImpl-->addComment)"); return false; } } // @Override // public text1 findText(text2 text) { // // Text textDaoText = textDao.findText(text); // if (textDaoText != null){ // // 将textDaoText对象转换为json字符串 // String s = JSON.toJSONString(textDaoText); // // 将Text对象的参数拷贝到text1对象中 // text1 textObject = JSON.parseObject(s, text1.class); // // 根据要查找的文章id,找到对应为作者的昵称 // UserDao userDao = new UserDaoImpl(); // User user = userDao.findUserByTextId(text.getTextid()); // // 在textObject中设置username参数的值 // textObject.setUsername(user.getUsername()); // return textObject; // } // else{ // return null; // } // // } @Override public text2 findAlltext(int textid) { return textDao.findFirstComment(textid); } @Override public Boolean deleteText(int textid) { return textDao.deleteText(textid); } @Override public Boolean updateCommentNum(int textid) { return textDao.updateTextCommentNum(textid); } @Override public List<simpletext> getsimpleTextByUserID(String userid) { return textDao.getsimpleTextByUserID(userid); } @Override public List<simpletext> getcollectionByUserID(String userid) { return textDao.getcollectionByUserID(userid); } @Override public void updateLikes(int likes, int textid) { textDao.updateLikes(likes, textid); } @Override public Boolean cancelCollection(collection collection) { return textDao.cancelCollection(collection); } @Override public List<simpletext_article> getAllsimpleartcle() { return textDao.getAllsimpleartcle(); } @Override public List<simpletext_article> getTopArticle() { return textDao.getTopArticle(); } @Override public List<simpletext_article> searchArticleByKeyWorks(String keyworks) { return textDao.searchArticleByKeyWorks(keyworks); } @Override public void addHomearticle(int textid) { textDao.addHomearticle(textid); } @Override public void cancleHomearticle(int textid) { textDao.cancleHomearticle(textid); } @Override public List<simpletext_article> getCanToHomeArtivcle() { return textDao.getCanToHomeArtivcle(); } // @Override // public text2 findAlltext(ArrayList<Text> text) { // ArrayList<text2> list2 = null; // for (Text atext : text) { // TextService textService = new TextServiceImpl(); // text1 text1 = textService.findText(atext); // String s = JSON.toJSONString(text1); // text2 textObject = JSON.parseObject(s, text2.class); // TextDao textDao = new TextDaoImpl(); // ArrayList<Text> firstComment = textDao.findFirstComment(textObject.getTextid()); // if (firstComment != null) { // text2 alltext = findAlltext(firstComment); // list2.add(alltext); // } else { // list2.add(textObject); // } // textObject.setList(list2); // } // return text.get(0); // } }
package com.syc.net.aio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousServerSocketChannel; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.CountDownLatch; public class AsyncTimeServerHandler implements Runnable { private AsynchronousServerSocketChannel asynchronousServerSocketChannel; public AsyncTimeServerHandler(int port) { try { asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open() .bind(new InetSocketAddress(port)); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { CountDownLatch latch = new CountDownLatch(1); // do somethings ,but will not quit doAccept(); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } private void doAccept() { asynchronousServerSocketChannel.accept(this, new CompletionHandler<AsynchronousSocketChannel, AsyncTimeServerHandler>() { @Override public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) { attachment.asynchronousServerSocketChannel.accept(attachment, this); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); result.read(byteBuffer, byteBuffer, new ReadCompletionHandler(result)); } @Override public void failed(Throwable exc, AsyncTimeServerHandler attachment) { System.out.println("请求失败"); exc.printStackTrace(); System.out.println(attachment); } }); } }
package com.nowcoder.community.dao; import com.nowcoder.community.entity.LoginTicket; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Update; @Mapper public interface LoginTicketMapper { int insertLoginTicket(LoginTicket loginTicket); LoginTicket selectByTicket(String ticket); // @Update({ // "<script>", // "update login_ticket set status = #{arg1} where ticket = #{arg0} ", // "<if test = \"ticket!=null\">", // "and 1 = 1", // "</if>", // "</script>" // }) int updateStatus(@Param("ticket") String ticket, @Param("status") int status); }
package com.zhongyp.algorithm; /** * project: demo * author: zhongyp * date: 2018/2/28 * mail: zhongyp001@163.com */ public class RadixSort { /** * * 基数排序 * @param A * @param n * @return * * 基数排序思想:求出最大的数是几位的,建10个桶,一个计数器,从个位开始排序,按照数值存入桶中,然后按照顺序取出,置空计数器。接着从十位开始排序,操作和个位一样,直到最大位数。 * */ public int[] radixSort(int[] A, int n) { int length = n; int divisor = 1;// 定义每一轮的除数,1,10,100... int[][] bucket = new int[10][length];// 定义了10个桶,以防每一位都一样全部放入一个桶中 int[] count = new int[10];// 统计每个桶中实际存放的元素个数 int digit;// 获取元素中对应位上的数字,即装入那个桶 for (int i = 1; i <= 3; i++) {// 经过4次装通操作,排序完成 for (int temp : A) {// 计算入桶 digit = (temp / divisor) % 10; bucket[digit][count[digit]++] = temp; } int k = 0;// 被排序数组的下标 for (int b = 0; b < 10; b++) {// 从0到9号桶按照顺序取出 if (count[b] == 0)// 如果这个桶中没有元素放入,那么跳过 {continue;} for (int w = 0; w < count[b]; w++) { A[k++] = bucket[b][w]; } count[b] = 0;// 桶中的元素已经全部取出,计数器归零 } divisor *= 10; } return A; } }
class Solution { public List<List<Integer>> levelOrder(Node root) { List<List<Integer>> res = new ArrayList<>(); if (root == null) return res; Queue<Node> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { int size = queue.size(); List<Integer> curLevel = new ArrayList<>(); for (int i = 0; i < size; i++) { Node curr = queue.poll(); curLevel.add(curr.val); for (Node child : curr.children) queue.offer(child); } res.add(curLevel); } return res; } }
package com.download.data; public class HUDList1 { private String agcid; private String adr1; private String adr2; private String city; private String email; private String fax; private String nme; private String phone1; private String statecd; private String weburl; private String zipcd; private String agc_ADDR_LATITUDE; private String agc_ADDR_LONGITUDE; private String languages; private String services; private String parentid; private String county_NME; private String phone2; private String mailingadr1; private String mailingadr2; private String mailingcity; private String mailingzipcd; private String mailingstatecd; private String state_NME; private String state_FIPS_CODE; private String faithbased; private String colonias_IND; private String migrantwkrs_IND; private String agc_STATUS; private String agc_SRC_CD; private String counslg_METHOD; private String distance; private String adj; private String vP; public HUDList1() {}; public HUDList1(String agcid, String adr1, String adr2, String city, String email, String fax, String nme, String phone1, String statecd, String weburl, String zipcd, String agc_ADDR_LATITUDE, String agc_ADDR_LONGITUDE, String languages, String services, String parentid, String county_NME, String phone2, String mailingadr1, String mailingadr2, String mailingcity, String mailingzipcd, String mailingstatecd, String state_NME, String state_FIPS_CODE, String faithbased, String colonias_IND, String migrantwkrs_IND, String agc_STATUS, String agc_SRC_CD, String counslg_METHOD, String distance, String adj, String vP) { super(); this.agcid = agcid; this.adr1 = adr1; this.adr2 = adr2; this.city = city; this.email = email; this.fax = fax; this.nme = nme; this.phone1 = phone1; this.statecd = statecd; this.weburl = weburl; this.zipcd = zipcd; this.agc_ADDR_LATITUDE = agc_ADDR_LATITUDE; this.agc_ADDR_LONGITUDE = agc_ADDR_LONGITUDE; this.languages = languages; this.services = services; this.parentid = parentid; this.county_NME = county_NME; this.phone2 = phone2; this.mailingadr1 = mailingadr1; this.mailingadr2 = mailingadr2; this.mailingcity = mailingcity; this.mailingzipcd = mailingzipcd; this.mailingstatecd = mailingstatecd; this.state_NME = state_NME; this.state_FIPS_CODE = state_FIPS_CODE; this.faithbased = faithbased; this.colonias_IND = colonias_IND; this.migrantwkrs_IND = migrantwkrs_IND; this.agc_STATUS = agc_STATUS; this.agc_SRC_CD = agc_SRC_CD; this.counslg_METHOD = counslg_METHOD; this.distance = distance; this.setAdj(adj); this.setvP(vP); } public String getAgcid() { return agcid; } public void setAgcid(String agcid) { this.agcid = agcid; } public String getAdr1() { return adr1; } public void setAdr1(String adr1) { this.adr1 = adr1; } public String getAdr2() { return adr2; } public void setAdr2(String adr2) { this.adr2 = adr2; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getNme() { return nme; } public void setNme(String nme) { this.nme = nme; } public String getPhone1() { return phone1; } public void setPhone1(String phone1) { this.phone1 = phone1; } public String getStatecd() { return statecd; } public void setStatecd(String statecd) { this.statecd = statecd; } public String getWeburl() { return weburl; } public void setWeburl(String weburl) { this.weburl = weburl; } public String getZipcd() { return zipcd; } public void setZipcd(String zipcd) { this.zipcd = zipcd; } public String getAgc_ADDR_LATITUDE() { return agc_ADDR_LATITUDE; } public void setAgc_ADDR_LATITUDE(String agc_ADDR_LATITUDE) { this.agc_ADDR_LATITUDE = agc_ADDR_LATITUDE; } public String getAgc_ADDR_LONGITUDE() { return agc_ADDR_LONGITUDE; } public void setAgc_ADDR_LONGITUDE(String agc_ADDR_LONGITUDE) { this.agc_ADDR_LONGITUDE = agc_ADDR_LONGITUDE; } public String getLanguages() { return languages; } public void setLanguages(String languages) { this.languages = languages; } public String getServices() { return services; } public void setServices(String services) { this.services = services; } public String getParentid() { return parentid; } public void setParentid(String parentid) { this.parentid = parentid; } public String getCounty_NME() { return county_NME; } public void setCounty_NME(String county_NME) { this.county_NME = county_NME; } public String getPhone2() { return phone2; } public void setPhone2(String phone2) { this.phone2 = phone2; } public String getMailingadr1() { return mailingadr1; } public void setMailingadr1(String mailingadr1) { this.mailingadr1 = mailingadr1; } public String getMailingadr2() { return mailingadr2; } public void setMailingadr2(String mailingadr2) { this.mailingadr2 = mailingadr2; } public String getMailingcity() { return mailingcity; } public void setMailingcity(String mailingcity) { this.mailingcity = mailingcity; } public String getMailingzipcd() { return mailingzipcd; } public void setMailingzipcd(String mailingzipcd) { this.mailingzipcd = mailingzipcd; } public String getMailingstatecd() { return mailingstatecd; } public void setMailingstatecd(String mailingstatecd) { this.mailingstatecd = mailingstatecd; } public String getState_NME() { return state_NME; } public void setState_NME(String state_NME) { this.state_NME = state_NME; } public String getState_FIPS_CODE() { return state_FIPS_CODE; } public void setState_FIPS_CODE(String state_FIPS_CODE) { this.state_FIPS_CODE = state_FIPS_CODE; } public String getFaithbased() { return faithbased; } public void setFaithbased(String faithbased) { this.faithbased = faithbased; } public String getColonias_IND() { return colonias_IND; } public void setColonias_IND(String colonias_IND) { this.colonias_IND = colonias_IND; } public String getMigrantwkrs_IND() { return migrantwkrs_IND; } public void setMigrantwkrs_IND(String migrantwkrs_IND) { this.migrantwkrs_IND = migrantwkrs_IND; } public String getAgc_STATUS() { return agc_STATUS; } public void setAgc_STATUS(String agc_STATUS) { this.agc_STATUS = agc_STATUS; } public String getAgc_SRC_CD() { return agc_SRC_CD; } public void setAgc_SRC_CD(String agc_SRC_CD) { this.agc_SRC_CD = agc_SRC_CD; } public String getCounslg_METHOD() { return counslg_METHOD; } public void setCounslg_METHOD(String counslg_METHOD) { this.counslg_METHOD = counslg_METHOD; } @Override public String toString() { return (this.getAgcid() + this.getAdr1()); } public String getDistance() { return distance; } public void setDistance(String distance) { this.distance = distance; } public String getAdj() { return adj; } public void setAdj(String adj) { this.adj = adj; } public String getvP() { return vP; } public void setvP(String vP) { this.vP = vP; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package view; import controller.PessoaJpaController; import java.util.Iterator; import java.util.Vector; import javax.swing.table.DefaultTableModel; import model.domain.Pessoa; /** * * @author Danie */ public class PessoasView extends javax.swing.JInternalFrame { /** * Creates new form CaixasView */ private PessoaJpaController pessoaJpaController; public PessoasView() { this.pessoaJpaController = new PessoaJpaController(); initComponents(); } public PessoaJpaController getPessoasController() { return pessoaJpaController; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); jPanel3 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); textIdPessoa = new javax.swing.JTextField(); textNomePessoa = new javax.swing.JTextField(); textTelefonePessoa = new javax.swing.JTextField(); textEmailPessoa = new javax.swing.JTextField(); panelBotoes = new javax.swing.JPanel(); btnInserir = new javax.swing.JButton(); btnRemover = new javax.swing.JButton(); btnAlterar = new javax.swing.JButton(); btnPesquisar = new javax.swing.JButton(); btnNovo = new javax.swing.JButton(); panelTabela = new javax.swing.JScrollPane(); tabelaCaixas = new javax.swing.JTable(); selectCargo = new javax.swing.JComboBox<>(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); textSenha = new javax.swing.JTextField(); setClosable(true); setTitle("Cadastro de Funcionários"); setVisible(true); jLabel1.setText("Id"); jLabel2.setText("Nome Completo"); jLabel3.setText("Telefone"); jLabel4.setText("Email"); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${pessoasController.pessoaDigitada.id}"), textIdPessoa, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); textIdPessoa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textIdPessoaActionPerformed(evt); } }); textNomePessoa.setEnabled(false); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${pessoasController.pessoaDigitada.nomePessoa}"), textNomePessoa, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); textTelefonePessoa.setEnabled(false); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${pessoasController.pessoaDigitada.telefone}"), textTelefonePessoa, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); textEmailPessoa.setEnabled(false); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${pessoasController.pessoaDigitada.dataAdmissao}"), textEmailPessoa, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); btnInserir.setText("Inserir"); btnInserir.setEnabled(false); btnInserir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnInserirActionPerformed(evt); } }); btnRemover.setText("Remover"); btnRemover.setEnabled(false); btnRemover.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnRemoverActionPerformed(evt); } }); btnAlterar.setText("Alterar"); btnAlterar.setEnabled(false); btnPesquisar.setText("Pesquisar"); btnNovo.setText("Novo"); btnNovo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNovoActionPerformed(evt); } }); javax.swing.GroupLayout panelBotoesLayout = new javax.swing.GroupLayout(panelBotoes); panelBotoes.setLayout(panelBotoesLayout); panelBotoesLayout.setHorizontalGroup( panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panelBotoesLayout.createSequentialGroup() .addComponent(btnNovo) .addGap(18, 18, 18) .addComponent(btnInserir) .addGap(18, 18, 18) .addComponent(btnAlterar) .addGap(18, 18, 18) .addComponent(btnRemover) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnPesquisar) .addContainerGap()) ); panelBotoesLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnAlterar, btnInserir, btnRemover}); panelBotoesLayout.setVerticalGroup( panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotoesLayout.createSequentialGroup() .addContainerGap() .addGroup(panelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnInserir) .addComponent(btnRemover) .addComponent(btnAlterar) .addComponent(btnPesquisar) .addComponent(btnNovo)) .addContainerGap()) ); panelBotoesLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnAlterar, btnInserir, btnRemover}); tabelaCaixas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "ID", "Nome Completo", "Telefone", "Email" } ) { boolean[] canEdit = new boolean [] { false, false, false, false }; public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${pessoasController.listaPessoa}"); org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, eLProperty, tabelaCaixas); org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idPessoa}")); columnBinding.setColumnName("Id Pessoa"); columnBinding.setColumnClass(Integer.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nomePessoa}")); columnBinding.setColumnName("Nome Pessoa"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${emailPessoa}")); columnBinding.setColumnName("Email Pessoa"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${telefonePessoa}")); columnBinding.setColumnName("Telefone Pessoa"); columnBinding.setColumnClass(String.class); columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cargoPessoa}")); columnBinding.setColumnName("Cargo Pessoa"); columnBinding.setColumnClass(String.class); bindingGroup.addBinding(jTableBinding); jTableBinding.bind();binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${pessoasController.pessoaSelecionada}"), tabelaCaixas, org.jdesktop.beansbinding.BeanProperty.create("selectedElement")); bindingGroup.addBinding(binding); panelTabela.setViewportView(tabelaCaixas); selectCargo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Funcionario", "Gerente" })); selectCargo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { selectCargoActionPerformed(evt); } }); jLabel5.setText("Cargo"); jLabel6.setText("Senha"); textSenha.setEnabled(false); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panelBotoes, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(textTelefonePessoa, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textIdPessoa, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textNomePessoa) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(textEmailPessoa, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel6) .addComponent(textSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(18, 18, Short.MAX_VALUE) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(selectCargo, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap()) .addComponent(panelTabela))) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textIdPessoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textNomePessoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6)) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(textEmailPessoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(selectCargo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(textTelefonePessoa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panelTabela, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); 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() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) ); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents private void textIdPessoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textIdPessoaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_textIdPessoaActionPerformed private void btnRemoverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoverActionPerformed // TODO add your handling code here: }//GEN-LAST:event_btnRemoverActionPerformed private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed this.btnInserir.setEnabled(true); this.textEmailPessoa.setEnabled(true); this.textNomePessoa.setEnabled(true); this.textTelefonePessoa.setEnabled(true); this.textSenha.setEnabled(true); this.textIdPessoa.setEnabled(false); this.textEmailPessoa.setText(null); this.textNomePessoa.setText(null); this.textTelefonePessoa.setText(null); }//GEN-LAST:event_btnNovoActionPerformed private void btnInserirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInserirActionPerformed this.pessoaJpaController.create(new Pessoa(this.textNomePessoa.getText(), this.textEmailPessoa.getText(), this.textTelefonePessoa.getText(), this.selectCargo.getItemAt(this.selectCargo.getSelectedIndex()), this.textSenha.getText())); }//GEN-LAST:event_btnInserirActionPerformed private void selectCargoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectCargoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_selectCargoActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnAlterar; private javax.swing.JButton btnInserir; private javax.swing.JButton btnNovo; private javax.swing.JButton btnPesquisar; private javax.swing.JButton btnRemover; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel3; private javax.swing.JPanel panelBotoes; private javax.swing.JScrollPane panelTabela; private javax.swing.JComboBox<String> selectCargo; private javax.swing.JTable tabelaCaixas; private javax.swing.JTextField textEmailPessoa; private javax.swing.JTextField textIdPessoa; private javax.swing.JTextField textNomePessoa; private javax.swing.JTextField textSenha; private javax.swing.JTextField textTelefonePessoa; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables }