text
stringlengths
10
2.72M
package sw.server.models; /** * Message model * * @author Lars Kristian * */ public class Message { private final long id; private final long rfid; private final int messageType; private final long timeSent; private final int pulse; private final double temperature; private final double latitude; private final double longitude; public Message(long id, long rfid, int messageType, double latitude, double longitude, int pulse, double temperature) { super(); this.id = id; this.rfid = rfid; this.messageType = messageType; this.pulse = pulse; this.temperature = temperature; this.longitude = longitude; this.latitude = latitude; this.timeSent = System.currentTimeMillis(); } public long getId() { return id; } public long getRfid() { return rfid; } public int getMessageType() { return messageType; } public long getTimeSent() { return timeSent; } public int getPulse() { return pulse; } public double getTemperature() { return temperature; } public double getLongitude() { return longitude; } public double getLatitude() { return latitude; } }
package com.apprisingsoftware.xmasrogue.io; import asciiPanel.AsciiPanel; import com.apprisingsoftware.xmasrogue.ChristmasRogue; import com.apprisingsoftware.xmasrogue.util.Coord; import java.awt.Color; import java.awt.event.KeyEvent; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; public class MainMenuScreen extends MenuScreen implements NestedInputAcceptingAsciiScreen { public MainMenuScreen(int width, int height) { super(width, height, new HashMap<Coord, Message>() {{ char[] title = {(char)17,' ',' ','M','E','R','R','Y',' ','C','H','R','I','S','T','M','A','S',' ',' ',(char)16}; for (int i=0; i<title.length; i++) { put(new Coord((width - title.length) / 2 + i, 3), new Message(String.valueOf(title[i]), i%2==0 ? Color.RED : Color.GREEN)); } String[] story = { "It's Christmas Eve and almost time for Santa Claus to give out presents. All is ready for tomorrow...", "But wait! Santa's sleigh is gone! Nailed to the door (how inconsiderate -- it was just recently polished!)", "reads a note:", "", " Dear Mr. Claus,", " We, the Foundation for the Promotion of Monstrous Rights and Privileges, believe that your", " 'gift-giving' operation is blatantly discriminatory against our constituency. Last year, not a single", " corrupt elf or vampire bat received a present despite the fact that your extensive operation could", " clearly support their inclusion. We feel that your official statement on the issue, involving such", " subjective and easily biased terms as 'naughty' and 'nice', is completely unsatisfactory.", " Since your prejudicial pandering to the human bloc has made it impossible for the FPMRP to seek", " legislation to address our concerns, we have been forced to take more drastic action. You may have", " noticed that your sleigh is missing. It currently resides at the twenty-sixth level of the Dark", " Catacombs. We and our constituency earnestly hope that our actions will render Christmas impossible,", " this year, in support of continued progress toward inter-species equality in the future.", "", " Sincerely,", " Mr. Shamilith, Ancient Karmic Wyrm and President of the FPMRP", "", "Can you help Santa save Christmas in time? (I sure hope so -- I want my presents.)", "", "[n] New Game", }; int maxLen = Arrays.stream(story).mapToInt(String::length).max().getAsInt(); for (int i=0; i<story.length; i++) { put(new Coord((width - maxLen) / 2, 5 + i), new Message(story[i], Color.WHITE)); } }}); } @Override public NestedInputAcceptingAsciiScreen respondToInput(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_N) { ChristmasRogue.setDEBUG(false); return new GameAsciiScreen(width, height, (int) System.currentTimeMillis()); } if (e.getKeyCode() == KeyEvent.VK_W) { ChristmasRogue.setDEBUG(true); return new GameAsciiScreen(width, height, (int) System.currentTimeMillis()); } return null; } @Override protected Color getBackgroundColor(int x, int y) { return AsciiPanel.black; } @Override public Collection<Coord> getUpdatedBackgroundTiles() { return Collections.emptyList(); } }
package board; public class BeanPaging { // 카사딘 // 빼액 private int startPage; private int endPage; private int lastPage; private int currentPage; public int getStartPage() { return startPage; } public void setStartPage(int startPage) { this.startPage = startPage; } public int getEndPage() { return endPage; } public void setEndPage(int endPage) { this.endPage = endPage; } public int getLastPage() { return lastPage; } public void setLastPage(int lastPage) { this.lastPage = lastPage; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } }
package cn.com.ykse.santa.web.form; /** * Created by youyi on 2016/6/1. */ public class IssueSearchRequest { private Long pageNo; private Long pageSize; public Long getPageNo() { return pageNo; } public void setPageNo(Long pageNo) { this.pageNo = pageNo; } public Long getPageSize() { return pageSize; } public void setPageSize(Long pageSize) { this.pageSize = pageSize; } }
package clueGame; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Scanner; import java.util.Set; public class Board { public static final int MAX_BOARD_SIZE = 50; private int numRows; private int numColumns; private BoardCell[][] board = new BoardCell[MAX_BOARD_SIZE][MAX_BOARD_SIZE];; private Map<Character, String> rooms = new HashMap<>(); // map for legend private Map<BoardCell, Set<BoardCell>> adjMatrix = new HashMap<>(); private Set<BoardCell> targets = new HashSet<>(); private Set<BoardCell> visited = new HashSet<>(); private String boardConfigFile; private String roomConfigFile; // variable used for singleton pattern public static Board theInstance = new Board(); // ctor is private to ensure only one can be created private Board() {} // this method returns the only Board public static Board getInstance() { return theInstance; } // This will setup the board/ csv public void initialize() throws FileNotFoundException { // We don't know how big the board is before hand so we have to use // this variable to allocate memory for the board try{ loadBoardConfig(); loadRoomConfig(); } catch (BadConfigFormatException e) { e.fillInStackTrace(); } // This will set up the adjmatrix calcAdjacencies(); return; } // load in the legend public void loadBoardConfig() throws FileNotFoundException { FileReader reader = new FileReader(roomConfigFile); Scanner legend = new Scanner(reader); while (legend.hasNextLine()) { String ln = legend.nextLine(); String[] a = ln.split(","); rooms.put(a[0].charAt(0), a[1].substring(1)); } legend.close(); return; } public void loadRoomConfig() throws FileNotFoundException, BadConfigFormatException { FileReader csv = new FileReader(boardConfigFile); Scanner line = new Scanner(csv); int i = 0; //This will be what we use to store our max row values as while (line.hasNextLine()) { int j = 0; //This is what we will use to store our max column String ln = line.nextLine(); String[] a = ln.split(","); // We will go through our array of strings and place them into our board for (String k :a) { // NOTE: we have to see if the string has two characters in it if (!rooms.containsKey(k.charAt(0))) { throw new BadConfigFormatException(k); } if (k.length() == 2) { String k1 = String.valueOf(k.charAt(1)); switch (k1) { case "U": board[i][j] = new BoardCell(i, j, k.charAt(0), DoorDirection.UP); break; case "D": board[i][j] = new BoardCell(i, j, k.charAt(0), DoorDirection.DOWN); break; case "R": board[i][j] = new BoardCell(i, j, k.charAt(0), DoorDirection.RIGHT); break; case "L": board[i][j] = new BoardCell(i, j, k.charAt(0), DoorDirection.LEFT); break; case "N": board[i][j] = new BoardCell(i, j, k.charAt(0), DoorDirection.NONE); break; } } else { board[i][j] = new BoardCell(i, j, k.charAt(0), DoorDirection.NONE); } ++j; } if(i != 0) { if (numColumns != j) { throw new BadConfigFormatException(); } } else { numColumns = j; } ++i; } numRows = i; } public void calcAdjacencies() { for (int i = 0; i < numRows; ++i) { for (int j = 0; j < numColumns; ++j) { Set<BoardCell> adj = new HashSet<BoardCell>(); // If we are at at a walkway if (board[i][j].getInitial() == 'W') { if (i-1 >= 0 && (board[i-1][j].getInitial() == 'W' || board[i-1][j].getDoorDirection() == DoorDirection.DOWN)) { adj.add(board[i-1][j]); } if (i+1 < numRows && (board[i+1][j].getInitial() == 'W' || board[i+1][j].getDoorDirection() == DoorDirection.UP)) { adj.add(board[i+1][j]); } if (j+1 < numColumns && (board[i][j+1].getInitial() == 'W' || board[i][j+1].getDoorDirection() == DoorDirection.LEFT)) { adj.add(board[i][j+1]); } if (j-1 >= 0 && (board[i][j-1].getInitial() == 'W' || board[i][j-1].getDoorDirection() == DoorDirection.RIGHT)) { adj.add(board[i][j-1]); } } // if we are in a door check were it opens and add that spot else if (board[i][j].getDoorDirection() != DoorDirection.NONE) { if (board[i][j].getDoorDirection() == DoorDirection.UP) { adj.add(board[i-1][j]); } else if (board[i][j].getDoorDirection() == DoorDirection.DOWN) { adj.add(board[i+1][j]); } else if (board[i][j].getDoorDirection() == DoorDirection.RIGHT) { adj.add(board[i][j+1]); } else { adj.add(board[i][j-1]); } } adjMatrix.put(board[i][j], new HashSet<BoardCell>(adj)); adj.clear(); } } return; } public void calcTargets(BoardCell startCell, int pathLength) { visited.add(startCell); for (BoardCell i: adjMatrix.get(startCell)) { if (!visited.contains(i)) { visited.add(i); if (pathLength == 1 || i.getDoorDirection() != DoorDirection.NONE) { targets.add(i); visited.remove(i); } else { calcTargets(i, pathLength-1); } } } visited.remove(startCell); return; } public void calcTargets(int row, int col, int length) { calcTargets(board[row][col], length); } public BoardCell getCellAt(int i, int j) { return board[i][j]; } public void setConfigFiles(String string, String string2) { boardConfigFile = string; roomConfigFile = string2; } // These are the getters which will be used for the tests and mabye other things down the line public int getNumRows() { return numRows; } public int getNumColumns() { return numColumns; } public Map<Character, String> getLegend() { return rooms; } public Map<BoardCell, Set<BoardCell>> getAdjMatrix() { return adjMatrix; } public Set<BoardCell> getTargets() { // We are never cleaning our targets set so i'm adding them to a new set and cleaning the old set Set<BoardCell> currTargets = new HashSet<>(targets); targets = new HashSet<BoardCell>(); return currTargets; } public BoardCell[][] getBoard() { return board; } public void numRows() { return; } public Set<BoardCell> getAdjList(BoardCell cell) { return adjMatrix.get(cell); } public Set<BoardCell> getAdjList(int row, int col) { return adjMatrix.get(board[row][col]); } public BoardCell getCell(int row, int col) { return board[row][col]; } }
package me.minijaws.Ponify; import java.util.HashMap; import java.util.logging.Logger; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class Ponify extends JavaPlugin{ private final PonifyPlayerListener playerListener = new PonifyPlayerListener(this); public static HashMap <Player,String> pinfo = new HashMap <Player,String>(); Logger log = Logger.getLogger("Minecraft"); public void onEnable(){ log.info("ponify starting"); PluginManager pm = this.getServer().getPluginManager(); //pm.registerEvent(Event.Type.PLAYER_DROP_ITEM, playerListener, Event.Priority.High, this); pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Event.Priority.High, this); } public void onDisable(){ log.info("ponify to the moon!!!"); } }
package exer; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; public class TCPTest { public static void main(String[] args) throws IOException { InetAddress address = InetAddress.getByName("192.168.11.68"); Socket socket = new Socket(address,9091); OutputStream os = socket.getOutputStream(); FileInputStream fis = new FileInputStream("a.jpg"); byte[] buffer = new byte[1024]; int len; while((len = fis.read(buffer)) != -1){ os.write(buffer,0,len); } os.flush(); socket.shutdownOutput(); InputStream is = socket.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[10]; int len1; while((len1 = is.read(b)) != -1){ baos.write(b, 0, len1); } System.out.println(baos.toString()); is.close(); baos.close(); os.close(); fis.close(); socket.close(); } }
package com.supconit.kqfx.web.analysis.controllers; import hc.base.domains.AjaxMessage; import hc.business.dic.entities.Data; import hc.business.dic.services.DataDictionaryService; import hc.mvc.annotations.FormBean; import hc.safety.manager.SafetyManager; import java.io.IOException; import java.io.OutputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import jodd.util.StringUtil; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.util.Region; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.CollectionUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.supconit.kqfx.web.analysis.entities.CarModel; import com.supconit.kqfx.web.analysis.entities.JgZcd; import com.supconit.kqfx.web.analysis.services.CarModelService; import com.supconit.kqfx.web.analysis.services.JgZcdService; import com.supconit.kqfx.web.util.DateUtil; import com.supconit.kqfx.web.util.OperateType; import com.supconit.kqfx.web.util.UtilTool; import com.supconit.kqfx.web.xtgl.services.SystemLogService; /** * 行车车型统计 * * @author cjm * */ @RequestMapping("/analysis/cartype") @Controller("analysis_cartype_controller") public class CarTypeAnalysisController { private transient static final Logger logger = LoggerFactory .getLogger(CarTypeAnalysisController.class); private static final String MENU_CODE = "BRIDGE_DAY_ANALYSIS"; private static final String DIC_CAR_TYPE = "FXZF_CAR_MODEL"; private static final String DIC_DETECT = "STATIONNAME"; @Autowired private CarModelService carModelService; @Autowired private DataDictionaryService dataDictionaryService; @Autowired private JgZcdService jgZcdService; @Autowired private SafetyManager safetyManager; @Resource private HttpServletRequest request; @Autowired private SystemLogService systemLogService; @RequestMapping(value = "list", method = RequestMethod.GET) public String list(ModelMap model) { List<JgZcd> zcdList = this.jgZcdService.getZcdListByAuth(); Calendar cal = Calendar.getInstance(); cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE), 0, 0, 0); cal.add(Calendar.DATE, -1); model.put("begindate", DateUtil.formatDate(cal.getTime(), DateUtil.DATE_FORMAT_YYYYMMDD)); model.put("zcdList", zcdList); this.systemLogService.log(MENU_CODE, OperateType.query.getCode(), "按车型统计列表", request.getRemoteAddr()); return "analysis/cartype/list"; } /** * * @param condition * @return */ @ResponseBody @RequestMapping("getchartdata") public AjaxMessage getChartData( @FormBean(value = "condition", modelCode = "prepareCarModel") CarModel condition) { try { CarModel condition2 = this.translateCondition(condition); // 是否选择日期没有选择查看昨天数据信息 List<CarModel> carModels = this.getListByCondition(condition2); // 设置legend String[] legend = { "2轴", "3轴", "4轴", "5轴", "6轴", "6轴以上" }; Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("yAis", carModels); resultMap.put("legend", legend); this.systemLogService.log(MENU_CODE, OperateType.query.getCode(), "按车型统计查询图表数据", request.getRemoteAddr()); return AjaxMessage.success(resultMap); } catch (Exception e) { e.printStackTrace(); return AjaxMessage.success(e.toString()); } } /** * 导出Excel * @param request * @param response * @param condition */ @RequestMapping(value = "export", method = RequestMethod.GET) public void exportAll( HttpServletRequest request, HttpServletResponse response, @FormBean(value = "condition", modelCode = "prepareCarModel") CarModel condition) { // 是否选择日期没有选择查看昨天数据信息 try { CarModel condition2 = this.translateCondition(condition); List<CarModel> carModels = this.getListByCondition(condition2); if(!CollectionUtils.isEmpty(carModels)){ OutputStream out = null; String title = "按车型统计记录_"+DateUtil.formatDate(new Date(), DateUtil.DB_TIME_PATTERN)+".xls"; response.setHeader("Content-Disposition", "attachment; filename=" + new String(title.getBytes("GB2312"), "iso8859-1")); response.setContentType("application/msexcel;charset=UTF-8"); out =response.getOutputStream(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet(UtilTool.toGBK("按车型统计")); HSSFRow top = sheet.createRow(0); HSSFRow row = sheet.createRow(1); HSSFCellStyle style1 = workbook.createCellStyle(); HSSFCellStyle style2 = workbook.createCellStyle(); HSSFCellStyle style3 = workbook.createCellStyle(); /** 字体font **/ HSSFFont font1 = workbook.createFont(); font1.setColor(HSSFColor.BLACK.index); font1.setFontHeightInPoints((short) 10); font1.setBoldweight((short) 24); font1.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); HSSFFont font2 = workbook.createFont(); font2.setColor(HSSFColor.BLACK.index); font2.setFontHeightInPoints((short) 10); font2.setBoldweight((short) 24); style1.setFont(font1); style1=setHSSFCellStyle(style1); style1.setFillBackgroundColor(HSSFColor.AQUA.index); style1.setFillForegroundColor(HSSFColor.AQUA.index); style1.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setFont(font2); style2=setHSSFCellStyle(style2); style3.setFont(font1); style3=setHSSFCellStyle(style3); /** 字体居中 **/ style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style3.setAlignment(HSSFCellStyle.ALIGN_CENTER); String[] head = {"轴数","车辆类型","额定核载参数","车长特征参数","百分比"}; for (int i = 0; i < head.length; i++) { HSSFCell cell = top.createCell(i); cell.setCellStyle(style3); } //设置表头样式 top.getSheet().addMergedRegion(new Region(0,(short)0,0,(short)(head.length-1))); HSSFCell celltop = top.createCell(0); top.setHeight((short) (200*4)); celltop.setCellStyle(style3); //获取导出条件 String conditionStr = ""; //日期 if(null!=condition.getBeginDate()||null!=condition.getEndDate()){ if(null!=condition.getBeginDate()){ conditionStr += "统计开始日期:"+DateUtil.formatDate(condition.getBeginDate(), DateUtil.DATE_FORMAT_YYYYMMDD)+"\r\n"; } if(null!=condition.getEndDate()){ conditionStr += "统计截止日期:"+DateUtil.formatDate(condition.getEndDate(), DateUtil.DATE_FORMAT_YYYYMMDD)+"\r\n"; } } //机构ID if(null!=condition2.getDetects()&&condition2.getDetects().length>0) { conditionStr += "统计治超站:"; for (int j = 0; j < condition2.getDetects().length; j++) { Data data = dataDictionaryService.getByDataCode(DIC_DETECT, condition2.getDetects()[j]); conditionStr += null!=data?data.getName():""+","; } } //设置表头内容 celltop.setCellValue("按车型统计 \r\n"+conditionStr); Integer[] colWidth = new Integer[head.length]; for (int i = 0; i < head.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(head[i]); cell.setCellStyle(style1); if(i==2) { colWidth[i] = (head[i].length()+40)*256; }else{ colWidth[i] = (head[i].length()+13)*256; } } CarModel carModel = carModels.get(0); //2轴 if(0!=carModel.getAxisTwo()){ double f = ((double)carModel.getAxisTwo()/carModel.getAxisTotal())*100; BigDecimal b = new BigDecimal(f); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1); HSSFCell cell = row1.createCell(0); cell.setCellValue("2轴"); cell.setCellStyle(style2); HSSFCell cell1 = row1.createCell(1); cell1.setCellValue("小客车或小货车"); cell1.setCellStyle(style2); HSSFCell cell2 = row1.createCell(2); cell2.setCellValue("中小客车:额定座位≤19座;小货车:载质量≤2吨"); cell2.setCellStyle(style2); HSSFCell cell3 = row1.createCell(3); cell3.setCellValue("车长<6m"); cell3.setCellStyle(style2); HSSFCell cell4 = row1.createCell(4); cell4.setCellValue(result+"%"); cell4.setCellStyle(style2); } //3轴 if(0!=carModel.getAxisThree()){ double f = ((double)carModel.getAxisThree()/carModel.getAxisTotal())*100; BigDecimal b = new BigDecimal(f); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1); HSSFCell cell = row1.createCell(0); cell.setCellValue("3轴"); cell.setCellStyle(style2); HSSFCell cell1 = row1.createCell(1); cell1.setCellValue("大货车"); cell1.setCellStyle(style2); HSSFCell cell2 = row1.createCell(2); cell2.setCellValue("大客车:额定座位>19座;中货车:2吨<载质量≤7吨"); cell2.setCellStyle(style2); HSSFCell cell3 = row1.createCell(3); cell3.setCellValue("车长<6m"); cell3.setCellStyle(style2); HSSFCell cell4 = row1.createCell(4); cell4.setCellValue(result+"%"); cell4.setCellStyle(style2); } //4轴 if(0!=carModel.getAxisFour()){ double f = ((double)carModel.getAxisFour()/carModel.getAxisTotal())*100; BigDecimal b = new BigDecimal(f); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1); HSSFCell cell = row1.createCell(0); cell.setCellValue("4轴"); cell.setCellStyle(style2); HSSFCell cell1 = row1.createCell(1); cell1.setCellValue("大货车"); cell1.setCellStyle(style2); HSSFCell cell2 = row1.createCell(2); cell2.setCellValue("7吨<载质量≤20吨"); cell2.setCellStyle(style2); HSSFCell cell3 = row1.createCell(3); cell3.setCellValue("6m≤车长≤12m"); cell3.setCellStyle(style2); HSSFCell cell4 = row1.createCell(4); cell4.setCellValue(result+"%"); cell4.setCellStyle(style2); } //5轴 if(0!=carModel.getAxisFive()){ double f = ((double)carModel.getAxisFive()/carModel.getAxisTotal())*100; BigDecimal b = new BigDecimal(f); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1); HSSFCell cell = row1.createCell(0); cell.setCellValue("5轴"); cell.setCellStyle(style2); HSSFCell cell1 = row1.createCell(1); cell1.setCellValue("特大货车"); cell1.setCellStyle(style2); HSSFCell cell2 = row1.createCell(2); cell2.setCellValue("20吨<载质量"); cell2.setCellStyle(style2); HSSFCell cell3 = row1.createCell(3); cell3.setCellValue("车长>12m"); cell3.setCellStyle(style2); HSSFCell cell4 = row1.createCell(4); cell4.setCellValue(result+"%"); cell4.setCellStyle(style2); } //6轴 if(0!=carModel.getAxisSix()){ double f = ((double)carModel.getAxisSix()/carModel.getAxisTotal())*100; BigDecimal b = new BigDecimal(f); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1); HSSFCell cell = row1.createCell(0); cell.setCellValue("6轴"); cell.setCellStyle(style2); HSSFCell cell1 = row1.createCell(1); cell1.setCellValue("特大货车"); cell1.setCellStyle(style2); HSSFCell cell2 = row1.createCell(2); cell2.setCellValue("20吨<载质量"); cell2.setCellStyle(style2); HSSFCell cell3 = row1.createCell(3); cell3.setCellValue("车长>12m"); cell3.setCellStyle(style2); HSSFCell cell4 = row1.createCell(4); cell4.setCellValue(result+"%"); cell4.setCellStyle(style2); } //6轴以上 if(0!=carModel.getAxisSeven()){ double f = ((double)carModel.getAxisSeven()/carModel.getAxisTotal())*100; BigDecimal b = new BigDecimal(f); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); HSSFRow row1 = sheet.createRow(sheet.getLastRowNum()+1); HSSFCell cell = row1.createCell(0); cell.setCellValue("6轴以上"); cell.setCellStyle(style2); HSSFCell cell1 = row1.createCell(1); cell1.setCellValue("特大货车"); cell1.setCellStyle(style2); HSSFCell cell2 = row1.createCell(2); cell2.setCellValue("20吨<载质量"); cell2.setCellStyle(style2); HSSFCell cell3 = row1.createCell(3); cell3.setCellValue("车长>12m"); cell3.setCellStyle(style2); HSSFCell cell4 = row1.createCell(4); cell4.setCellValue(result+"%"); cell4.setCellStyle(style2); } for (int i = 0; i < colWidth.length; i++) { sheet.setColumnWidth(i,colWidth[i]); } workbook.write(out); out.flush(); out.close(); }else{ logger.info("-------------------------数据结果为空---------------"); } this.systemLogService.log(MENU_CODE, OperateType.query.getCode(), "按车型统计数据导出", request.getRemoteAddr()); } catch (IOException e) { e.printStackTrace(); } } HSSFCellStyle setHSSFCellStyle( HSSFCellStyle style){ style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); return style; } /** * 统计分析查询条件 * * @param condition * @return */ public List<CarModel> getListByCondition(CarModel condition) { List<CarModel> carModels = this.carModelService .AnalysisByCondition(condition); if (!CollectionUtils.isEmpty(carModels)) for (CarModel carModel : carModels) { if (null != carModel) carModel.setAxisTotal(carModel.getAxisTwo() + carModel.getAxisThree() + carModel.getAxisFour() + carModel.getAxisFive() + carModel.getAxisSix() + carModel.getAxisSeven()); } return !CollectionUtils.isEmpty(carModels) && null != carModels.get(0) ? carModels : new ArrayList<CarModel>(); } /** * 将条件中多个治超站转译 * @param condition * @return */ public CarModel translateCondition(CarModel condition){ // 是否选择日期没有选择查看昨天数据信息 List<JgZcd> zcdList = new ArrayList<JgZcd>(); String[] detects = null; // 根据治超站获取对应的机构治超站列表以及查询所需数组 if (!"null".equals(condition.getDetectStation())&&!StringUtil.isEmpty(condition.getDetectStation())) { detects = condition.getDetectStation().split(","); } else { zcdList = this.jgZcdService.getZcdListByAuth(); detects = new String[zcdList.size()]; for (int i = 0; i < zcdList.size(); i++) { detects[i] = zcdList.get(i).getDeteStation(); } } condition.setDetects(detects); return condition; } }
/** * ファイル名 : TVsmSupplierMngNoMapper.java * 作成者 : hung.pd * 作成日時 : 2018/5/31 * Copyright © 2017-2018 TAU Corporation. All Rights Reserved. */ package jp.co.tau.web7.admin.supplier.mappers; import jp.co.tau.web7.admin.supplier.dto.InfoWinBidDTO; import jp.co.tau.web7.admin.supplier.dto.WinningBidDetailDTO; import jp.co.tau.web7.admin.supplier.entity.TVsmSupplierMngNoEntity; import jp.co.tau.web7.admin.supplier.mappers.common.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * <p>クラス名 :TVsmSupplierMngNoMapper</p> * <p>説明 :トラックバス配送料金情報</p> * @author hung.pd * @since 2018/05/31 */ @Mapper public interface TVsmSupplierMngNoMapper extends BaseMapper<TVsmSupplierMngNoEntity> { InfoWinBidDTO findInfoWinBid(WinningBidDetailDTO dto); }
/* * Copyright 2019 iserge. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cleanlogic.rsc4j.format; import com.google.gson.annotations.Expose; import org.cleanlogic.rsc4j.format.enums.SemanticType; import org.cleanlogic.rsc4j.format.enums.TextEncoding; import org.cleanlogic.rsc4j.utils.StringUtils; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * Structure table of values of semantics * * @author Serge Silaev aka iSergio <s.serge.b@gmail.com> */ public class RSCSemantic { /** * Length of semantic record. Constant. */ private static final int LENGTH = 84; /** * Constant unique semantic code */ private int code; /** * Semantic type */ private SemanticType type; /** * Multiple semantic of single object */ private boolean repeat; /** * Service semantic. If true - semantic can use for any objects in classificator */ private boolean service; /** * Semantic name */ private String name = ""; /** * Semantic key */ private String key = ""; /** * Measure unit */ private String unit = ""; /** * Size of semantic field */ private int size; /** * Double precision */ private int precision; /** * Composite second */ private int flag; /** * List of values for semantic */ private List<RSCSemanticValue> values = new ArrayList<>(); // /** // * List default values for semantic // */ // private List<RSCSemanticDefault> defaults = new ArrayList<>(); private final TextEncoding encoding; public RSCSemantic(TextEncoding encoding) { this.encoding = encoding; } public int getLength() { return LENGTH; } public int getCode() { return code; } public SemanticType getType() { return type; } public boolean isRepeat() { return repeat; } public boolean isService() { return service; } public String getName() { return name; } public String getKey() { return key; } public String getUnit() { return unit; } public int getSize() { return size; } public int getPrecision() { return precision; } public int getFlag() { return flag; } // public List<RSCSemanticDefault> getDefaults() { // return defaults; // } public List<RSCSemanticValue> getValues() { return values; } public void read(ByteBuffer buffer, boolean strict) { // Buffer position before begin read int pos = buffer.position(); code = buffer.getInt(); type = SemanticType.fromValue(buffer.getShort()); repeat = (int) buffer.get() == 1; service = (int) buffer.get() == 1; byte[] name = new byte[32]; buffer.get(name); try { this.name = StringUtils.getString(name, encoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] key = new byte[16]; buffer.get(key); try { this.key = StringUtils.getString(key, encoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } byte[] unit = new byte[8]; buffer.get(unit); try { this.unit = StringUtils.getString(unit, encoding); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } size = buffer.getShort(); precision = (int) buffer.get(); flag = (int) buffer.get(); int offsetValues = buffer.getInt(); int countValues = buffer.getInt(); int offsetDefaults = buffer.getInt(); int countDefaults = buffer.getInt(); // Check length and readed data size int _length = buffer.position() - pos; if (this.getLength() != _length) { System.err.println("Something wrong read semantic. Aspect/Actual:" + this.getLength() + "/" + _length); } if (offsetValues > 0 && countValues > 0) { // Move to offset buffer.position(offsetValues); while (countValues > 0) { RSCSemanticValue semanticValue = new RSCSemanticValue(encoding); semanticValue.read(buffer, strict); values.add(semanticValue); countValues--; } } // if (offsetDefaults > 0 && countDefaults > 0) { // // Move to offset // buffer.position(offsetDefaults); // while (countDefaults > 0) { // RSCSemanticDefault semanticDefault = new RSCSemanticDefault(); // semanticDefault.read(buffer, strict); // defaults.add(semanticDefault); // countDefaults--; // } // } // Force set buffer offset to end of semantic record buffer.position(pos + this.getLength()); } }
package ca.mohawk.jdw.shifty.testcompany; /* I, Josh Maione, 000320309 certify that this material is my original work. No other person's work has been used without due acknowledgement. I have not made my work available to anyone else. Module: test-company Developed By: Josh Maione (000320309) */ import ca.mohawk.jdw.shifty.companyapi.model.employee.Employee; import ca.mohawk.jdw.shifty.companyapi.model.shift.Shift; import ca.mohawk.jdw.shifty.companyapi.model.shift.ShiftValidator; import java.time.LocalDate; import java.time.Month; import java.util.Arrays; import java.util.List; public class TestCompanyShiftValidator implements ShiftValidator { private static final List<LocalDate> HOLIDAYS = Arrays.asList( LocalDate.of(0, Month.DECEMBER, 24), LocalDate.of(0, Month.DECEMBER, 25) ); @Override public boolean canOffer(final Employee offeringEmployee, final Shift shift){ final LocalDate date = shift.startTimestamp() .toLocalDateTime() .toLocalDate() .withYear(0); return !HOLIDAYS.contains(date); } @Override public boolean canRequest(final Employee offeringEmployee, final Shift shift, final Employee requestingEmployee){ return offeringEmployee.rank() == requestingEmployee.rank(); } }
package tasks; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Copy { public void copyFile(String sourceFilePath,String destinationFilePath) throws IOException{ //File source = new File(sourceFile); //File dest = new File(destination); // File sourceFile = new File(sourceFilePath); File destinationFile = new File(destinationFilePath); //sourceFile.delete(); FileInputStream fileInputStream = new FileInputStream(sourceFile); FileOutputStream fileOutputStream = new FileOutputStream(destinationFile); int bufferSize; byte[] bufffer = new byte[512]; try { while ((bufferSize = fileInputStream.read(bufffer)) > 0) { fileOutputStream.write(bufffer, 0, bufferSize); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } fileInputStream.close(); fileOutputStream.close(); } }
package com.bbb.composite.product.details.services.client; import java.net.URI; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.Assert; 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.MockitoAnnotations; import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import com.bbb.composite.product.details.dto.CategoryDTO; import com.bbb.core.cache.dto.CacheableDTO; import com.bbb.core.cache.manager.CoreCacheManager; import com.bbb.core.dto.BaseServiceDTO; import com.bbb.core.dto.ServiceStatus; import com.bbb.core.integration.rest.CoreRestTemplate; import com.bbb.core.utils.CoreUtils; @RunWith(MockitoJUnitRunner.class) @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT) @TestPropertySource(locations = "classpath:bootstrap-test_local.properties") public class CategoryIntegrationServiceImplMockTest { @Autowired @InjectMocks CategoryIntegrationServiceImpl categoryIntegrationService = new CategoryIntegrationServiceImpl(); @Mock private CoreRestTemplate asyncRestTemplate; @Mock private LoadBalancerClient loadBalancer; @Mock private CoreCacheManager coreCacheManager; @Spy private IntegrationServiceUtilsImpl integrationServiceUtils; @Mock private CoreUtils coreUtils; private static final ParameterizedTypeReference<BaseServiceDTO<List<CategoryDTO>>> RESPONSE_TYPE = new ParameterizedTypeReference<BaseServiceDTO<List<CategoryDTO>>>() { }; @Before public void setup() { MockitoAnnotations.initMocks(this); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testGetCategories() { String siteId = "siteId_2"; String channel = "web"; List<String> childCategories = new ArrayList<>(); childCategories.add("AA"); childCategories.add("ACD"); childCategories.add("AC"); String key = "category-microservice-siteId-siteId_2-categoryIds-AA-ACD-AC-bbbChannel-web"; String url = "http://local:12331/category/site/{siteId}/category/{categoryId}?channel={bbbChannel}"; List<Object> argsList = new ArrayList<>(3); argsList.add(siteId); argsList.add(childCategories); Mockito.when(coreCacheManager.getFromCacheList(key, CategoryDTO.class)).thenReturn(null); Mockito.when(loadBalancer.choose(Mockito.anyString())).thenReturn(getServiceInstance()); Mockito.when(asyncRestTemplate.exchange(url, HttpMethod.GET, null, RESPONSE_TYPE, CoreUtils.toArray(argsList))) .thenReturn(createDummyData(siteId, childCategories)); List<CategoryDTO> categoryDTOList = categoryIntegrationService.getCategories(channel, siteId, childCategories); Assert.assertNotNull(categoryDTOList); Assert.assertEquals("AA", categoryDTOList.get(0).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(0).getSiteId()); Assert.assertEquals("ACD", categoryDTOList.get(1).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(1).getSiteId()); Assert.assertEquals("AC", categoryDTOList.get(2).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(2).getSiteId()); } @SuppressWarnings({"unchecked" }) @Test public void testGetCategoriesFromCache() { String siteId = "siteId_2"; String channel = null; List<String> childCategories = new ArrayList<>(); childCategories.add("AA"); childCategories.add("ACD"); childCategories.add("AC"); String key = "category-microservice-siteId-siteId_2-categoryIds-AA-ACD-AC"; String url = "http://local:12331/category/site/{siteId}/category/{categoryId}"; List<Object> argsList = new ArrayList<>(3); argsList.add(siteId); argsList.add(childCategories); Mockito.when(coreCacheManager.getFromCacheList(key, CategoryDTO.class)).thenReturn(getDataFromCache(key, siteId, childCategories)); List<CategoryDTO> categoryDTOList = categoryIntegrationService.getCategories(channel, siteId, childCategories); Assert.assertNotNull(categoryDTOList); Assert.assertEquals("AA", categoryDTOList.get(0).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(0).getSiteId()); Assert.assertEquals("ACD", categoryDTOList.get(1).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(1).getSiteId()); Assert.assertEquals("AC", categoryDTOList.get(2).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(2).getSiteId()); } @Test public void testGetCategoriesChannelNull() { String siteId = "siteId_2"; String channel = ""; List<String> childCategories = new ArrayList<>(); childCategories.add("AA"); childCategories.add("ACD"); childCategories.add("AC"); String key = "category-microservice-siteId-siteId_2-categoryIds-AA-ACD-AC"; String url = "http://local:12331/category/site/{siteId}/category/{categoryId}"; List<Object> argsList = new ArrayList<>(3); argsList.add(siteId); argsList.add(childCategories); Mockito.when(coreCacheManager.getFromCacheList(key, CategoryDTO.class)).thenReturn(null); Mockito.when(loadBalancer.choose(Mockito.anyString())).thenReturn(getServiceInstance()); Mockito.when(asyncRestTemplate.exchange(url, HttpMethod.GET, null, RESPONSE_TYPE, CoreUtils.toArray(argsList))) .thenReturn(createDummyData(siteId, childCategories)); List<CategoryDTO> categoryDTOList = categoryIntegrationService.getCategories(channel, siteId, childCategories); Assert.assertNotNull(categoryDTOList); Assert.assertEquals("AA", categoryDTOList.get(0).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(0).getSiteId()); Assert.assertEquals("ACD", categoryDTOList.get(1).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(1).getSiteId()); Assert.assertEquals("AC", categoryDTOList.get(2).getCatalogId()); Assert.assertEquals("siteId_2", categoryDTOList.get(2).getSiteId()); } @SuppressWarnings({ "rawtypes","unchecked" }) private CacheableDTO getDataFromCache(String key,String siteId,List<String> categoryIds){ CacheableDTO cacheData=new CacheableDTO<>(); cacheData.setKey(key); cacheData.setData(getCategoryData(siteId,categoryIds)); return cacheData; } private BaseServiceDTO<List<CategoryDTO>> getCategoryData(String siteId,List<String> categoryIds){ BaseServiceDTO<List<CategoryDTO>> baseServiceDTO = new BaseServiceDTO<>(); baseServiceDTO.setResponseSentTime(Instant.now()); baseServiceDTO.setServiceStatus(ServiceStatus.SUCCESS); baseServiceDTO.setPageSize(1); baseServiceDTO.setPageFrom(1); baseServiceDTO.setPageTo(1); List<CategoryDTO> categoryDTOs = new ArrayList<>(); for (String categories : categoryIds) { CategoryDTO categoryDTO = new CategoryDTO(); categoryDTO.setSiteId(siteId); categoryDTO.setCatalogId(categories); categoryDTOs.add(categoryDTO); } baseServiceDTO.setData(categoryDTOs); return baseServiceDTO; } private ResponseEntity<BaseServiceDTO<List<CategoryDTO>>> createDummyData(String siteId, List<String> categoryIds) { return new ResponseEntity<BaseServiceDTO<List<CategoryDTO>>>(getCategoryData(siteId,categoryIds), HttpStatus.OK); } private ServiceInstance getServiceInstance() { ServiceInstance instance = new ServiceInstance() { @Override public boolean isSecure() { return false; } @Override public URI getUri() { return null; } @Override public String getServiceId() { return null; } @Override public int getPort() { return 12331; } @Override public Map<String, String> getMetadata() { return null; } @Override public String getHost() { return "local"; } }; return instance; } }
package com.zzlz13.zmusic; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.provider.MediaStore; import com.zzlz13.zmusic.bean.Song; import com.zzlz13.zmusic.service.MusicService; import com.zzlz13.zmusic.utils.PlayListHelper; import java.io.File; import java.util.ArrayList; import java.util.WeakHashMap; /** * Created by hjr on 2016/5/18. */ public class MusicPlayer { public static IZmusicService mService = null; private static final WeakHashMap<Context,ServiceBinder> mConnectionMap; static { mConnectionMap = new WeakHashMap<Context,ServiceBinder>(); } /** * 绑定service,并且返回ContextWrapper,也就是连接map的key * */ public static final ServiceToken bindToService(Context context, ServiceConnection callback){ Activity realActivity = ((Activity) context).getParent(); if (realActivity == null){ realActivity = ((Activity) context); } ContextWrapper contextWrapper = new ContextWrapper(realActivity); contextWrapper.startService(new Intent(contextWrapper,MusicService.class)); /** 这里执行了onServiceConnected接口,bind service */ ServiceBinder binder = new ServiceBinder(callback, contextWrapper.getApplicationContext()); if (contextWrapper.bindService(new Intent().setClass(contextWrapper,MusicService.class),binder,Context.BIND_AUTO_CREATE)){ //bind service success,add map mConnectionMap.put(contextWrapper,binder); return new ServiceToken(contextWrapper); } return null; } /** 根据ServiceToken解绑,也就是ConnectionMap的key */ public static void unBindFromService(ServiceToken token){ if (token == null) return; ContextWrapper contextWrapper = token.mContextWrapper; ServiceBinder binder = mConnectionMap.remove(contextWrapper); /** 没有remove成功,return */ if (binder == null) return; contextWrapper.unbindService(binder); if (mConnectionMap.isEmpty()) mService = null; } public static final class ServiceBinder implements ServiceConnection{ private final ServiceConnection mCallback; private final Context mContext; public ServiceBinder(ServiceConnection callback, Context context) { mCallback = callback; mContext = context; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IZmusicService.Stub.asInterface(service); if (mCallback != null){ mCallback.onServiceConnected(name,service); } //TODO init setting } @Override public void onServiceDisconnected(ComponentName name) { if (mCallback != null){ mCallback.onServiceDisconnected(name); } mService = null; } } /** 用对象封装了ContextWrapper */ public static final class ServiceToken{ public ContextWrapper mContextWrapper; public ServiceToken(ContextWrapper contextWrapper) { mContextWrapper = contextWrapper; } } public static long getDuration(){ try { return mService.duration(); } catch (RemoteException e) { e.printStackTrace(); } return 0; } public static String getTitle(){ try { return mService.title(); } catch (RemoteException e) { e.printStackTrace(); } return ""; } public static String getArtist(){ try { return mService.artist(); } catch (RemoteException e) { e.printStackTrace(); } return ""; } public static int getPlayMode(){ try { return mService.getPlayMode(); } catch (RemoteException e) { e.printStackTrace(); } return Constants.NORMAL_PLAY_MODE; } public static void setPlayMode(int mode){ try { mService.setPlayMode(mode); } catch (RemoteException e) { e.printStackTrace(); } } public static String getCoverPath(){ try { return mService.coverPath(); } catch (RemoteException e) { e.printStackTrace(); } return null; } public static String getMusicPath(){ try { return mService.musicPath(); } catch (RemoteException e) { e.printStackTrace(); } return null; } public static long getPosition(){ try { return mService.position(); } catch (RemoteException e) { e.printStackTrace(); } return 0; } public static boolean seekTo(long where){ try { mService.seek(where); return true; } catch (RemoteException e) { e.printStackTrace(); return false; } } public static int getPlayState(){ try { return mService.getPlayState(); } catch (RemoteException e) { e.printStackTrace(); } return Constants.ERROR_PLAY; } public static void playOrPause(){ try { mService.palyOrPause(); } catch (RemoteException e) { e.printStackTrace(); } } public static void next(){ try { mService.next(); } catch (RemoteException e) { e.printStackTrace(); } } public static void previous(){ try { mService.prev(); } catch (RemoteException e) { e.printStackTrace(); } } public static void playAll(Context context,ArrayList<Song> list, String id,int type,String albumname){ if (list == null || list.size() == 0 || mService == null) return; try{ PlayListHelper.savePlayListBeforeEqual(context, list, type, albumname); for (Song song : list) { if (id.equals(song._id)){ mService.play(song.musicPath); } } }catch (Exception e){ e.printStackTrace(); } } /** * 删除音乐 * @param context * @param delPath * @param completeDel 彻底删除 */ public static void deleteMusic(Context context, String delPath,boolean completeDel) { if (completeDel){ File file = new File(delPath); if (file.exists()){ file.delete(); } } context.getContentResolver().delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, MediaStore.Audio.Media.DATA + " = '" + delPath + "'", null); } }
package com.tencent.mm.plugin.fts.b; import com.tencent.mm.plugin.fts.b.a.u; import com.tencent.mm.sdk.platformtools.al.a; class a$8 implements a { final /* synthetic */ a jtJ; a$8(a aVar) { this.jtJ = aVar; } public final boolean vD() { a.e(this.jtJ).a(131093, new u(this.jtJ, (byte) 0)); return false; } public final String toString() { return super.toString() + "|atOnceIndexTimer"; } }
package com.foosbot.service.handlers; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(value = { "valid" }) public interface Validates { boolean isValid(); }
package com.expense.tracker; import com.opencsv.bean.AbstractBeanField; import com.opencsv.exceptions.CsvConstraintViolationException; import com.opencsv.exceptions.CsvDataTypeMismatchException; public class DoubleConverter extends AbstractBeanField<Double> { @Override protected Double convert(String value) throws CsvDataTypeMismatchException, CsvConstraintViolationException { return Double.parseDouble(value.replace(",", ".")); } }
import java.util.Scanner; public class Main { public static void main(String [] args) { Scanner sc = new Scanner(System.in); // initiate scanner class, name it sc int numbers, sum = 0; // for summing numbers System.out.println("How many numbers do you want to sum? (Enter 5 for this project):"); numbers = sc.nextInt(); // Allow user input for the numbers int all[] = new int[numbers]; System.out.println("Time to enter "+numbers+" numbers:"); System.out.println("--------------------------------------------"); for(int i=0;i<numbers;i++) // keep track of current number { System.out.println("Enter number "+(i+1)+":"); all[i]=sc.nextInt(); } for(int i=0;i<numbers;i++) // keep track of next number { sum+=all[i]; } // Print results System.out.println("--------------------------------------------"); System.out.println("The sum of all "+numbers+" numbers is: "+sum+"."); } }
/** * Copyright &copy; 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved. */ package com.beiyelin.account.entity; import com.beiyelin.commonsql.jpa.BaseDomainEntity; import com.beiyelin.commonsql.jpa.MasterDataEntity; import lombok.*; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import java.util.HashMap; import java.util.List; import static com.beiyelin.commonsql.constant.Repository.NAME_LENGTH; /** * 角色Entity * @author Newmann HU * @Date 2018-1-3 */ @Data @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode(callSuper=true) @Entity @Table(name = Role.TABLE_NAME) public class Role extends MasterDataEntity { public static final String TABLE_NAME= "s_role"; private static final long serialVersionUID = 1L; /** * 角色名称 */ @Column(unique = true,length = NAME_LENGTH) private String name; // @Column(nullable = false) // private int status; /** * 拥有哪些权限 */ // @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE }, fetch = FetchType.EAGER)//todo 方便测试,设为立即载入,fetch = FetchType.LAZY // @JoinTable(name = "s_role_permission", // joinColumns = { @JoinColumn(name = "role_id") }, // inverseJoinColumns = {@JoinColumn(name = "permission_id") }) @Transient private List<Permission> permissionList; /** * 拥有哪些账户 */ @Transient private List<Account> accountList; // /** // * 拥有哪些账户 // */ // @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE }, fetch = FetchType.EAGER)//todo 方便测试,设为立即载入,fetch = FetchType.LAZY // @JoinTable(name = "s_role_account", // joinColumns = { @JoinColumn(name = "role_id") }, // inverseJoinColumns = { @JoinColumn(name = "account_id") }) // private Set<Account> accounts = new HashSet<Account>(0); }
package rotation; public class rotation{ public static final int N = 5; int[][] matrix = new int[N][N]; public rotation (int[][] m){ for(int i = 0;i<N;i++){ for(int j = 0;j<N;j++){ matrix[i][j] = m[i][j]; } } } public int[][] rotation(){ int[] temp = new int[N]; int layer = N/2; int offset = 0; for(int i = 0;i<layer;i++){ for(int j = offset;j< N-offset;j++){ temp[j] = matrix[i][j]; } for(int j = offset;j< N-offset;j++){ matrix[i][j] = matrix[N-j-1][i]; } for(int j = offset;j< N-offset;j++){ matrix[j][i] = matrix[N-i-1][j]; } for(int j = offset;j< N-offset;j++){ matrix[N-i-1][j] = matrix[N -1-j][N-i-1]; } for(int j = offset;j< N-offset;j++){ matrix[j][N-i-1] = temp[j]; } offset++; } return matrix; } public static void main(String[] str){ int[][] m = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}}; rotation test = new rotation(m); int[][] result = test.rotation(); System.out.println("The result after compression is:"); for(int i = 0;i< N;i++){ for(int j = 0;j<N;j++){ System.out.println(result[i][j]); } System.out.println(); } } }
import java.util.*; class while2_Test { public static void main(String ar[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int n2 = sc.nextInt(); int i = 0; while (n<=n2) { if(n%5==0) { i++; } n++; } System.out.println("5의 배수의 개수 : " +i); } }
package edu.iss.caps.service; import java.util.ArrayList; import edu.iss.caps.exception.FailedAuthentication; import edu.iss.caps.model.User; public interface UserService { User findUser(String userId); ArrayList<User> findAllUsers(); User authenticate(String userId, String password) throws FailedAuthentication; User createUser(User user); User changeUser(User user); void removeUser(User user); }
package duke.exception; public class DukeException extends Exception { DukeException() { } }
package client.views.mainComponents; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; public class BottomRightPane { private JScrollPane fieldHelpScrollPane; private JTabbedPane tabbedPane; public BottomRightPane() { fieldHelpScrollPane = new JScrollPane(); tabbedPane = new JTabbedPane(); tabbedPane.addTab("Field Help", fieldHelpScrollPane); tabbedPane.addTab("Image Navigation", new JLabel("Image Navigation")); } /** * @return the fieldHelpScrollPane */ public JScrollPane getFieldHelpScrollPane() { return fieldHelpScrollPane; } /** * @return the tabbedPane */ public JTabbedPane getTabbedPane() { return tabbedPane; } }
package com.cxjd.nvwabao.bean; import org.litepal.crud.DataSupport; import java.io.Serializable; /** * 项目名: NvWaBao2 * 包名: com.cxjd.nvwabao.bean * 文件名: PingLunPeople * 创建者: LC * 创建时间: 2018/4/1 21:11 * 描述: TODO */ public class PingLunPeople extends DataSupport implements Serializable { private String name; private String data; private String pingLun; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getPingLun() { return pingLun; } public void setPingLun(String pingLun) { this.pingLun = pingLun; } }
package com.java.smart_garage.contracts.repoContracts; import com.java.smart_garage.models.City; import java.util.List; public interface CityRepository { List<City> getAllCityIndex(); }
package designpattern.singleton; /** * Created by john(Zhewei) on 2016/12/14. */ public class InnerSingleton { private InnerSingleton(){ } private static class InstanceHolder { private static InnerSingleton instance = new InnerSingleton(); } //饿汉的变形,让其实现了延迟加载,并能保证多线程下单例 public static InnerSingleton getInstance() { return InstanceHolder.instance; } }
package quartz; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobListener; /** * @author malf * @description TODO * @project how2jStudy * @since 2020/11/7 */ public class MailJobListener implements JobListener { @Override public String getName() { return "listener of mail job"; } @Override public void jobToBeExecuted(JobExecutionContext jobExecutionContext) { System.out.println("准备执行:\t " + jobExecutionContext.getJobDetail().getKey()); } @Override public void jobExecutionVetoed(JobExecutionContext jobExecutionContext) { System.out.println("取消执行:\t " + jobExecutionContext.getJobDetail().getKey()); } @Override public void jobWasExecuted(JobExecutionContext jobExecutionContext, JobExecutionException e) { System.out.println("执行结束:\t " + jobExecutionContext.getJobDetail().getKey()); System.out.println(); } }
package com.argentinatecno.checkmanager.main.fragment_reports.di; import com.argentinatecno.checkmanager.CheckManagerAppModule; import com.argentinatecno.checkmanager.lib.di.LibsModule; import com.argentinatecno.checkmanager.main.fragment_reports.ui.FragmentReport; import javax.inject.Singleton; import dagger.Component; @Singleton @Component(modules = {FragmentReportModule.class, LibsModule.class, CheckManagerAppModule.class}) public interface FragmentReportComponent { void inject(FragmentReport fragment); }
package com.lec.ex04; public interface I1 { public int i1 =1; //final static이기때문에 '상수' public void m1(); }
/* * 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 HP */ public class Session { private static int id = 0; private static String username; private static String email; private static String role; private static String password; public static String getPassword() { return password; } public static void setPassword(String password) { Session.password = password; } private static int id_Lo; public static int getId() { return id; } public static void setId(int id) { Session.id = id; } public static String getUsername() { return username; } public static void setUsername(String username) { Session.username = username; } public static String getEmail() { return email; } public static void setEmail(String email) { Session.email = email; } public static String getRole() { return role; } public static void setRole(String role) { Session.role = role; } public static int getId_Lo() { return id_Lo; } public static void setId_Lo(int id_Lo) { Session.id_Lo = id_Lo; } }
package com.tencent.mm.plugin.backup.bakoldlogic.bakoldpcmodel; import com.tencent.mm.plugin.backup.bakoldlogic.bakoldpcmodel.e.b; public interface e$e extends b { void atd(); }
/* 7. Reverse Integer Given a 32-bit signed integer, reverse digits of an integer. Example 1: Input: 123 Output: 321 Example 2: Input: -123 Output: -321 Example 3: Input: 120 Output: 21 */ package leetcode_math; public class Question_7 { public int reverse(int x) { int result = 0; while(x != 0) { int newResult = result * 10 + x % 10; if ((newResult - x % 10) / 10 != result) { result = 0; break; } result = newResult; x = x/10; } return result; } public void solve() { System.out.println(Integer.MAX_VALUE); System.out.println(reverse(123)); } }
package practice; import java.util.Scanner; public class SalesTax { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.println("enter the price"); int price=input.nextInt(); System.out.println("you entered the price "+price); float tax=10*price/100; float newprice=price+tax; System.out.println("appropriate tax = "+tax); System.out.println("total purchase price = "+newprice); } }
package com.google.android.exoplayer2.a; import android.annotation.TargetApi; import android.media.AudioTrack; import android.media.MediaCodec; import android.media.MediaCrypto; import android.media.MediaFormat; import android.os.Handler; import com.google.android.exoplayer2.Format; import com.google.android.exoplayer2.a.e$a.1; import com.google.android.exoplayer2.a.e$a.2; import com.google.android.exoplayer2.a.e$a.3; import com.google.android.exoplayer2.drm.d; import com.google.android.exoplayer2.e; import com.google.android.exoplayer2.e.a; import com.google.android.exoplayer2.e.b; import com.google.android.exoplayer2.e.c; import com.google.android.exoplayer2.i.f; import com.google.android.exoplayer2.i.t; import com.google.android.exoplayer2.p; import java.util.Arrays; @TargetApi(16) public final class i extends b implements f { private int aeg; private int aeh; private final e$a ahm; private final f ahn; private boolean aho; private boolean ahp; private MediaFormat ahq; private long ahr; private boolean ahs; public i(c cVar, com.google.android.exoplayer2.drm.b<d> bVar, Handler handler, e eVar, c cVar2, d... dVarArr) { super(1, cVar, bVar, true); this.ahn = new f(cVar2, dVarArr, new a(this, (byte) 0)); this.ahm = new e$a(handler, eVar); } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ protected final int a(com.google.android.exoplayer2.e.c r11, com.google.android.exoplayer2.Format r12) { /* r10 = this; r6 = 21; r7 = -1; r3 = 1; r1 = 0; r2 = r12.adW; r0 = com.google.android.exoplayer2.i.g.at(r2); if (r0 != 0) goto L_0x000e; L_0x000d: return r1; L_0x000e: r0 = com.google.android.exoplayer2.i.t.SDK_INT; if (r0 < r6) goto L_0x0025; L_0x0012: r0 = 32; L_0x0014: r4 = r10.ah(r2); if (r4 == 0) goto L_0x0027; L_0x001a: r4 = r11.kp(); if (r4 == 0) goto L_0x0027; L_0x0020: r0 = r0 | 8; r1 = r0 | 4; goto L_0x000d; L_0x0025: r0 = r1; goto L_0x0014; L_0x0027: r5 = r11.d(r2, r1); if (r5 != 0) goto L_0x002f; L_0x002d: r1 = r3; goto L_0x000d; L_0x002f: r2 = com.google.android.exoplayer2.i.t.SDK_INT; if (r2 < r6) goto L_0x0059; L_0x0033: r2 = r12.sampleRate; if (r2 == r7) goto L_0x0046; L_0x0037: r2 = r12.sampleRate; r4 = r5.aps; if (r4 != 0) goto L_0x0061; L_0x003d: r2 = "sampleRate.caps"; r5.aj(r2); r2 = r1; L_0x0044: if (r2 == 0) goto L_0x005a; L_0x0046: r2 = r12.aeg; if (r2 == r7) goto L_0x0059; L_0x004a: r6 = r12.aeg; r2 = r5.aps; if (r2 != 0) goto L_0x008e; L_0x0050: r2 = "channelCount.caps"; r5.aj(r2); r2 = r1; L_0x0057: if (r2 == 0) goto L_0x005a; L_0x0059: r1 = r3; L_0x005a: if (r1 == 0) goto L_0x0173; L_0x005c: r1 = 4; L_0x005d: r0 = r0 | 8; r1 = r1 | r0; goto L_0x000d; L_0x0061: r4 = r5.aps; r4 = r4.getAudioCapabilities(); if (r4 != 0) goto L_0x0071; L_0x0069: r2 = "sampleRate.aCaps"; r5.aj(r2); r2 = r1; goto L_0x0044; L_0x0071: r4 = r4.isSampleRateSupported(r2); if (r4 != 0) goto L_0x008c; L_0x0077: r4 = new java.lang.StringBuilder; r6 = "sampleRate.support, "; r4.<init>(r6); r2 = r4.append(r2); r2 = r2.toString(); r5.aj(r2); r2 = r1; goto L_0x0044; L_0x008c: r2 = r3; goto L_0x0044; L_0x008e: r2 = r5.aps; r2 = r2.getAudioCapabilities(); if (r2 != 0) goto L_0x009e; L_0x0096: r2 = "channelCount.aCaps"; r5.aj(r2); r2 = r1; goto L_0x0057; L_0x009e: r7 = r5.name; r8 = r5.mimeType; r4 = r2.getMaxInputChannelCount(); if (r4 > r3) goto L_0x00b0; L_0x00a8: r2 = com.google.android.exoplayer2.i.t.SDK_INT; r9 = 26; if (r2 < r9) goto L_0x00c8; L_0x00ae: if (r4 <= 0) goto L_0x00c8; L_0x00b0: r2 = r4; L_0x00b1: if (r2 >= r6) goto L_0x0170; L_0x00b3: r2 = new java.lang.StringBuilder; r4 = "channelCount.support, "; r2.<init>(r4); r2 = r2.append(r6); r2 = r2.toString(); r5.aj(r2); r2 = r1; goto L_0x0057; L_0x00c8: r2 = "audio/mpeg"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x00d1: r2 = "audio/3gpp"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x00da: r2 = "audio/amr-wb"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x00e3: r2 = "audio/mp4a-latm"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x00ec: r2 = "audio/vorbis"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x00f5: r2 = "audio/opus"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x00fe: r2 = "audio/raw"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x0107: r2 = "audio/flac"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x0110: r2 = "audio/g711-alaw"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x0119: r2 = "audio/g711-mlaw"; r2 = r2.equals(r8); if (r2 != 0) goto L_0x012b; L_0x0122: r2 = "audio/gsm"; r2 = r2.equals(r8); if (r2 == 0) goto L_0x012d; L_0x012b: r2 = r4; goto L_0x00b1; L_0x012d: r2 = "audio/ac3"; r2 = r2.equals(r8); if (r2 == 0) goto L_0x0161; L_0x0136: r2 = 6; L_0x0137: r8 = new java.lang.StringBuilder; r9 = "AssumedMaxChannelAdjustment: "; r8.<init>(r9); r7 = r8.append(r7); r8 = ", ["; r7 = r7.append(r8); r4 = r7.append(r4); r7 = " to "; r4 = r4.append(r7); r4 = r4.append(r2); r7 = "]"; r4.append(r7); goto L_0x00b1; L_0x0161: r2 = "audio/eac3"; r2 = r2.equals(r8); if (r2 == 0) goto L_0x016d; L_0x016a: r2 = 16; goto L_0x0137; L_0x016d: r2 = 30; goto L_0x0137; L_0x0170: r2 = r3; goto L_0x0057; L_0x0173: r1 = 3; goto L_0x005d; */ throw new UnsupportedOperationException("Method not decompiled: com.google.android.exoplayer2.a.i.a(com.google.android.exoplayer2.e.c, com.google.android.exoplayer2.Format):int"); } protected final a a(c cVar, Format format, boolean z) { if (ah(format.adW)) { a kp = cVar.kp(); if (kp != null) { this.aho = true; return kp; } } this.aho = false; return super.a(cVar, format, z); } private boolean ah(String str) { f fVar = this.ahn; if (fVar.afQ != null) { if (Arrays.binarySearch(fVar.afQ.afz, f.ag(str)) >= 0) { return true; } } return false; } protected final void a(a aVar, MediaCodec mediaCodec, Format format, MediaCrypto mediaCrypto) { boolean z = t.SDK_INT < 24 && "OMX.SEC.aac.dec".equals(aVar.name) && "samsung".equals(t.MANUFACTURER) && (t.DEVICE.startsWith("zeroflte") || t.DEVICE.startsWith("herolte") || t.DEVICE.startsWith("heroqlte")); this.ahp = z; if (this.aho) { this.ahq = format.iQ(); this.ahq.setString("mime", "audio/raw"); mediaCodec.configure(this.ahq, null, mediaCrypto, 0); this.ahq.setString("mime", format.adW); return; } mediaCodec.configure(format.iQ(), null, mediaCrypto, 0); this.ahq = null; } public final f iq() { return this; } protected final void c(String str, long j, long j2) { e$a e_a = this.ahm; if (e_a.afC != null) { e_a.handler.post(new 2(e_a, str, j, j2)); } } protected final void e(Format format) { super.e(format); e$a e_a = this.ahm; if (e_a.afC != null) { e_a.handler.post(new 3(e_a, format)); } this.aeh = "audio/raw".equals(format.adW) ? format.aeh : 2; this.aeg = format.aeg; } protected final void onOutputFormatChanged(MediaCodec mediaCodec, MediaFormat mediaFormat) { int i; int[] iArr; Object obj = this.ahq != null ? 1 : null; String string = obj != null ? this.ahq.getString("mime") : "audio/raw"; if (obj != null) { mediaFormat = this.ahq; } int integer = mediaFormat.getInteger("channel-count"); int integer2 = mediaFormat.getInteger("sample-rate"); if (this.ahp && integer == 6 && this.aeg < 6) { int[] iArr2 = new int[this.aeg]; for (i = 0; i < this.aeg; i++) { iArr2[i] = i; } iArr = iArr2; } else { iArr = null; } try { int i2; f fVar = this.ahn; i = this.aeh; boolean z = !"audio/raw".equals(string); int ag = z ? f.ag(string) : i; int i3 = 0; if (z) { i2 = 0; } else { fVar.agr = t.ax(i, integer); fVar.afR.ahf = iArr; i = integer; for (d dVar : fVar.afT) { i3 |= dVar.r(integer2, i, ag); if (dVar.isActive()) { i = dVar.iY(); ag = dVar.iZ(); } } if (i3 != 0) { fVar.jc(); } i2 = i3; integer = i; } switch (integer) { case 1: i = 4; break; case 2: i = 12; break; case 3: i = 28; break; case 4: i = 204; break; case 5: i = 220; break; case 6: i = 252; break; case 7: i = 1276; break; case 8: i = com.google.android.exoplayer2.b.CHANNEL_OUT_7POINT1_SURROUND; break; default: throw new f.c("Unsupported channel count: " + integer); } if (t.SDK_INT <= 23 && "foster".equals(t.DEVICE) && "NVIDIA".equals(t.MANUFACTURER)) { switch (integer) { case 3: case 5: i = 252; break; case 7: i = com.google.android.exoplayer2.b.CHANNEL_OUT_7POINT1_SURROUND; break; } } i3 = (t.SDK_INT <= 25 && "fugu".equals(t.DEVICE) && z && integer == 1) ? 12 : i; if (i2 != 0 || !fVar.isInitialized() || fVar.encoding != ag || fVar.sampleRate != integer2 || fVar.agb != i3) { f fVar2; fVar.reset(); fVar.encoding = ag; fVar.agd = z; fVar.sampleRate = integer2; fVar.agb = i3; fVar.agc = z ? ag : 2; fVar.agu = t.ax(2, integer); if (!z) { ag = AudioTrack.getMinBufferSize(integer2, i3, fVar.agc); com.google.android.exoplayer2.i.a.ap(ag != -2); i3 = ag * 4; i = ((int) fVar.A(250000)) * fVar.agu; ag = (int) Math.max((long) ag, fVar.A(750000) * ((long) fVar.agu)); if (i3 < i) { fVar2 = fVar; } else if (i3 > ag) { i = ag; fVar2 = fVar; } else { i = i3; fVar2 = fVar; } } else if (fVar.agc == 5 || fVar.agc == 6) { i = 20480; fVar2 = fVar; } else { i = 49152; fVar2 = fVar; } fVar2.bufferSize = i; fVar.age = z ? -9223372036854775807L : fVar.z((long) (fVar.bufferSize / fVar.agu)); fVar.b(fVar.acY); } } catch (Throwable e) { throw new f.c(e); } catch (f.c e2) { throw e.a(e2, this.index); } } protected static void jr() { } protected static void js() { } protected static void jt() { } protected final void ae(boolean z) { boolean z2 = false; super.ae(z); e$a e_a = this.ahm; com.google.android.exoplayer2.b.d dVar = this.aqc; if (e_a.afC != null) { e_a.handler.post(new 1(e_a, dVar)); } int i = this.acj.aeA; if (i != 0) { f fVar = this.ahn; if (t.SDK_INT >= 21) { z2 = true; } com.google.android.exoplayer2.i.a.ap(z2); if (!fVar.agM || fVar.aeS != i) { fVar.agM = true; fVar.aeS = i; fVar.reset(); return; } return; } f fVar2 = this.ahn; if (fVar2.agM) { fVar2.agM = false; fVar2.aeS = 0; fVar2.reset(); } } protected final void b(long j, boolean z) { super.b(j, z); this.ahn.reset(); this.ahr = j; this.ahs = true; } protected final void onStarted() { super.onStarted(); this.ahn.play(); } protected final void onStopped() { f fVar = this.ahn; fVar.agL = false; if (fVar.isInitialized()) { fVar.jj(); fVar.afX.pause(); } super.onStopped(); } protected final void ix() { try { f fVar = this.ahn; fVar.reset(); fVar.jg(); for (d reset : fVar.afT) { reset.reset(); } fVar.aeS = 0; fVar.agL = false; try { super.ix(); } finally { this.aqc.jC(); this.ahm.e(this.aqc); } } catch (Throwable th) { super.ix(); } finally { this.aqc.jC(); this.ahm.e(this.aqc); } } public final boolean iT() { if (super.iT()) { f fVar = this.ahn; boolean z = !fVar.isInitialized() || (fVar.agK && !fVar.je()); if (z) { return true; } } return false; } public final boolean hv() { return this.ahn.je() || super.hv(); } public final long jn() { long aj = this.ahn.aj(iT()); if (aj != Long.MIN_VALUE) { if (!this.ahs) { aj = Math.max(this.ahr, aj); } this.ahr = aj; this.ahs = false; } return this.ahr; } public final p b(p pVar) { return this.ahn.b(pVar); } public final p ju() { return this.ahn.acY; } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ protected final boolean a(long r12, long r14, android.media.MediaCodec r16, java.nio.ByteBuffer r17, int r18, int r19, long r20, boolean r22) { /* r11 = this; r2 = r11.aho; if (r2 == 0) goto L_0x0012; L_0x0004: r2 = r19 & 2; if (r2 == 0) goto L_0x0012; L_0x0008: r2 = 0; r0 = r16; r1 = r18; r0.releaseOutputBuffer(r1, r2); r2 = 1; L_0x0011: return r2; L_0x0012: if (r22 == 0) goto L_0x0030; L_0x0014: r2 = 0; r0 = r16; r1 = r18; r0.releaseOutputBuffer(r1, r2); r2 = r11.aqc; r3 = r2.aic; r3 = r3 + 1; r2.aic = r3; r2 = r11.ahn; r3 = r2.agy; r4 = 1; if (r3 != r4) goto L_0x002e; L_0x002b: r3 = 2; r2.agy = r3; L_0x002e: r2 = 1; goto L_0x0011; L_0x0030: r10 = r11.ahn; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r10.agF; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x003c; L_0x0036: r2 = r10.agF; Catch:{ d -> 0x01c1, f$h -> 0x021e } r0 = r17; if (r0 != r2) goto L_0x00cd; L_0x003c: r2 = 1; L_0x003d: com.google.android.exoplayer2.i.a.ao(r2); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r10.isInitialized(); Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 != 0) goto L_0x00a5; L_0x0046: r2 = r10.afV; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2.block(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r10.jl(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r10.aga = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r10.aga; Catch:{ d -> 0x01c1, f$h -> 0x021e } r9 = r2.getAudioSessionId(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = com.google.android.exoplayer2.a.f.afO; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x0082; L_0x005b: r2 = com.google.android.exoplayer2.i.t.SDK_INT; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = 21; if (r2 >= r3) goto L_0x0082; L_0x0061: r2 = r10.afZ; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x0070; L_0x0065: r2 = r10.afZ; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2.getAudioSessionId(); Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r9 == r2) goto L_0x0070; L_0x006d: r10.jg(); Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0070: r2 = r10.afZ; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 != 0) goto L_0x0082; L_0x0074: r2 = new android.media.AudioTrack; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = 3; r4 = 4000; // 0xfa0 float:5.605E-42 double:1.9763E-320; r5 = 4; r6 = 2; r7 = 2; r8 = 0; r2.<init>(r3, r4, r5, r6, r7, r8, r9); Catch:{ d -> 0x01c1, f$h -> 0x021e } r10.afZ = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0082: r2 = r10.aeS; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == r9) goto L_0x008d; L_0x0086: r10.aeS = r9; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r10.afU; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2.cb(r9); Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x008d: r2 = r10.afX; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = r10.aga; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = r10.jk(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2.a(r3, r4); Catch:{ d -> 0x01c1, f$h -> 0x021e } r10.jf(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = 0; r10.agN = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r10.agL; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x00a5; L_0x00a2: r10.play(); Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x00a5: r2 = r10.jk(); Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x00e5; L_0x00ab: r2 = r10.aga; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2.getPlayState(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = 2; if (r2 != r3) goto L_0x00d0; L_0x00b4: r2 = 0; r10.agN = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x00b7: r2 = 0; L_0x00b8: if (r2 == 0) goto L_0x0233; L_0x00ba: r2 = 0; r0 = r16; r1 = r18; r0.releaseOutputBuffer(r1, r2); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r11.aqc; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = r2.aib; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = r3 + 1; r2.aib = r3; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = 1; goto L_0x0011; L_0x00cd: r2 = 0; goto L_0x003d; L_0x00d0: r2 = r10.aga; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2.getPlayState(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = 1; if (r2 != r3) goto L_0x00e5; L_0x00d9: r2 = r10.afX; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2.jm(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = 0; r2 = (r2 > r4 ? 1 : (r2 == r4 ? 0 : -1)); if (r2 != 0) goto L_0x00b7; L_0x00e5: r2 = r10.agN; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = r10.je(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r10.agN = r3; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x0111; L_0x00ef: r2 = r10.agN; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 != 0) goto L_0x0111; L_0x00f3: r2 = r10.aga; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2.getPlayState(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = 1; if (r2 == r3) goto L_0x0111; L_0x00fc: r2 = android.os.SystemClock.elapsedRealtime(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = r10.agO; Catch:{ d -> 0x01c1, f$h -> 0x021e } r6 = r2 - r4; r2 = r10.afU; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = r10.bufferSize; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = r10.age; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = com.google.android.exoplayer2.b.n(r4); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2.d(r3, r4, r6); Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0111: r2 = r10.agF; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 != 0) goto L_0x0182; L_0x0115: r2 = r17.hasRemaining(); Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 != 0) goto L_0x011d; L_0x011b: r2 = 1; goto L_0x00b8; L_0x011d: r2 = r10.agd; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x0134; L_0x0121: r2 = r10.agx; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 != 0) goto L_0x0134; L_0x0125: r2 = r10.agc; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = 7; if (r2 == r3) goto L_0x012e; L_0x012a: r3 = 8; if (r2 != r3) goto L_0x019b; L_0x012e: r2 = com.google.android.exoplayer2.a.h.d(r17); Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0132: r10.agx = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0134: r2 = r10.agf; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x0161; L_0x0138: r2 = r10.jd(); Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x00b7; L_0x013e: r9 = r10.afY; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = new com.google.android.exoplayer2.a.f$g; Catch:{ d -> 0x01c1, f$h -> 0x021e } r3 = r10.agf; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = 0; r0 = r20; r4 = java.lang.Math.max(r4, r0); Catch:{ d -> 0x01c1, f$h -> 0x021e } r6 = r10.ji(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r6 = r10.z(r6); Catch:{ d -> 0x01c1, f$h -> 0x021e } r8 = 0; r2.<init>(r3, r4, r6, r8); Catch:{ d -> 0x01c1, f$h -> 0x021e } r9.add(r2); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = 0; r10.agf = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } r10.jc(); Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0161: r2 = r10.agy; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 != 0) goto L_0x01c9; L_0x0165: r2 = 0; r0 = r20; r2 = java.lang.Math.max(r2, r0); Catch:{ d -> 0x01c1, f$h -> 0x021e } r10.agz = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = 1; r10.agy = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0172: r2 = r10.agd; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x0220; L_0x0176: r2 = r10.agt; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = r10.agx; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = (long) r4; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2 + r4; r10.agt = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x017e: r0 = r17; r10.agF = r0; Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0182: r2 = r10.agd; Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 == 0) goto L_0x022c; L_0x0186: r2 = r10.agF; Catch:{ d -> 0x01c1, f$h -> 0x021e } r0 = r20; r10.a(r2, r0); Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x018d: r2 = r10.agF; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2.hasRemaining(); Catch:{ d -> 0x01c1, f$h -> 0x021e } if (r2 != 0) goto L_0x00b7; L_0x0195: r2 = 0; r10.agF = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = 1; goto L_0x00b8; L_0x019b: r3 = 5; if (r2 != r3) goto L_0x01a3; L_0x019e: r2 = com.google.android.exoplayer2.a.a.iX(); Catch:{ d -> 0x01c1, f$h -> 0x021e } goto L_0x0132; L_0x01a3: r3 = 6; if (r2 != r3) goto L_0x01ab; L_0x01a6: r2 = com.google.android.exoplayer2.a.a.b(r17); Catch:{ d -> 0x01c1, f$h -> 0x021e } goto L_0x0132; L_0x01ab: r3 = new java.lang.IllegalStateException; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = new java.lang.StringBuilder; Catch:{ d -> 0x01c1, f$h -> 0x021e } r5 = "Unexpected audio encoding: "; r4.<init>(r5); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r4.append(r2); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2.toString(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r3.<init>(r2); Catch:{ d -> 0x01c1, f$h -> 0x021e } throw r3; Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x01c1: r2 = move-exception; L_0x01c2: r3 = r11.index; r2 = com.google.android.exoplayer2.e.a(r2, r3); throw r2; L_0x01c9: r2 = r10.agz; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = r10.jh(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = r10.z(r4); Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2 + r4; r4 = r10.agy; Catch:{ d -> 0x01c1, f$h -> 0x021e } r5 = 1; if (r4 != r5) goto L_0x0208; L_0x01d9: r4 = r2 - r20; r4 = java.lang.Math.abs(r4); Catch:{ d -> 0x01c1, f$h -> 0x021e } r6 = 200000; // 0x30d40 float:2.8026E-40 double:9.8813E-319; r4 = (r4 > r6 ? 1 : (r4 == r6 ? 0 : -1)); if (r4 <= 0) goto L_0x0208; L_0x01e6: r4 = new java.lang.StringBuilder; Catch:{ d -> 0x01c1, f$h -> 0x021e } r5 = "Discontinuity detected [expected "; r4.<init>(r5); Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = r4.append(r2); Catch:{ d -> 0x01c1, f$h -> 0x021e } r5 = ", got "; r4 = r4.append(r5); Catch:{ d -> 0x01c1, f$h -> 0x021e } r0 = r20; r4 = r4.append(r0); Catch:{ d -> 0x01c1, f$h -> 0x021e } r5 = "]"; r4.append(r5); Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = 2; r10.agy = r4; Catch:{ d -> 0x01c1, f$h -> 0x021e } L_0x0208: r4 = r10.agy; Catch:{ d -> 0x01c1, f$h -> 0x021e } r5 = 2; if (r4 != r5) goto L_0x0172; L_0x020d: r4 = r10.agz; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r20 - r2; r2 = r2 + r4; r10.agz = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = 1; r10.agy = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r10.afU; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2.iS(); Catch:{ d -> 0x01c1, f$h -> 0x021e } goto L_0x0172; L_0x021e: r2 = move-exception; goto L_0x01c2; L_0x0220: r2 = r10.ags; Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = r17.remaining(); Catch:{ d -> 0x01c1, f$h -> 0x021e } r4 = (long) r4; Catch:{ d -> 0x01c1, f$h -> 0x021e } r2 = r2 + r4; r10.ags = r2; Catch:{ d -> 0x01c1, f$h -> 0x021e } goto L_0x017e; L_0x022c: r0 = r20; r10.x(r0); Catch:{ d -> 0x01c1, f$h -> 0x021e } goto L_0x018d; L_0x0233: r2 = 0; goto L_0x0011; */ throw new UnsupportedOperationException("Method not decompiled: com.google.android.exoplayer2.a.i.a(long, long, android.media.MediaCodec, java.nio.ByteBuffer, int, int, long, boolean):boolean"); } protected final void jv() { try { f fVar = this.ahn; if (!fVar.agK && fVar.isInitialized() && fVar.jd()) { fVar.afX.B(fVar.ji()); fVar.agj = 0; fVar.agK = true; } } catch (Exception e) { throw e.a(e, this.index); } } public final void d(int i, Object obj) { f fVar; switch (i) { case 2: fVar = this.ahn; float floatValue = ((Float) obj).floatValue(); if (fVar.agC != floatValue) { fVar.agC = floatValue; fVar.jf(); return; } return; case 3: b bVar = (b) obj; fVar = this.ahn; if (!fVar.aeT.equals(bVar)) { fVar.aeT = bVar; if (!fVar.agM) { fVar.reset(); fVar.aeS = 0; return; } return; } return; default: super.d(i, obj); return; } } }
public class Person { String name; String nationality; int age; public Person(String name, String nationality, int age) { this.name = name; this.nationality = nationality; this.age = age; } }
package pbure; import java.util.Scanner; public class Hometask3 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in) ; System.out.println("Please input a year"); int year; year = sc.nextInt(); if (year%4 == 0 && year%100>0 || year%400 == 0) { System.out.println("Year has 366 days"); } else { System.out.println("Year has 365 days"); } } }
package robotsimulator; public class Bullet { private double x; private double y; private double heading; private double velocity; private double damage; private double radius; private double range; private int counter; public Bullet(double x, double y, double heading, double velocity, double damage, double radius, double range) { this.x = x; this.y = y; this.heading = heading; this.velocity = velocity; this.damage = damage; this.radius = radius; counter = ((int)(range / velocity) + 1); } public double getX() { return x; } public double getY() { return y; } public double getHeading() { return heading; } public double getVelocity() { return velocity; } public double getDamage() { return damage; } public double getRadius() { return radius; } public boolean isDestroyed() { return counter < 1; } public void step() { x += velocity * Math.cos(heading); y += velocity * Math.sin(heading); counter -= 1; } }
package com.example.ahmed.octopusmart.Dialog.GenricDialogFragment; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.ahmed.octopusmart.R; import java.util.ArrayList; public abstract class GenricDialogArrayAdapter<T> extends RecyclerView.Adapter<GenricDialogArrayAdapter.ViewHolder>{ // Vars private LayoutInflater mInflater; ArrayList<T> list ; public GenricDialogArrayAdapter(Context context, ArrayList<T> objects) { init(context); list = objects ; } @Override public int getItemCount() { return list.size(); } // Headers public abstract void drawText(TextView textView, T object); private void init(Context context) { this.mInflater = LayoutInflater.from(context); } GenricDialogFragment.GenricDialogFragmentClickListener genricDialogArrayAdapterClickListenr ; public void setGenricDialogArrayAdapterClickListenr(GenricDialogFragment.GenricDialogFragmentClickListener genricDialogArrayAdapterClickListenr) { this.genricDialogArrayAdapterClickListenr = genricDialogArrayAdapterClickListenr; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { final ViewHolder vh; View convertView = mInflater.inflate(R.layout.simple_spinner_item, parent, false); vh = new ViewHolder(convertView); return vh; } @Override public void onBindViewHolder(ViewHolder holder, final int position) { drawText(holder.textView, list.get(position)); if (genricDialogArrayAdapterClickListenr != null) holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { genricDialogArrayAdapterClickListenr.onGenericDialogItemClicked(list.get(position)); } }); } static class ViewHolder extends RecyclerView.ViewHolder { TextView textView; View delete ; private ViewHolder(View rootView) { super(rootView); textView = (TextView) rootView.findViewById(R.id.row_text); } } }
/* Recursive Solution to find the First Occurence of an element in an array using binary search Time Complexity: O(log N); Space Complexity: O(log N); */ package Searching.FirstOccurence; public class FirstOccurenceBS { public static void main(String[] args) { int[] arr = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2 }; System.out.println(findFirstOccurence(arr, 1, 0, arr.length - 1)); System.out.println(findFirstOccurence(arr, 2, 0, arr.length - 1)); } static int findFirstOccurence(int arr[], int key, int low, int high) { if (low > high) return -1; int mid = (low + high) / 2; if (key > arr[mid]) return findFirstOccurence(arr, key, mid + 1, high); else if (key < arr[mid]) return findFirstOccurence(arr, key, low, mid - 1); else { // if mid = 0 then it is also the first occurence if (mid == 0 || arr[mid - 1] != arr[mid]) return mid; return findFirstOccurence(arr, key, low, mid - 1); } } }
package com.travix.toughjet.controller; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.time.Instant; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import com.travix.toughjet.domain.FlightRequest; import com.travix.toughjet.entity.Flight; import com.travix.toughjet.service.FlightService; @RunWith(SpringRunner.class) @WebMvcTest(FlightController.class) public class FlightControllerIntegrationTest { @Autowired private MockMvc mvc; @MockBean private FlightService service; @Test public void testfindFlight() throws Exception { FlightRequest request = new FlightRequest("SAW", "AMS", LocalDate.of(2020, 03, 01), LocalDate.of(2020, 03, 04), 3); Flight flight = new Flight(1L, 1, "Pegasus", "AMS", "SAW", Instant.now(), Instant.now(), 34.5, 12.5, 2.7, 123); List<Flight> result = new ArrayList<Flight>(); result.add(flight); given(service.findFlight(request)).willReturn(result); mvc.perform(get("/flights?outboundDate=2020-03-01&to=AMS&from=SAW&numberOfAdults=3&inboundDate=2020-03-04") .contentType(MediaType.APPLICATION_JSON)).andExpect(status().isOk()); } }
package com.baixiaowen.javaconcurrencyprogramming.threadcoreknowledge线程8大核心基础知识.threadsafetyissues线程安全问题.手写观察者模式; public class Main { public static void main(String[] args) { // 初始化自定义监听器 MyEventListener myEventListener = new MyEventListener(event -> { System.out.println("我是真正的监听器方法"); }); // myEventListener.registeredMonitoring(new Event() { }); } }
public class Test { public static class Animal { // khai báo thuộc tính public String name; public String type; public int age; // Khởi tạo contructor ko tham số public Animal() { } // Khoi tao contructor co tham so public Animal(String name, String type, int age) { this.name = name; this.type = type; this.age = age; } // Phuong thức get set public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } // Overriding @Override public String toString() { return "Animal{" + "name='" + name + '\'' + ", type='" + type + '\'' + ", age=" + age + '}'; } public void move(){ System.out.println("Animals can move"); } } public static class Chicken extends Animal { private int sochan; public Chicken() { super(); } public Chicken(String name, String type, int age, int sochan) { super(name, type, age); this.sochan = sochan; } @Override public void move() { System.out.println("Chicken co the bay"); } } //Dog kế thừa Animal public static class Dog extends Animal { private int sochan; public Dog() { super(); } public Dog(String name, String type, int age, int sochan) { super(name, type, age); this.sochan = sochan; } @Override public void move() { System.out.println("Dogs co the chay"); } // overloading public void move(String bosung) { System.out.println("Dogs co the chay " + bosung); } } public static void main(String[] args) { Animal animal = new Animal(); animal.move(); String bosung = "trung thanh"; Dog dog = new Dog(); dog.move(bosung); Animal animal1 = new Chicken(); animal1.move(); } }
package com.tencent.mm.plugin.game.ui; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.plugin.game.e.c; import com.tencent.mm.plugin.game.f.i; import com.tencent.mm.plugin.game.model.an; class GameLibraryUI$6 implements OnClickListener { final /* synthetic */ GameLibraryUI jZN; GameLibraryUI$6(GameLibraryUI gameLibraryUI) { this.jZN = gameLibraryUI; } public final void onClick(View view) { int i = 6; if (view.getTag() instanceof String) { c.a(view, this.jZN); i = 7; } else { Intent intent = new Intent(this.jZN, GameCategoryUI.class); intent.putExtra("extra_type", 2); intent.putExtra("extra_category_name", this.jZN.getString(i.game_library_more_game)); intent.putExtra("game_report_from_scene", 1113); this.jZN.startActivity(intent); } an.a(this.jZN, 11, 1113, 1, i, GameLibraryUI.e(this.jZN), null); } }
package com.duanxr.yith.easy; /** * @author 段然 2021/3/8 */ public class NumberComplement { /** * Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation. * *   * * Example 1: * * Input: num = 5 * Output: 2 * Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2. * Example 2: * * Input: num = 1 * Output: 0 * Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0. *   * * Constraints: * * The given integer num is guaranteed to fit within the range of a 32-bit signed integer. * num >= 1 * You could assume no leading zero bit in the integer’s binary representation. * This question is the same as 1009: https://leetcode.com/problems/complement-of-base-10-integer/ * * 给你一个 正 整数 num ,输出它的补数。补数是对该数的二进制表示取反。 * *   * * 示例 1: * * 输入:num = 5 * 输出:2 * 解释:5 的二进制表示为 101(没有前导零位),其补数为 010。所以你需要输出 2 。 * 示例 2: * * 输入:num = 1 * 输出:0 * 解释:1 的二进制表示为 1(没有前导零位),其补数为 0。所以你需要输出 0 。 *   * * 提示: * * 给定的整数 num 保证在 32 位带符号整数的范围内。 * num >= 1 * 你可以假定二进制数不包含前导零位。 * 本题与 1009 https://leetcode-cn.com/problems/complement-of-base-10-integer/ 相同 * */ class Solution { public int findComplement(int num) { int mask = ~0; int tn = num; while (tn!=0) { tn=tn>>>1; mask = mask<<1; } return ~(num|mask); } } class Solution1 { public int findComplement(int num) { char[] c = Integer.toBinaryString(num).toCharArray(); StringBuilder stringBuilder = new StringBuilder(); for (char nowC : c) { if (nowC == '0') { stringBuilder.append('1'); } else { stringBuilder.append('0'); } } return Integer.valueOf(stringBuilder.toString(), 2); } } }
package pdx.module.janitorial; public class CheckoutSchedule { public static String[] columns = {"Floor", "Room", "Time", "Urgent?"}; public static String[][] placeholder = { {"1", "109", "10:00 AM", "No"}, {"2", "206", "10:00 AM", "Yes"}, {"2", "108", "10:00 AM", "No"}, {"4", "401", "10:00 AM", "No"}, {"5", "510", "10:00 AM", "Yes"}, {"6", "611", "10:00 AM", "Yes"}, }; }
package fr.eseo.poo.projet.artiste.modele; import java.text.DecimalFormat; public class Coordonnees { public static final double ABSCISSE_PAR_DEFAUT = 0, ORDONNEE_PAR_DEFAUT = 0; private double abscisse, ordonnee; public Coordonnees() { this(ABSCISSE_PAR_DEFAUT, ORDONNEE_PAR_DEFAUT); } public Coordonnees(double abscisse, double ordonnee) { this.setAbscisse(abscisse); this.setOrdonnee(ordonnee); } public double getAbscisse() { return this.abscisse; } public void setAbscisse(double abscisse) { this.abscisse = abscisse; } public double getOrdonnee() { return this.ordonnee; } public void setOrdonnee(double ordonnee) { this.ordonnee = ordonnee; } public void deplacerDe(double deltaX, double deltaY) { this.setAbscisse(this.getAbscisse() + deltaX); this.setOrdonnee(this.getOrdonnee() + deltaY); } public void deplacerVers(double nouvelleAbscisse, double nouvelleOrdonnee) { this.setAbscisse(nouvelleAbscisse); this.setOrdonnee(nouvelleOrdonnee); } public double distanceVers(Coordonnees autreCoordonnees) { return Math.sqrt(Math.pow(this.getAbscisse() - autreCoordonnees.getAbscisse(), 2) + Math.pow(this.getOrdonnee() - autreCoordonnees.getOrdonnee(), 2)); } public double angleVers(Coordonnees autreCoordonnees) { double angle = Math.asin((autreCoordonnees.getOrdonnee() - this.getOrdonnee()) / this.distanceVers(autreCoordonnees)); if (this.getAbscisse() > autreCoordonnees.getAbscisse()) angle = (this.getOrdonnee() > autreCoordonnees.getOrdonnee()) ? -Math.PI - angle : Math.PI - angle; return angle; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Coordonnees)) { return false; } Coordonnees other = (Coordonnees) obj; if (Double.doubleToLongBits(abscisse) != Double.doubleToLongBits(other.abscisse)) { return false; } if (Double.doubleToLongBits(ordonnee) != Double.doubleToLongBits(other.ordonnee)) { return false; } return true; } @Override public String toString() { DecimalFormat decimalFormat = new DecimalFormat("0.0#"); return "(" + decimalFormat.format(this.getAbscisse()) + " , " + decimalFormat.format(this.getOrdonnee()) + ")"; } }
package controlador; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.delegate.ExecutionListener; import persistencia.Solicitud; public class CorregirLista implements ExecutionListener{ public void notify(DelegateExecution execution) { EntityManagerFactory emf = Persistence .createEntityManagerFactory("EmployeePU"); EntityManager em = emf.createEntityManager(); EntityTransaction et= em.getTransaction(); et.begin(); Query q = em.createNamedQuery("Solicitud.ByProcesoIdOrderPrioridad"); try { if(execution.getVariable("identificacion") instanceof Long) { q.setParameter("idProceso",(Long)execution.getVariable("identificacion")); }else if(execution.getVariable("identificacion") instanceof Integer) { q.setParameter("idProceso",(Integer)execution.getVariable("identificacion")); }else if(execution.getVariable("identificacion") instanceof String) { q.setParameter("idProceso",new Long((String)execution.getVariable("identificacion"))); } }catch(Exception e) { e.printStackTrace(); } List<Solicitud> solicitudes= (List<Solicitud>) q.getResultList(); et.commit(); List list_validadas= new ArrayList(); List list_invalidadas= new ArrayList(); for (Solicitud solicitud : solicitudes) { if(solicitud.getValidado()) { list_validadas.add(solicitud.getId().getCi()); }else { list_invalidadas.add(solicitud.getId().getCi()); } } execution.setVariable("list_solicitudes", list_validadas); execution.setVariable("list_solicitudes_invalidas", list_invalidadas); //SI esta validado la saco de invalidas, si no de validas // if(solicitud.getValidado()) { // //Si no esta en la lista de validas la agrego // if(!((ArrayList) execution.getVariable("list_solicitudes")).contains(solicitud.getId().getCi())) { // execution.setVariable("list_solicitudes",((ArrayList)execution.getVariable("list_solicitudes")).add(solicitud.getId().getCi())); // } // //Si esta en las invalidas la saco // if(((ArrayList) execution.getVariable("list_solicitudes_invalidas")).contains(solicitud.getId().getCi())) { // execution.setVariable("list_solicitudes_invalidas", ((ArrayList)execution.getVariable("list_solicitudes_invalidas")).remove(solicitud.getId().getCi())); // } // }else { // //Si no esta en la lista de validas la agrego // if(!((ArrayList) execution.getVariable("list_solicitudes_invalidas")).contains(solicitud.getId().getCi())) { // execution.setVariable("list_solicitudes_invalidas",((ArrayList)execution.getVariable("list_solicitudes_invalidas")).add(solicitud.getId().getCi())); // } // //Si esta en las invalidas la saco // if(((ArrayList) execution.getVariable("list_solicitudes")).contains(solicitud.getId().getCi())) { // execution.setVariable("list_solicitudes", ((ArrayList)execution.getVariable("list_solicitudes")).remove(solicitud.getId().getCi())); // } // } } }
package com.simpson.kisen.unofficial.model.vo; import java.util.List; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; @Data @ToString(callSuper = true) @NoArgsConstructor public class UnofficialPdImgExt2 extends UnofficialDeposit { private List<DepositpdImg> depositpdImgList; }
package com.tencent.mm.pluginsdk.g.a.c; import com.tencent.mm.sdk.platformtools.bi; import java.util.List; class i$3 implements Runnable { final /* synthetic */ m fht; final /* synthetic */ String qBR; final /* synthetic */ List qDb; final /* synthetic */ i qDc; i$3(i iVar, List list, m mVar, String str) { this.qDc = iVar; this.qDb = list; this.fht = mVar; this.qBR = str; } public final void run() { for (d dVar : this.qDb) { if (bi.oV(dVar.aca()).equals(this.fht.groupId)) { dVar.QI(this.qBR); } } } }
package com.tiger.exception; public enum ResultErrorCodeEnum { PARAM_ERROR(1001,"参数错误"), SERIALIZATIO_ERROR(1002,"序列化异常"), FILE_TOO_MAX_ERROR(1003,"文件太大"), SYSTEM_BUSY(1004,"系统繁忙,请稍后再试"), REQUEST_METHOD(1005,"请求类型错误"), RE_LOGIN(401,"请重新登录"); private int code; private String message; ResultErrorCodeEnum(int code, String message){ this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } }
package com.shopping.Servlet; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.shopping.models.ShoesOrder; import com.shopping.service.OrderService; import com.shopping.service.ShoesOrderService; import com.shopping.service.ShoesService; public class PayOK extends HttpServlet { OrderService orse=new OrderService(); ShoesOrderService sose=new ShoesOrderService(); ShoesService shse=new ShoesService(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String OrderNum=(String)req.getParameter("orderId"); System.out.println(OrderNum); OrderNum = OrderNum.substring(1,OrderNum.length()-1); String []orders = OrderNum.split(","); boolean b=false; for (String string : orders) { try { b=orse.updateByNum(string.trim()); } catch (SQLException e) { e.printStackTrace(); } } List<ShoesOrder> list=new ArrayList<ShoesOrder>(); boolean f=false; for(String string : orders) { try { list=sose.selectAmount(string.trim()); } catch (SQLException e) { e.printStackTrace(); } for(ShoesOrder li:list) { try { f=shse.UpdateCount(li.getAmount(), li.getShoesId()); } catch (SQLException e) { e.printStackTrace(); } } } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } }
package com.mxfit.mentix.menu3; import android.Manifest; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.annotation.SuppressLint; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.res.ResourcesCompat; import android.support.v4.graphics.drawable.DrawableCompat; import android.support.v7.app.AlertDialog; import android.view.View; import android.support.design.widget.NavigationView; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.ViewAnimationUtils; import android.widget.Button; import android.widget.ImageButton; import android.widget.RelativeLayout; 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.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PolylineOptions; import com.google.firebase.auth.FirebaseAuth; import com.mxfit.mentix.menu3.HistoryPackage.HistoryFragment; import com.mxfit.mentix.menu3.LoginPackage.AccountFragment; import com.mxfit.mentix.menu3.LoginPackage.LoginActivity; import com.mxfit.mentix.menu3.PushupsPackage.PushupsFragment; import com.mxfit.mentix.menu3.RunningPackage.MapsFragment; import com.mxfit.mentix.menu3.SitupsPackage.SitupsFragment; import com.mxfit.mentix.menu3.TrainingsPackage.TrainingFragment; import com.mxfit.mentix.menu3.Utils.*; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import me.grantland.widget.AutofitTextView; import static android.graphics.drawable.GradientDrawable.Orientation.TOP_BOTTOM; import static com.mxfit.mentix.menu3.GlobalValues.*; import static java.lang.Math.round; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnMapReadyCallback, LocationListener, TrainingFragment.OnFragmentInteractionListener, PushupsFragment.OnFragmentInteractionListener { //90 do -90 DatabaseHelper myDb; DatabasePremadesHelper runDb; Date date; DateFormat dateFormat; public String dbTableName; SaveFileCalendar saveFileCalendar; private GoogleMap mMap; LocationManager locationManager; private Location mLastLocation; public NavigationView navigationView; boolean exists = true; boolean existsUpd = true; String dist = "0.00"; private boolean drawLine = false; private boolean mapVisibility = false; private boolean TrackCamera = true; private boolean isTrackerInitialized = false; public boolean isInTraining = false; //wybral goal private boolean hasChosenGoal = true; //ukonczyl goal private boolean hasFinishedGoal = false; LatLng last = new LatLng(0.0, 0.0); public LatLng zero = new LatLng(0.0, 0.0); LatLng locations[] = new LatLng[20]; int locationsArraySize = 0; private float distance = 0; private float goaldistance = 0; private TextView txtTime; private AutofitTextView txtDistance; private TextView txtMenuTime; private TextView txtMenuDistance; private TextView txtMenuAvgSpeed; private TextView txtMenuCurGoal; private ImageButton btnLocationUpdates; private Button btnTrackCamera; private FloatingActionButton btnMapVis; private ImageButton btnStop; String curTime; RelativeLayout mapVis; RelativeLayout fragVis; public NumberFormat formatter; FragmentManager manager; long storeSeconds; public int themeNumber; public static MainActivity instance; double AVSspeed = 0.0; String currentTime = "0:00:00"; Toolbar toolbar; final int MSG_START_TIMER = 0; final int MSG_STOP_TIMER = 1; final int MSG_UPDATE_TIMER = 2; final int MSG_PAUSE_TIMER = 3; StopWatch timer = new StopWatch(); int REFRESH_RATE = 1000; ColorLineMethods colorLineMethods; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case MSG_START_TIMER: timer.resume(); //start timer mHandler.sendEmptyMessage(MSG_UPDATE_TIMER); break; case MSG_UPDATE_TIMER: currentTime = timer.toString(); curTime = currentTime; txtTime.setText("" + curTime); if (exists && findViewById(R.id.textView2) != null && existsUpd) { reinitializeFragButtons(); existsUpd = false; } if (txtMenuTime != null) { txtMenuTime.setText(curTime); } mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER, REFRESH_RATE); //text view is updated every second, break; //though the timer is still running case MSG_STOP_TIMER: mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates. timer.stop();//stop timer currentTime = timer.toString(); txtTime.setText("" + currentTime); if (txtMenuTime != null) { txtMenuTime.setText(currentTime); } break; case MSG_PAUSE_TIMER: mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates. timer.pause(); break; default: break; } } }; private void reinitializeFragButtons() { txtMenuTime = fragment.getView().findViewById(R.id.textView2); txtMenuAvgSpeed = fragment.getView().findViewById(R.id.textView13); txtMenuDistance = fragment.getView().findViewById(R.id.textView12); txtMenuCurGoal = fragment.getView().findViewById(R.id.GoalInt); TextView txtMenuFinGoal = fragment.getView().findViewById(R.id.GoalFinal); setTxtMenuAvgSpeed(); setTxtMenuDistance(); txtMenuFinGoal.setText(""+formatter.format(goal)); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case 7171: if (!(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.Permissions_warning) .setTitle(R.string.Permissions_title); builder.setNeutralButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); dialog = builder.create(); dialog.show(); } break; } } public void showHome(){ switch (welcomeScreen) { case 0: showTraining(); break; case 1: showRunning(); break; case 2: showPushups(); break; } if(welcomeScreen != 1) { hideMainLayout(); } existsUpd = true; navigationView.getMenu().getItem(welcomeScreen).setChecked(true); } FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() { @SuppressLint("SetTextI18n") @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if (FireBaseConnection.user == null) { startActivity(new Intent(MainActivity.this, LoginActivity.class)); finish(); } else { //setDataToView(user); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); prefs = PreferenceManager.getDefaultSharedPreferences(this); setContentView(R.layout.activity_main); FireBaseConnection.instatiate(); System.out.println(FireBaseConnection.user); authListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { if (FireBaseConnection.user == null) { System.out.println(FireBaseConnection.user); startActivity(new Intent(MainActivity.this, LoginActivity.class)); finish(); } } }; System.out.println(authListener); instance = this; Intent myIntent = new Intent(getBaseContext(), ClosingService.class); startService(myIntent); toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setLogo(R.mipmap.mxfitlaunchersplash); toolbar.setTitle(""); setSupportActionBar(toolbar); mapVis = (RelativeLayout) findViewById(R.id.mapsLayout); fragVis = (RelativeLayout) findViewById(R.id.mainLayout); btnMapVis = (FloatingActionButton) findViewById(R.id.mapVisBut); txtTime = (TextView) findViewById(R.id.txtTimer); txtDistance = (AutofitTextView) findViewById(R.id.txtDistance); btnLocationUpdates = (ImageButton) findViewById(R.id.btnTrackLocation); btnTrackCamera = (Button) findViewById(R.id.btnMoveCamera); btnStop = (ImageButton) findViewById(R.id.StopButton); btnStop.setEnabled(false); formatter = new DecimalFormat("#0.00"); DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); hideMainLayout(); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map1); mapFragment.getMapAsync(this); prefs = PreferenceManager.getDefaultSharedPreferences(this); loadTrainingData(); saveFileCalendar = new SaveFileCalendar(); if(!Synchronised) { saveFileCalendar.checkPushupsDate(); saveFileCalendar.checkRunningDate(); } else { saveFileCalendar.checkDayDate(); } loadPreferences(); showHome(); setName(); btnLocationUpdates.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggleDrawLine(); } }); btnTrackCamera.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggleTrack(); } }); btnMapVis.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { toggleMap(); } }); btnStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isInTraining) { showTrainingEndAlert(); } } }); } protected void setName(){ String name = prefs.getString("display_name",""); View headerView = navigationView.getHeaderView(0); TextView navUsername = (TextView) headerView.findViewById(R.id.nickName); TextView navMsg = (TextView) headerView.findViewById(R.id.welcomemsg); navUsername.setText(name); if(!name.equals("")) { navMsg.setText(getResources().getString(R.string.welcome_back) + ","); } else { navMsg.setText(R.string.welcome_back); } } private void initializeLocationManager() { if (!isTrackerInitialized) { locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, REFRESH*1000, REFRESH * 2, this); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } isTrackerInitialized = true; } } private void deinitializeLocationManager() { if (locationManager != null) { locationManager.removeUpdates(this); locationManager = null; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } } mMap.setMyLocationEnabled(false); last = zero; isTrackerInitialized = false; } public void showSettingsAlert() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle(R.string.GPS_name); alertDialog.setMessage(R.string.GPS_warning); alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } public void showTrainingEndAlert() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this); alertDialog.setTitle(R.string.Pushups_title); alertDialog.setMessage(R.string.EndTraining_warning); alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { saveDataOnStop(true); } }); alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); alertDialog.show(); } public void saveDataOnStop(Boolean resetView){ if(drawLine){ storeSeconds = timer.getRunningTime(); } mHandler.sendEmptyMessage(MSG_STOP_TIMER); saveDBonStop(locationsArraySize-1); if((goaldistance/1000)>=goal) { runDb = new DatabasePremadesHelper(getBaseContext()); if (rday < runDb.getHowManyRuns()) { runDb.setRunFinished(rday); rday++; goal = runDb.getDayRun(rday); } if(!Synchronised) { new SaveFileCalendar().setRunningDate(); } else { new SaveFileCalendar().setDayDate(false); } resetAlarm(); goaldistance = 0; } saveTrainingData(); if(resetView) { AVSspeed = 0.0; distance = 0; if (drawLine) { toggleDrawLine(); } isInTraining = false; mMap.clear(); reinitializeFragButtons(); txtDistance.setText(formatter.format(distance) + " m"); new ShowMap(instance, dbTableName.substring(2),true); dbTableName = null; if(goaldistance/1000<=goal) { hasFinishedGoal = false; } btnStop.setEnabled(false); } } public void addDBLocation(LatLng latLng, int Size) { if(locationsArraySize < Size) { locations[locationsArraySize] = latLng; locationsArraySize++; } else if (locationsArraySize == Size) { locations[locationsArraySize] = latLng; saveDBonStop(Size); } } public void saveDBonStop(int Size){ if(myDb!= null) { if(drawLine){ storeSeconds = timer.getRunningTime(); } myDb.insertMultipleData(locations, Size, distance, storeSeconds); locationsArraySize = 0; for (int i = 0; i <= Size; i++) { locations[i] = zero; } } } private void toggleDrawLine() { if (!drawLine) { if (!checkPermissions()) { return; } if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { showSettingsAlert(); return; } initializeLocationManager(); if (!isInTraining) { date = new Date(); dateFormat = new SimpleDateFormat("yyyyśMMśdd_HHźmmźss"); dbTableName = "t_" + dateFormat.format(date); myDb = new DatabaseHelper(this, dbTableName); btnStop.setEnabled(true); isInTraining = true; } if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); } colorLineMethods = new ColorLineMethods(); colorLineMethods.checkLinePrefs(); btnLocationUpdates.setImageResource(R.drawable.ic_pause); drawLine = true; mHandler.sendEmptyMessage(MSG_START_TIMER); reinitializeFragButtons(); } else { pauseTracking(); } } public void pauseTracking() { btnLocationUpdates.setImageResource(R.drawable.ic_play); drawLine = false; storeSeconds = timer.getRunningTime(); mHandler.sendEmptyMessage(MSG_PAUSE_TIMER); } public boolean checkPermissions() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_FINE_LOCATION, }, 7171); return false; } else { return true; } } private void toggleMap() { initializeLocationManager(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mMap.setMyLocationEnabled(true); } if (!mapVisibility) { mapVis.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); btnMapVis.setImageResource(R.drawable.ic_showmenu); btnMapVis.setBackgroundTintList(ColorStateList.valueOf(ResourcesCompat.getColor(getResources(),android.R.color.white,null))); if (Build.VERSION.SDK_INT >= 21) { int cx = (btnMapVis.getRight()+btnMapVis.getLeft())/2; int cy = (btnMapVis.getTop()+btnMapVis.getBottom())/2; btnMapVis.setEnabled(false); float finalRadius = (float) Math.hypot(fragVis.getWidth(), fragVis.getHeight()); Animator anim = ViewAnimationUtils.createCircularReveal(fragVis, cx, cy, finalRadius, 0); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); fragVis.setVisibility(View.INVISIBLE); fragVis.setLayoutParams(new RelativeLayout.LayoutParams(0, 0)); btnMapVis.setEnabled(true); } }); mapVis.setVisibility(View.VISIBLE); anim.start(); } else { fragVis.setVisibility(View.INVISIBLE); fragVis.setLayoutParams(new RelativeLayout.LayoutParams(0, 0)); mapVis.setVisibility(View.VISIBLE); } mapVisibility = true; } else { fragVis.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); btnMapVis.setImageResource(R.drawable.ic_map); btnMapVis.setBackgroundTintList(ColorStateList.valueOf(ResourcesCompat.getColor(getResources(),R.color.colorPrimary,null))); if (Build.VERSION.SDK_INT >= 21) { int cx = (btnMapVis.getRight()+btnMapVis.getLeft())/2; int cy = (btnMapVis.getTop()+btnMapVis.getBottom())/2; btnMapVis.setEnabled(false); float finalRadius = (float) Math.hypot(mapVis.getWidth(), mapVis.getHeight()); Animator anim = ViewAnimationUtils.createCircularReveal(fragVis, cx, cy, 0, finalRadius); anim.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); mapVis.setVisibility(View.INVISIBLE); mapVis.setLayoutParams(new RelativeLayout.LayoutParams(0, 0)); btnMapVis.setEnabled(true); } }); fragVis.setVisibility(View.VISIBLE); anim.start(); } else { mapVis.setVisibility(View.INVISIBLE); mapVis.setLayoutParams(new RelativeLayout.LayoutParams(0, 0)); fragVis.setVisibility(View.VISIBLE); } mapVisibility = false; reinitializeFragButtons(); setTxtMenuAvgSpeed(); setTxtMenuDistance(); txtMenuTime.setText(currentTime); } } private void setTxtMenuAvgSpeed() { if (txtMenuAvgSpeed != null) { txtMenuAvgSpeed.setText(""+AVSspeed); } } private void setTxtMenuDistance() { if (txtMenuDistance != null) { double MenuDist = distance/1000.0; dist = formatter.format(MenuDist); txtMenuDistance.setText(dist); if(hasChosenGoal) { double CurGoalDist = goaldistance/1000; txtMenuCurGoal.setText(formatter.format(CurGoalDist)); if(CurGoalDist>=goal) { hasFinishedGoal = true; txtMenuCurGoal.setTextColor(Color.GREEN); } else { txtMenuCurGoal.setTextColor(Color.RED); } } } } private void toggleTrack() { if (!TrackCamera) { DrawableCompat.setTint(btnTrackCamera.getBackground(), ContextCompat.getColor(this, R.color.colorPrimary)); TrackCamera = true; } else { DrawableCompat.setTint(btnTrackCamera.getBackground(), ContextCompat.getColor(this, android.R.color.black)); TrackCamera = false; } } private void exitPrompt() { if (isInTraining) { AlertDialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.Pushups_warning) .setTitle(R.string.Pushups_title); builder.setNeutralButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { deinitializeLocationManager(); saveDataOnStop(false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { finishAndRemoveTask(); } else { finishAffinity(); } } }); builder.setNegativeButton("Minimize", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { moveTaskToBack(true); } }); builder.setPositiveButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { return; } }); dialog = builder.create(); dialog.show(); } else { super.onBackPressed(); } } @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { if (welcomeScreen == 0 && fragment instanceof TrainingFragment) { exitPrompt(); } else if (welcomeScreen == 1 && fragment instanceof MapsFragment) { exitPrompt(); } else if (welcomeScreen == 2 && fragment instanceof PushupsFragment) { exitPrompt(); } else { showHome(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } public void loadPreferences() { setTheme(); AlarmEnabled = prefs.getBoolean("switch_notifications_enable",false); if(AlarmEnabled) setTrainingNotification(prefs.getInt("Hour",12),prefs.getInt("Minute",0)); welcomeScreen = Integer.parseInt(prefs.getString("example_list", "0")); REFRESH = Integer.parseInt(prefs.getString("sync_frequency", "2")); if(prefs.getBoolean("pref_theme_color", false)) { if(prefs.getBoolean("switch_bar_color", false)) toolbar.setBackgroundColor(prefs.getInt("color1", 0)); else { if(themeNumber != 3) toolbar.setBackgroundColor(getResources().getColor(R.color.barColor)); else toolbar.setBackgroundColor(getResources().getColor(R.color.Gold)); } if(prefs.getBoolean("switch_background_color", false)) { if (prefs.getBoolean("switch_gradient_color", false)) { int Color1 = prefs.getInt("color2", 0), Color2 = prefs.getInt("color3", 0); int[] colors = new int[]{Color1, Color2}; GradientDrawable gd = new GradientDrawable(TOP_BOTTOM, colors); fragVis.setBackground(gd); } else fragVis.setBackgroundColor(prefs.getInt("color2", 0)); } else fragVis.setBackground(ContextCompat.getDrawable(this, R.drawable.pushupgui)); } else { if(themeNumber != 3) toolbar.setBackgroundColor(getResources().getColor(R.color.barColor)); else toolbar.setBackgroundColor(getResources().getColor(R.color.Gold)); fragVis.setBackground(ContextCompat.getDrawable(this, R.drawable.pushupgui)); } } public void setTheme(){ themeNumber = Integer.parseInt(prefs.getString("theme_number", "1")); if(themeNumber == 1) setTheme(R.style.DailyTheme); else if (themeNumber == 2) setTheme(R.style.AppTheme); else if (themeNumber == 3) setTheme(R.style.DeusAge); else if (themeNumber == 4) setTheme(R.style.MinimalisticTheme); } public void showRunning() { if (!(fragment instanceof MapsFragment)) { fragment = MapsFragment.newInstance(dist,AVSspeed,formatter.format(goaldistance/1000),goal,hasFinishedGoal,currentTime); } if (fragment != null) { FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit(); } exists = true; btnMapVis.setVisibility(View.VISIBLE); btnLocationUpdates.setVisibility(View.VISIBLE); btnStop.setVisibility(View.VISIBLE); initializeLocationManager(); if (!mapVisibility) { mapVis.setVisibility(View.INVISIBLE); fragVis.setVisibility(View.VISIBLE); mapVis.setLayoutParams(new RelativeLayout.LayoutParams(0, 0)); fragVis.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); } else { mapVis.setVisibility(View.VISIBLE); fragVis.setVisibility(View.INVISIBLE); mapVis.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); fragVis.setLayoutParams(new RelativeLayout.LayoutParams(0, 0)); } } private void showTraining() { if (!(fragment instanceof TrainingFragment)) { fragment = TrainingFragment.newInstance(pushupsDay, pushupsTraininglevel,goal); } if (fragment != null) { FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit(); } } public void showPushups() { if (!(fragment instanceof PushupsFragment)) { fragment = PushupsFragment.newInstance(pushupsDay, pushupsTraininglevel); } if (fragment != null) { FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit(); } } public void showAccount() { if (!(fragment instanceof AccountFragment)) { fragment = new AccountFragment(this); } if (fragment != null) { FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit(); } } private void showHistory() { if (!(fragment instanceof HistoryFragment)) { fragment = new HistoryFragment(); } if (fragment != null) { FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit(); } } Fragment fragment = null; @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.nav_trainings) showTraining(); else if (id == R.id.nav_running) showRunning(); else if (id == R.id.nav_pushups) showPushups(); else if (id == R.id.nav_account) showAccount(); else if (id == R.id.nav_history) showHistory(); else if (id == R.id.nav_situps) showSitups(); if(id != R.id.nav_running) { if(!isInTraining && id != R.id.nav_settings) { deinitializeLocationManager(); } existsUpd = true; exists = false; if(id == R.id.nav_exit) { exitPrompt(); } else if (id == R.id.nav_settings) { Intent settings = new Intent(this, SettingsActivity.class); startActivity(settings); } else { hideMainLayout(); } } if(fragment != null){ manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit(); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } public void showSitups() { if (!(fragment instanceof SitupsFragment)) { fragment = SitupsFragment.newInstance(situpsDay, situpsTraininglevel); } if (fragment != null) { FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mainLayout, fragment, fragment.getTag()).commit(); } } public void hideMainLayout() { mapVis.setVisibility(View.INVISIBLE); fragVis.setVisibility(View.VISIBLE); mapVis.setLayoutParams(new RelativeLayout.LayoutParams(0, 0)); fragVis.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT)); btnMapVis.setVisibility(View.INVISIBLE); btnStop.setVisibility(View.INVISIBLE); btnLocationUpdates.setVisibility(View.INVISIBLE); } public void resetAlarm(){ if(AlarmEnabled) { cancelAlarm(); setTrainingNotification(prefs.getInt("Hour", 12), prefs.getInt("Minute", 0)); } } public void setTrainingNotification(int hour, int minute){ Intent intent = new Intent(this, NotificationReceiver.class); intent.setAction(NotificationReceiver.ACTION_ALARM_RECEIVER); boolean isWorking = (PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_NO_CREATE) != null); ArrayList<String> dates = new ArrayList<>(); if(lastPushupDate!= null) dates.add(lastPushupDate); if(lastRunDate!=null) dates.add(lastRunDate); if(lastSitupDate!=null) dates.add(lastSitupDate); Date closestDate = saveFileCalendar.WhichDateFirst(dates); if(!isWorking && closestDate!=null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(closestDate); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); startAlarm(calendar); Toast.makeText(this, "Reminder set", Toast.LENGTH_SHORT).show(); } } private void startAlarm(Calendar c) { AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, NotificationReceiver.class); intent.setAction(NotificationReceiver.ACTION_ALARM_RECEIVER); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent); ComponentName receiver = new ComponentName(this, NotificationReceiver.class); PackageManager pm = this.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP); } protected void cancelAlarm(){ AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(this, NotificationReceiver.class); intent.setAction(NotificationReceiver.ACTION_ALARM_RECEIVER); PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, PendingIntent.FLAG_CANCEL_CURRENT); alarmManager.cancel(pendingIntent); pendingIntent.cancel(); ComponentName receiver = new ComponentName(this, NotificationReceiver.class); PackageManager pm = this.getPackageManager(); pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } } @Override public void onLocationChanged(Location location) { LatLng sydney = new LatLng(location.getLatitude (), location.getLongitude()); if(TrackCamera) { float zoom = mMap.getCameraPosition().zoom; mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, zoom)); } if(FirstZoom) { mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 9.0f)); FirstZoom = false; } if (drawLine && !last.equals(zero)) { PolylineOptions PolOps = new PolylineOptions().jointType(2).width(5); if (isMultiColorLine && isCustomLine) { colorLineMethods.setLineColor(); PolOps.color(Color.rgb((int)tempColors[0], (int)tempColors[1], (int)tempColors[2])); } else if (isCustomLine){ PolOps.color(LineColor1); } else { PolOps.color(Color.BLUE); } mMap.addPolyline(PolOps.add(last, sydney)); addDBLocation(sydney,5); distance += location.distanceTo(mLastLocation); if(hasChosenGoal) { goaldistance += location.distanceTo(mLastLocation); } setTxtMenuDistance(); if(distance < 1000000) txtDistance.setText(formatter.format(distance)+ " m"); else txtDistance.setText(formatter.format(distance/1000)+ " km"); if(distance>0) { AVSspeed = (round((distance/timer.getRunningTime())*3.6 * 100.0)/100.0); setTxtMenuAvgSpeed(); } } last = sydney; mLastLocation = location; } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { if(drawLine) { showSettingsAlert(); pauseTracking(); } } @Override protected void onDestroy() { deinitializeLocationManager(); saveTrainingData(); super.onDestroy(); } //trainingfragment @Override public void onFragmentInteraction(int pday, int TLevel, float pgoal) { pushupsDay = pday; pushupsTraininglevel = TLevel; goal = pgoal; } //pushupsfragment @Override public void onFragmentInteraction(int pday, int tlevel) { pushupsDay = pday; pushupsTraininglevel = tlevel; } public void signOut() { FireBaseConnection.auth.signOut(); FireBaseConnection.refreshUser(); finish(); startActivity(new Intent(MainActivity.this, LoginActivity.class)); } }
package net.minecraft.client.renderer.texture; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Arrays; import java.util.List; import java.util.Set; import net.minecraft.client.renderer.StitcherException; import net.minecraft.util.math.MathHelper; import optifine.MathUtils; public class Stitcher { private final int mipmapLevelStitcher; private final Set<Holder> setStitchHolders = Sets.newHashSetWithExpectedSize(256); private final List<Slot> stitchSlots = Lists.newArrayListWithCapacity(256); private int currentWidth; private int currentHeight; private final int maxWidth; private final int maxHeight; private final int maxTileDimension; public Stitcher(int maxWidthIn, int maxHeightIn, int maxTileDimensionIn, int mipmapLevelStitcherIn) { this.mipmapLevelStitcher = mipmapLevelStitcherIn; this.maxWidth = maxWidthIn; this.maxHeight = maxHeightIn; this.maxTileDimension = maxTileDimensionIn; } public int getCurrentWidth() { return this.currentWidth; } public int getCurrentHeight() { return this.currentHeight; } public void addSprite(TextureAtlasSprite textureAtlas) { Holder stitcher$holder = new Holder(textureAtlas, this.mipmapLevelStitcher); if (this.maxTileDimension > 0) stitcher$holder.setNewDimension(this.maxTileDimension); this.setStitchHolders.add(stitcher$holder); } public void doStitch() { Holder[] astitcher$holder = this.setStitchHolders.<Holder>toArray(new Holder[this.setStitchHolders.size()]); Arrays.sort((Object[])astitcher$holder); byte b; int i; Holder[] arrayOfHolder1; for (i = (arrayOfHolder1 = astitcher$holder).length, b = 0; b < i; ) { Holder stitcher$holder = arrayOfHolder1[b]; if (!allocateSlot(stitcher$holder)) { String s = String.format("Unable to fit: %s, size: %dx%d, atlas: %dx%d, atlasMax: %dx%d - Maybe try a lower resolution resourcepack?", new Object[] { stitcher$holder.getAtlasSprite().getIconName(), Integer.valueOf(stitcher$holder.getAtlasSprite().getIconWidth()), Integer.valueOf(stitcher$holder.getAtlasSprite().getIconHeight()), Integer.valueOf(this.currentWidth), Integer.valueOf(this.currentHeight), Integer.valueOf(this.maxWidth), Integer.valueOf(this.maxHeight) }); throw new StitcherException(stitcher$holder, s); } b++; } this.currentWidth = MathHelper.smallestEncompassingPowerOfTwo(this.currentWidth); this.currentHeight = MathHelper.smallestEncompassingPowerOfTwo(this.currentHeight); } public List<TextureAtlasSprite> getStichSlots() { List<Slot> list = Lists.newArrayList(); for (Slot stitcher$slot : this.stitchSlots) stitcher$slot.getAllStitchSlots(list); List<TextureAtlasSprite> list1 = Lists.newArrayList(); for (Slot stitcher$slot1 : list) { Holder stitcher$holder = stitcher$slot1.getStitchHolder(); TextureAtlasSprite textureatlassprite = stitcher$holder.getAtlasSprite(); textureatlassprite.initSprite(this.currentWidth, this.currentHeight, stitcher$slot1.getOriginX(), stitcher$slot1.getOriginY(), stitcher$holder.isRotated()); list1.add(textureatlassprite); } return list1; } private static int getMipmapDimension(int p_147969_0_, int p_147969_1_) { return (p_147969_0_ >> p_147969_1_) + (((p_147969_0_ & (1 << p_147969_1_) - 1) == 0) ? 0 : 1) << p_147969_1_; } private boolean allocateSlot(Holder p_94310_1_) { TextureAtlasSprite textureatlassprite = p_94310_1_.getAtlasSprite(); boolean flag = (textureatlassprite.getIconWidth() != textureatlassprite.getIconHeight()); for (int i = 0; i < this.stitchSlots.size(); i++) { if (((Slot)this.stitchSlots.get(i)).addSlot(p_94310_1_)) return true; if (flag) { p_94310_1_.rotate(); if (((Slot)this.stitchSlots.get(i)).addSlot(p_94310_1_)) return true; p_94310_1_.rotate(); } } return expandAndAllocateSlot(p_94310_1_); } private boolean expandAndAllocateSlot(Holder p_94311_1_) { Slot stitcher$slot; int i = Math.min(p_94311_1_.getWidth(), p_94311_1_.getHeight()); int j = Math.max(p_94311_1_.getWidth(), p_94311_1_.getHeight()); int k = MathHelper.smallestEncompassingPowerOfTwo(this.currentWidth); int l = MathHelper.smallestEncompassingPowerOfTwo(this.currentHeight); int i1 = MathHelper.smallestEncompassingPowerOfTwo(this.currentWidth + i); int j1 = MathHelper.smallestEncompassingPowerOfTwo(this.currentHeight + i); boolean flag = (i1 <= this.maxWidth); boolean flag1 = (j1 <= this.maxHeight); if (!flag && !flag1) return false; int k1 = MathUtils.roundDownToPowerOfTwo(this.currentHeight); boolean flag2 = (flag && i1 <= 2 * k1); if (this.currentWidth == 0 && this.currentHeight == 0) flag2 = true; if (flag2) { if (p_94311_1_.getWidth() > p_94311_1_.getHeight()) p_94311_1_.rotate(); if (this.currentHeight == 0) this.currentHeight = p_94311_1_.getHeight(); stitcher$slot = new Slot(this.currentWidth, 0, p_94311_1_.getWidth(), this.currentHeight); this.currentWidth += p_94311_1_.getWidth(); } else { stitcher$slot = new Slot(0, this.currentHeight, this.currentWidth, p_94311_1_.getHeight()); this.currentHeight += p_94311_1_.getHeight(); } stitcher$slot.addSlot(p_94311_1_); this.stitchSlots.add(stitcher$slot); return true; } public static class Holder implements Comparable<Holder> { private final TextureAtlasSprite theTexture; private final int width; private final int height; private final int mipmapLevelHolder; private boolean rotated; private float scaleFactor = 1.0F; public Holder(TextureAtlasSprite theTextureIn, int mipmapLevelHolderIn) { this.theTexture = theTextureIn; this.width = theTextureIn.getIconWidth(); this.height = theTextureIn.getIconHeight(); this.mipmapLevelHolder = mipmapLevelHolderIn; this.rotated = (Stitcher.getMipmapDimension(this.height, mipmapLevelHolderIn) > Stitcher.getMipmapDimension(this.width, mipmapLevelHolderIn)); } public TextureAtlasSprite getAtlasSprite() { return this.theTexture; } public int getWidth() { int i = this.rotated ? this.height : this.width; return Stitcher.getMipmapDimension((int)(i * this.scaleFactor), this.mipmapLevelHolder); } public int getHeight() { int i = this.rotated ? this.width : this.height; return Stitcher.getMipmapDimension((int)(i * this.scaleFactor), this.mipmapLevelHolder); } public void rotate() { this.rotated = !this.rotated; } public boolean isRotated() { return this.rotated; } public void setNewDimension(int p_94196_1_) { if (this.width > p_94196_1_ && this.height > p_94196_1_) this.scaleFactor = p_94196_1_ / Math.min(this.width, this.height); } public String toString() { return "Holder{width=" + this.width + ", height=" + this.height + ", name=" + this.theTexture.getIconName() + '}'; } public int compareTo(Holder p_compareTo_1_) { int i; if (getHeight() == p_compareTo_1_.getHeight()) { if (getWidth() == p_compareTo_1_.getWidth()) { if (this.theTexture.getIconName() == null) return (p_compareTo_1_.theTexture.getIconName() == null) ? 0 : -1; return this.theTexture.getIconName().compareTo(p_compareTo_1_.theTexture.getIconName()); } i = (getWidth() < p_compareTo_1_.getWidth()) ? 1 : -1; } else { i = (getHeight() < p_compareTo_1_.getHeight()) ? 1 : -1; } return i; } } public static class Slot { private final int originX; private final int originY; private final int width; private final int height; private List<Slot> subSlots; private Stitcher.Holder holder; public Slot(int originXIn, int originYIn, int widthIn, int heightIn) { this.originX = originXIn; this.originY = originYIn; this.width = widthIn; this.height = heightIn; } public Stitcher.Holder getStitchHolder() { return this.holder; } public int getOriginX() { return this.originX; } public int getOriginY() { return this.originY; } public boolean addSlot(Stitcher.Holder holderIn) { if (this.holder != null) return false; int i = holderIn.getWidth(); int j = holderIn.getHeight(); if (i <= this.width && j <= this.height) { if (i == this.width && j == this.height) { this.holder = holderIn; return true; } if (this.subSlots == null) { this.subSlots = Lists.newArrayListWithCapacity(1); this.subSlots.add(new Slot(this.originX, this.originY, i, j)); int k = this.width - i; int l = this.height - j; if (l > 0 && k > 0) { int i1 = Math.max(this.height, k); int j1 = Math.max(this.width, l); if (i1 >= j1) { this.subSlots.add(new Slot(this.originX, this.originY + j, i, l)); this.subSlots.add(new Slot(this.originX + i, this.originY, k, this.height)); } else { this.subSlots.add(new Slot(this.originX + i, this.originY, k, j)); this.subSlots.add(new Slot(this.originX, this.originY + j, this.width, l)); } } else if (k == 0) { this.subSlots.add(new Slot(this.originX, this.originY + j, i, l)); } else if (l == 0) { this.subSlots.add(new Slot(this.originX + i, this.originY, k, j)); } } for (Slot stitcher$slot : this.subSlots) { if (stitcher$slot.addSlot(holderIn)) return true; } return false; } return false; } public void getAllStitchSlots(List<Slot> p_94184_1_) { if (this.holder != null) { p_94184_1_.add(this); } else if (this.subSlots != null) { for (Slot stitcher$slot : this.subSlots) stitcher$slot.getAllStitchSlots(p_94184_1_); } } public String toString() { return "Slot{originX=" + this.originX + ", originY=" + this.originY + ", width=" + this.width + ", height=" + this.height + ", texture=" + this.holder + ", subSlots=" + this.subSlots + '}'; } } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\client\renderer\texture\Stitcher.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.huanuo.npo.service; import com.huanuo.npo.Dao.SiteInfoDao; import com.huanuo.npo.pojo.SiteInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.print.DocFlavor; import java.io.*; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; @Service public class SiteInfoService { public static final String STRING ="class java.lang.String"; public static final String DOUBLE ="double"; public static final String LONG ="long"; public static final String INT ="int"; public List<SiteInfo> readcsv(String csvfile) throws NoSuchMethodException{ List<SiteInfo> siteinfo=new ArrayList<SiteInfo>(); File inFile = new File(csvfile); // 读取的CSV文件 String inString = ""; BufferedReader reader = null; int table = 0; //判断表头 String[] TableTitle=new String[23]; try { reader = new BufferedReader(new FileReader(inFile)); //创建一个字符读取流对象FileReader(inFile);传递给缓冲对象的构造函数 while ((inString = reader.readLine()) != null) { if (table == 0) { TableTitle = inString.split(","); table++; } else { String[] strArray = null; strArray = inString.split(","); //创建对象引用,获取属性值: siteinfo.add(SetObj(strArray,TableTitle)); } } } catch (FileNotFoundException ex) { System.out.println("没找到文件!"); } catch (IOException ex) { System.out.println("读写文件出错!"); }catch (NoSuchMethodException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } } return siteinfo; } public SiteInfo SetObj(String[] strArray,String[] TableTitle) throws NoSuchMethodException, SecurityException, IllegalArgumentException{ SiteInfo obj=new SiteInfo(); Field[] field = obj.getClass().getDeclaredFields(); try { for(int i=0;i<TableTitle.length;i++ ) { //遍历表头 for (int j = 0; j < field.length; j++) { // 遍历所有属性 String name = field[j].getName(); // 获取属性的名字 String type = field[j].getGenericType().toString(); // 获取属性的类型 if (TableTitle[i].equalsIgnoreCase(name)) { field[j].setAccessible(true); // 如果type是类类型,则前面包含"class ",后面跟类名 if (type.equals(STRING)){ if (strArray[i].equals("")) { //为空设为空字符串 field[j].set(obj,"empty");} else { field[j].set(obj,strArray[i]);} } if (type.equals(INT)){ //为空设为0 if (strArray[i].equals("")) { //为空设为空字符串 field[j].set(obj,0);} else { field[j].set(obj,Integer.valueOf(strArray[i])); }} if (type.equals(LONG)) { if (strArray[i].equals("")){ //如果为空 if (name.equalsIgnoreCase("CI")) {//如果是CI,计算得出结果 long t = Long.parseLong(strArray[2]) * 256 + Long.parseLong(strArray[5]); field[j].set(obj, t); } else { //不是CI,空的填0 field[j].set(obj, 0); } } else{ field[j].set(obj, Long.parseLong(strArray[i])); } } if (type.equals(DOUBLE)) { if (strArray[i].equals("")) { //为空设为空字符串 field[j].set(obj,0);} else { field[j].set(obj, Double.parseDouble(strArray[i]));} } } } } } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } return obj; } }
package gdut.ff.service; import gdut.ff.domain.Role; import gdut.ff.domain.User; import gdut.ff.mapper.RoleMapper; import gdut.ff.mapper.UserMapper; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.List; /** * @Author bluesnail95 * @Date 2020/10/6 10:15 * @Description */ @Component public class UserDetailsServicempl implements UserDetailsService { @Resource private UserMapper userMapper; @Resource private RoleMapper roleMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userMapper.fingUserByName(username); if(null == user) { throw new UsernameNotFoundException("user is null"); } List<Role> roleList = roleMapper.findRoleByUser(user.getUserId()); user.setRoleList(roleList); return user; } }
package config; import common.instamsg.driver.ModulesProviderInterface; public class ModulesProviderFactory { public static ModulesProviderInterface getModulesProvider(String device){ if(device.equals("stub")){ return new device.stub.instamsg.ModulesProvider(); } else if(device.equals("linux")){ return new device.linux.instamsg.ModulesProvider(); } /* * All new device-implementors must add their devices in this factory. */ return null; } }
package com.vaadin.cdi.internal; import com.vaadin.cdi.viewcontextstrategy.ViewContextStrategy; import com.vaadin.cdi.viewcontextstrategy.ViewContextStrategyQualifier; import com.vaadin.cdi.viewcontextstrategy.ViewContextByNameAndParameters; import com.vaadin.navigator.View; import org.apache.deltaspike.core.api.literal.AnyLiteral; import org.apache.deltaspike.core.api.provider.BeanProvider; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.inject.Inject; import java.lang.annotation.Annotation; import java.util.Set; /** * Looks up ViewContextStrategy for view classes. */ @ApplicationScoped public class ViewContextStrategyProvider { private static AnyLiteral ANY_LITERAL = new AnyLiteral(); @Inject private BeanManager beanManager; public ViewContextStrategy lookupStrategy(Class<? extends View> viewClass) { Class<? extends Annotation> annotationClass = findStrategyAnnotation(viewClass); if (annotationClass == null) { annotationClass = ViewContextByNameAndParameters.class; } final Bean strategyBean = findStrategyBean(annotationClass); if (strategyBean == null) { throw new IllegalStateException( "No ViewContextStrategy found for " + annotationClass.getCanonicalName()); } return BeanProvider.getContextualReference(ViewContextStrategy.class, strategyBean); } private Class<? extends Annotation> findStrategyAnnotation(Class<? extends View> viewClass) { final Annotation[] annotations = viewClass.getAnnotations(); for (Annotation annotation : annotations) { final Class<? extends Annotation> annotationType = annotation.annotationType(); if (annotationType.getAnnotation(ViewContextStrategyQualifier.class) != null) { return annotationType; } } return null; } private Bean findStrategyBean(Class<? extends Annotation> annotationClass) { final Set<Bean<?>> strategyBeans = beanManager.getBeans(ViewContextStrategy.class, ANY_LITERAL); for (Bean<?> strategyBean : strategyBeans) { final Class<?> strategyBeanClass = strategyBean.getBeanClass(); if (ViewContextStrategy.class.isAssignableFrom(strategyBeanClass) && strategyBeanClass.getAnnotation(annotationClass) != null) { return strategyBean; } } return null; } }
package model; @SuppressWarnings("serial") public class MyException extends Exception { public MyException(String s) { System.out.println("MyException = " + s); } }
package com.tcs.ilp.t210.dao; 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 com.tcs.ilp.t210.model.BillAdminBean; import com.tcs.ilp.t210.model.BillBean; import com.tcs.ilp.t210.model.OrderBean; import com.tcs.ilp.t210.model.OrderBillComplaintBean; import com.tcs.ilp.t210.model.UserBean; import com.tcs.ilp.t210.util.DbConnection; public class SimDao { Connection con=null; OrderBean orderObj=null; BillBean billObj=null; ResultSet rs=null; PreparedStatement ps=null; public SimDao() { super(); try { con=DbConnection.getConnection(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public ArrayList<OrderBean> viewAllOrderDetails(int adminId) { ArrayList<OrderBean> orderList=new ArrayList<OrderBean>(); String sql="select * from OrderDetails where spid in(select spId from tag_sp_admin where adminid=?)"; try{ ps=con.prepareStatement(sql); ps.setInt(1, adminId); rs=ps.executeQuery(); while(rs.next()) { orderObj=new OrderBean(); orderObj.setOrderId(rs.getInt(1)); orderObj.setSPID(rs.getInt(2)); orderObj.setOrderDate(rs.getString(3)); orderObj.setQuantity(rs.getInt(4)); orderObj.setOrderStatus(rs.getString(5)); orderObj.setManufacturerId(rs.getInt(6)); orderObj.setPriority(rs.getString(7)); orderObj.setLocation(rs.getString(8)); orderObj.setImsiType(rs.getString(9)); orderObj.setSubscriptionType(rs.getString(10)); orderObj.setDeliveredQuantity(rs.getInt(11)); orderList.add(orderObj); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return orderList; } public OrderBean viewOrderDetailsByOrderId(ArrayList<OrderBean> orderDetail,int orderId) { String sql="select * from OrderDetails where ORDERID=?"; try{ ps=con.prepareStatement(sql); ps.setInt(1, orderId); rs=ps.executeQuery(); while(rs.next()) { orderObj=new OrderBean(); orderObj.setOrderId(rs.getInt(1)); orderObj.setSPID(rs.getInt(2)); orderObj.setOrderDate(rs.getString(3)); orderObj.setQuantity(rs.getInt(4)); orderObj.setOrderStatus(rs.getString(5)); orderObj.setManufacturerId(rs.getInt(6)); orderObj.setPriority(rs.getString(7)); orderObj.setLocation(rs.getString(8)); orderObj.setImsiType(rs.getString(9)); orderObj.setSubscriptionType(rs.getString(10)); orderObj.setDeliveredQuantity(rs.getInt(11)); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return orderObj; } public BillBean billGeneration(OrderBean orderObj) { PreparedStatement ps1=null; PreparedStatement ps2=null; double singleCost=50,bill=0; double dualCost=70; System.out.println("generating"); if(orderObj.getImsiType().equalsIgnoreCase("single")) { bill=singleCost*orderObj.getQuantity(); } else { bill=dualCost*orderObj.getQuantity(); } try{ System.out.println("generating"); String sql="update OrderDetails set ORDERSTATUS='BILL GENERATED' WHERE ORDERID=?"; String sql1="insert into BILL (BILLNO,BILLAMOUNT,BILLSTATUS,ORDERID)VALUES(BILLNO.NEXTVAL,?,'UNPAID',?)"; String sql2="select * from BILL where ORDERID=?"; ps=con.prepareStatement(sql); ps.setInt(1, orderObj.getOrderId()); ps.executeUpdate(); ps1=con.prepareStatement(sql1); ps1.setDouble(1, bill); ps1.setInt(2, orderObj.getOrderId()); ps1.executeUpdate(); ps2=con.prepareStatement(sql2); ps2.setInt(1, orderObj.getOrderId()); System.out.println(bill); rs=ps2.executeQuery(); while(rs.next()) { billObj=new BillBean(); billObj.setBillNo(rs.getInt(1)); billObj.setBillDate(rs.getString(2)); billObj.setBillAmount(rs.getDouble(3)); billObj.setBillStatus(rs.getString(4)); billObj.setPaymentMode(rs.getString(5)); billObj.setOrderId(rs.getInt(6)); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } if(ps1!=null) { ps1.close(); } if(ps2!=null) { ps2.close(); } } catch(SQLException e) { e.printStackTrace(); } } return billObj; } public BillBean billRegeneration(OrderBean orderBill) { PreparedStatement ps1=null; PreparedStatement ps2=null; PreparedStatement ps3=null; double singleCost=50,bill=0; double dualCost=70; BillBean b=null; if(orderBill.getImsiType().equalsIgnoreCase("single")) { bill=singleCost*orderBill.getDeliveredQuantity(); System.out.println(bill); } else { bill=dualCost*orderBill.getDeliveredQuantity(); } try{ String sql="update OrderDetails set ORDERSTATUS='BILL REGENERATED' WHERE ORDERID=?"; String sql1="delete from BILL where orderid=?"; String sql2="insert into BILL (BILLNO,BILLAMOUNT,BILLSTATUS,ORDERID)VALUES(BILLNO.NEXTVAL,?,'UNPAID',?)"; String sql3="select * from BILL where ORDERID=?"; ps=con.prepareStatement(sql); ps.setInt(1, orderBill.getOrderId()); ps.executeUpdate(); ps1=con.prepareStatement(sql1); ps1.setInt(1, orderBill.getOrderId()); ps1.executeUpdate(); System.out.println(bill); ps2=con.prepareStatement(sql2); ps2.setDouble(1, bill); ps2.setInt(2, orderBill.getOrderId()); ps2.executeUpdate(); ps3=con.prepareStatement(sql3); ps3.setInt(1, orderBill.getOrderId()); rs=ps3.executeQuery(); while(rs.next()) { billObj=new BillBean(); billObj.setBillNo(rs.getInt(1)); billObj.setBillDate(rs.getString(2)); billObj.setBillAmount(rs.getDouble(3)); billObj.setBillStatus(rs.getString(4)); billObj.setPaymentMode(rs.getString(5)); billObj.setOrderId(rs.getInt(6)); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } if(ps1!=null) { ps1.close(); } if(ps2!=null) { ps2.close(); } if(ps3!=null) { ps3.close(); } } catch(SQLException e) { e.printStackTrace(); } } return billObj; } public ArrayList<BillAdminBean> viewBills(int adminId) { ArrayList<BillAdminBean> billAdList=new ArrayList<BillAdminBean>(); BillAdminBean billAd=null; //String sql1=" select b.billno,b.billamount,b.billstatus,b.paymentmode,b.orderid,b.billdate,c.complaintstatus from Bill b left join complaintdetails c on b.orderid=c.orderid where b.orderid in(select orderid from orderdetails where spid in(select spid from tag_sp_admin where adminid=?))"; String sql=" select o.spid,b.billno,b.billamount,b.billstatus,b.paymentmode,b.orderid,b.billdate from Bill b left join orderdetails o on b.orderid=o.orderid where spid in(select spid from tag_sp_admin where adminid=?)"; try{ ps=con.prepareStatement(sql); ps.setInt(1, adminId); rs=ps.executeQuery(); while(rs.next()) { billAd=new BillAdminBean(); billAd.setSpid(rs.getInt(1)); billAd.setBillno(rs.getInt(2)); billAd.setBillamount(rs.getDouble(3)); billAd.setBillstatus(rs.getString(4)); billAd.setPaymentmode(rs.getString(5)); billAd.setOrderid(rs.getInt(6)); billAd.setBilldate(rs.getString(7)); billAdList.add(billAd); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return billAdList; } public ArrayList<OrderBean> viewRegenerateBill(int adminId) { ArrayList<OrderBean> orderList=new ArrayList<OrderBean>(); String sql="select * from OrderDetails where QUANTITYAFTERCREATION<QUANTITY and ORDERSTATUS='BILL GENERATED' and spid in(select spid from tag_sp_admin where adminid=?)"; PreparedStatement ps=null; ResultSet rs=null; try{ ps=con.prepareStatement(sql); ps.setInt(1, adminId); rs=ps.executeQuery(); while(rs.next()) { orderObj=new OrderBean(); orderObj.setOrderId(rs.getInt(1)); orderObj.setSPID(rs.getInt(2)); orderObj.setOrderDate(rs.getString(3)); orderObj.setQuantity(rs.getInt(4)); orderObj.setOrderStatus(rs.getString(5)); orderObj.setManufacturerId(rs.getInt(6)); orderObj.setPriority(rs.getString(7)); orderObj.setLocation(rs.getString(8)); orderObj.setImsiType(rs.getString(9)); orderObj.setSubscriptionType(rs.getString(10)); orderObj.setDeliveredQuantity(rs.getInt(11)); orderList.add(orderObj); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return orderList; } public int checkDateDifference(int billNo) { PreparedStatement ps=null; ResultSet rs=null; try{ String sql="(select b.BILLNO from BILL b where (sysdate-BILLDATE)>7 and billstatus='UNPAID' and orderid not in (select orderid from complaintdetails))UNION"+ "(select b.billno from bill b where (sysdate-BILLDATE)>7 and b.billstatus='UNPAID' and orderid in (select orderid from complaintdetails c where b.orderid=c.orderid and c.complaintstatus='RESOLVED' and (sysdate-c.resolveddate)>7))"; ps=con.prepareStatement(sql); rs=ps.executeQuery(); while(rs.next()) { if(rs.getInt(1)==billNo) return 1; } } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return 0; } public ArrayList<OrderBillComplaintBean> viewOrderDetailsByServiceProviderId(int spid) { ArrayList<OrderBillComplaintBean> orderBillComplaintList=new ArrayList<OrderBillComplaintBean>(); String sql="SELECT * FROM OrderDetails od LEFT JOIN BILL b ON od.ORDERID=b.ORDERID LEFT JOIN ComplaintDetails cd ON od.ORDERID=cd.ORDERID where SPID=?"; PreparedStatement ps=null; ResultSet rs=null; try{ ps=con.prepareStatement(sql); ps.setInt(1,spid ); rs=ps.executeQuery(); while(rs.next()) { OrderBillComplaintBean orderObj=new OrderBillComplaintBean(); System.out.println(rs.getString(5)); orderObj.setOrderId(rs.getInt(1)); orderObj.setSPID(rs.getInt(2)); orderObj.setOrderDate(rs.getString(3)); orderObj.setQuantity(rs.getInt(4)); orderObj.setOrderStatus(rs.getString(5)); orderObj.setManufacturerId(rs.getInt(6)); orderObj.setPriority(rs.getString(7)); orderObj.setLocation(rs.getString(8)); orderObj.setImsiType(rs.getString(9)); orderObj.setSubscriptionType(rs.getString(10)); orderObj.setBillNo(rs.getInt(12)); if(rs.getString(15)!=null) { orderObj.setBillStatus(rs.getString(15)); } else { orderObj.setBillStatus("NA"); } if(rs.getString(22)!=null) { orderObj.setComplaintStatus(rs.getString(22)); } else { orderObj.setComplaintStatus("NA"); } orderBillComplaintList.add(orderObj); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return orderBillComplaintList; } public OrderBean viewOrderStatus(int orderId) { orderObj=new OrderBean(); String sql="select * from OrderDetails where ORDERID=?"; PreparedStatement ps=null; ResultSet rs=null; try{ ps=con.prepareStatement(sql); ps.setInt(1,orderId); rs=ps.executeQuery(); while(rs.next()) { orderObj.setOrderStatus(rs.getString(5)); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return orderObj; } public BillBean viewOrderDetailsForOrder(int orderId) { billObj=new BillBean(); String sql="select * from BILL where ORDERID=?"; PreparedStatement ps=null; ResultSet rs=null; try{ ps=con.prepareStatement(sql); ps.setInt(1,orderId); rs=ps.executeQuery(); while(rs.next()) { billObj.setBillNo(rs.getInt(1)); billObj.setBillDate(rs.getString(2)); billObj.setBillAmount(rs.getDouble(3)); billObj.setBillStatus(rs.getString(4)); billObj.setPaymentMode(rs.getString(5)); billObj.setOrderId(rs.getInt(6)); } System.out.println(billObj.getBillStatus()); } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return billObj; } public OrderBillComplaintBean viewOrderBillComplaintDetails(int orderId) { OrderBillComplaintBean objBean1= new OrderBillComplaintBean(); String sql=" SELECT ORDERSTATUS,COMPLAINTSTATUS FROM OrderDetails od LEFT JOIN ComplaintDetails cd ON od.ORDERID=cd.ORDERID WHERE od.ORDERID=?"; PreparedStatement ps=null; ResultSet rs=null; try{ ps=con.prepareStatement(sql); ps.setInt(1,orderId); rs=ps.executeQuery(); while(rs.next()) { objBean1.setOrderStatus(rs.getString(1)); if(rs.getString(2)!=null) { objBean1.setComplaintStatus(rs.getString(2)); } else { objBean1.setComplaintStatus("NA"); } } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return objBean1; } public void updateBillStatus(int orderId) { String sql="update BILL set BILLSTATUS ='PAID' where ORDERID=?"; PreparedStatement ps=null; try{ ps=con.prepareStatement(sql); ps.setInt(1,orderId); int b=ps.executeUpdate(); System.out.println(b); if(b!=0) { System.out.println("Bill Status Updated"); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } } public void updateOrderStatus( int orderId) { String sql="update OrderDetails set ORDERSTATUS='PAID' where ORDERID=?"; PreparedStatement ps=null; try{ ps=con.prepareStatement(sql); ps.setInt(1,orderId); int b=ps.executeUpdate(); if(b!=0) { System.out.println("Order Status Updated"); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } } public void updatePaymentMode(int orderId, String mode) { String sql="update BILL set PAYMENTMODE =? where ORDERID=?"; PreparedStatement ps=null; try{ ps=con.prepareStatement(sql); ps.setString(1,mode); ps.setInt(2,orderId); int b=ps.executeUpdate(); if(b!=0) { System.out.println("Payment mode Updated"); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } } public int checkComplainDateDifference(OrderBillComplaintBean currentBean) { PreparedStatement ps=null; ResultSet rs=null; try{ String sql="(select b.BILLNO from BILL b where (sysdate-BILLDATE)>7 and billstatus='UNPAID' and orderid not in (select c.orderid from complaintdetails c inner join OrderDetails o on c.orderid=o.orderid where o.spid=?))UNION"+ "(select b.billno from bill b where (sysdate-BILLDATE)>7 and b.billstatus='UNPAID' and orderid in (select orderid from complaintdetails c where b.orderid=c.orderid and c.complaintstatus='RESOLVED' and (sysdate-c.resolveddate)>7))"; ps=con.prepareStatement(sql); ps.setInt(1, currentBean.getSPID()); rs=ps.executeQuery(); while(rs.next()) { if(rs.getInt(1)==currentBean.getBillNo()) return 1; } } catch (SQLException e) { // TODO: handle exception e.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return 0; } public ArrayList<OrderBean> viewSPOrderDetails(int spId) { ArrayList<OrderBean> orderList=new ArrayList<OrderBean>(); String sql="select * from OrderDetails where spId=?"; try{ ps=con.prepareStatement(sql); ps.setInt(1, spId); rs=ps.executeQuery(); while(rs.next()) { orderObj=new OrderBean(); orderObj.setOrderId(rs.getInt(1)); orderObj.setSPID(rs.getInt(2)); orderObj.setOrderDate(rs.getString(3)); orderObj.setQuantity(rs.getInt(4)); orderObj.setOrderStatus(rs.getString(5)); orderObj.setManufacturerId(rs.getInt(6)); orderObj.setPriority(rs.getString(7)); orderObj.setLocation(rs.getString(8)); orderObj.setImsiType(rs.getString(9)); orderObj.setSubscriptionType(rs.getString(10)); orderObj.setDeliveredQuantity(rs.getInt(11)); orderList.add(orderObj); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return orderList; } public ArrayList<OrderBean> viewGenerateBillOrder(UserBean adminbean) { ArrayList<OrderBean> orderList=new ArrayList<OrderBean>(); String sql="select * from OrderDetails where orderstatus='CREATED' and spid in(select spId from tag_sp_admin where adminid=?)"; try{ ps=con.prepareStatement(sql); ps.setInt(1, adminbean.getUserId()); rs=ps.executeQuery(); while(rs.next()) { orderObj=new OrderBean(); orderObj.setOrderId(rs.getInt(1)); orderObj.setSPID(rs.getInt(2)); orderObj.setOrderDate(rs.getString(3)); orderObj.setQuantity(rs.getInt(4)); orderObj.setOrderStatus(rs.getString(5)); orderObj.setManufacturerId(rs.getInt(6)); orderObj.setPriority(rs.getString(7)); orderObj.setLocation(rs.getString(8)); orderObj.setImsiType(rs.getString(9)); orderObj.setSubscriptionType(rs.getString(10)); orderObj.setDeliveredQuantity(rs.getInt(11)); orderList.add(orderObj); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return orderList; } public ArrayList<BillBean> viewBillsBySPId(int spId) { ArrayList<BillBean> billList=new ArrayList<BillBean>(); String sql=" select b.billno,b.billamount,b.billstatus,b.paymentmode,b.orderid,b.billdate,c.complaintstatus from Bill b left join complaintdetails c on b.orderid=c.orderid where b.orderid in(select orderid from orderdetails where spid=?)"; try{ ps=con.prepareStatement(sql); ps.setInt(1, spId); rs=ps.executeQuery(); while(rs.next()) { billObj=new BillBean(); billObj.setBillNo(rs.getInt(1)); billObj.setBillAmount(rs.getDouble(2)); billObj.setBillStatus(rs.getString(3)); billObj.setPaymentMode(rs.getString(4)); billObj.setOrderId(rs.getInt(5)); billObj.setBillDate(rs.getString(6)); billObj.setComplaintStatus(rs.getString(7)); billList.add(billObj); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return billList; } public ArrayList<BillBean> viewSPPayBills(int spId){ ArrayList<BillBean> billList=new ArrayList<BillBean>(); String sql="select b.billno,b.billamount,b.billstatus,b.paymentmode,b.orderid,b.billdate,c.complaintstatus from Bill b left join complaintdetails c on b.orderid=c.orderid where b.billstatus='UNPAID' AND b.orderid in(select orderid from orderdetails where spid=?)"; try{ ps=con.prepareStatement(sql); ps.setInt(1, spId); rs=ps.executeQuery(); System.out.println(spId); while(rs.next()) { billObj=new BillBean(); billObj.setBillNo(rs.getInt(1)); billObj.setBillAmount(rs.getDouble(2)); billObj.setBillStatus(rs.getString(3)); billObj.setPaymentMode(rs.getString(4)); billObj.setOrderId(rs.getInt(5)); billObj.setBillDate(rs.getString(6)); billObj.setComplaintStatus(rs.getString(7)); billList.add(billObj); } } catch(SQLException d) { d.printStackTrace(); } finally{ try { if(rs!=null) { rs.close(); } if(ps!=null) { ps.close(); } } catch(SQLException e) { e.printStackTrace(); } } return billList; } }
package com.mysql.cj.protocol.x; import com.google.protobuf.GeneratedMessageV3; import com.mysql.cj.exceptions.WrongArgumentException; import com.mysql.cj.protocol.Message; import com.mysql.cj.protocol.MessageListener; import com.mysql.cj.protocol.ProtocolEntity; import com.mysql.cj.protocol.ProtocolEntityFactory; import com.mysql.cj.protocol.ResultBuilder; import com.mysql.cj.x.protobuf.Mysqlx; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; public class ResultMessageListener<R> implements MessageListener<XMessage> { private ResultBuilder<?> resultBuilder; private CompletableFuture<R> future; private Map<Class<? extends GeneratedMessageV3>, ProtocolEntityFactory<? extends ProtocolEntity, XMessage>> messageToProtocolEntityFactory = new HashMap<>(); public ResultMessageListener(Map<Class<? extends GeneratedMessageV3>, ProtocolEntityFactory<? extends ProtocolEntity, XMessage>> messageToProtocolEntityFactory, ResultBuilder<R> resultBuilder, CompletableFuture<R> future) { this.messageToProtocolEntityFactory = messageToProtocolEntityFactory; this.resultBuilder = resultBuilder; this.future = future; } public boolean processMessage(XMessage message) { Class<? extends GeneratedMessageV3> msgClass = (Class)message.getMessage().getClass(); if (Mysqlx.Error.class.equals(msgClass)) { this.future.completeExceptionally((Throwable)new XProtocolError(Mysqlx.Error.class.cast(message.getMessage()))); } else if (!this.messageToProtocolEntityFactory.containsKey(msgClass)) { this.future.completeExceptionally((Throwable)new WrongArgumentException("Unhandled msg class (" + msgClass + ") + msg=" + message.getMessage())); } else { if (!this.resultBuilder.addProtocolEntity((ProtocolEntity)((ProtocolEntityFactory)this.messageToProtocolEntityFactory.get(msgClass)).createFromMessage(message))) return false; this.future.complete((R)this.resultBuilder.build()); } return true; } public void error(Throwable ex) { this.future.completeExceptionally(ex); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\com\mysql\cj\protocol\x\ResultMessageListener.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package edu.uci.ics.sdcl.firefly.report.predictive; import java.io.BufferedWriter; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Vector; import edu.uci.ics.sdcl.firefly.Answer; import edu.uci.ics.sdcl.firefly.Microtask; import edu.uci.ics.sdcl.firefly.report.descriptive.FileSessionDTO; import edu.uci.ics.sdcl.firefly.util.PropertyManager; /** Selects all first, second and third answers for each Java method */ public class AnswerOrderCounter { ArrayList<Tuple> firstAnswerList; ArrayList<Tuple> secondAnswerList; ArrayList<Tuple> thirdAnswerList; HashMap<String,String> firstWorkerCount; HashMap<String,String> secondWorkerCount; HashMap<String,String> thirdWorkerCount; HashMap<String,String> bugCoveringMap; double minimumDuration_1stAnswer; double maximumDuration_1stAnswer ; double minimumDuration_2ndAnswer; double maximumDuration_2ndAnswer ; double minimumDuration_3rdAnswer; double maximumDuration_3rdAnswer ; public class Tuple{ double TP=0.0; double TN=0.0; double FN=0.0; double FP=0.0; String questionID=null; String javaMethod=null; double duration=0.0; String answerOption=null; boolean isEmpty = false; public String toString(){ if(questionID==null){ isEmpty=true; return ", , , , , , , "; } else return javaMethod+","+questionID+","+duration+","+TP+","+TN+","+FN+","+FP+","+answerOption; } } public AnswerOrderCounter (double minimumDuration_1stAnswer, double maximumDuration_1stAnswer, double minimumDuration_2ndAnswer, double maximumDuration_2ndAnswer, double minimumDuration_3rdAnswer, double maximumDuration_3rdAnswer){ this.minimumDuration_1stAnswer = minimumDuration_1stAnswer; this.maximumDuration_1stAnswer = maximumDuration_1stAnswer; this.minimumDuration_2ndAnswer = minimumDuration_2ndAnswer; this.maximumDuration_2ndAnswer = maximumDuration_2ndAnswer; this.minimumDuration_3rdAnswer = minimumDuration_3rdAnswer; this.maximumDuration_3rdAnswer = maximumDuration_3rdAnswer; //Obtain bug covering question list PropertyManager manager = PropertyManager.initializeSingleton(); bugCoveringMap = new HashMap<String,String>(); String[] listOfBugPointingQuestions = manager.bugCoveringList.split(";"); for(String questionID:listOfBugPointingQuestions){ this.bugCoveringMap.put(questionID,questionID); } //Initialize datastructures this.firstAnswerList = new ArrayList<Tuple>(); this.secondAnswerList = new ArrayList<Tuple>(); this.thirdAnswerList = new ArrayList<Tuple>(); this.firstWorkerCount = new HashMap<String,String>(); this.secondWorkerCount = new HashMap<String,String>(); this.thirdWorkerCount = new HashMap<String,String>(); } /** Builds the three maps of answer duration, which can be printed by * method * @param microtaskMap */ public void buildDurationsByOrder(HashMap<String, Microtask> microtaskMap){ for(Microtask microtask: microtaskMap.values()){ Vector<Answer> answerList = microtask.getAnswerList(); for(Answer answer : answerList){ String order = new Integer(answer.getOrderInWorkerSession()).toString(); Double duration = new Double(answer.getElapsedTime())/1000; //In seconds if(validDuration(order, duration)){ Tuple tuple = computeCorrectness(microtask.getID().toString(),answer.getOption()); tuple.duration = duration; tuple.javaMethod = microtask.getFileName(); tuple.answerOption = answer.getShortOption(); addAnswer(order,tuple,answer.getWorkerId()); } } } } private boolean validDuration(String order, Double duration){ double max = 0.0; double min = 0.0; if(order.compareTo("1")==0){ max = this.maximumDuration_1stAnswer; min = this.minimumDuration_1stAnswer; } else{ if(order.compareTo("2")==0){ max = this.maximumDuration_2ndAnswer; min = this.minimumDuration_2ndAnswer; } else{ if(order.compareTo("3")==0){ max = this.maximumDuration_3rdAnswer; min = this.minimumDuration_3rdAnswer; } else System.out.println("ERROR, INDEX LARGER THAN 3. In AnswerOrderCounter : "+order); } } return (duration<=max&& duration>min); } private void addAnswer(String order,Tuple tuple, String workerID){ //System.out.println(order+":"+duration.toString()); if(order.compareTo("1")==0){ this.firstAnswerList.add(tuple); this.firstWorkerCount.put(workerID, workerID); } else{ if(order.compareTo("2")==0){ this.secondAnswerList.add(tuple); this.secondWorkerCount.put(workerID, workerID); } else{ if(order.compareTo("3")==0){ this.thirdAnswerList.add(tuple); this.thirdWorkerCount.put(workerID, workerID); } else System.out.println("ERROR, INDEX LARGER THAN 3. In AnswerOrderCounter : "+order); } } } private Tuple computeCorrectness(String questionID, String answerOption){ Tuple tuple = new Tuple(); if(this.bugCoveringMap.containsKey(questionID)){ if(answerOption.compareTo(Answer.YES)==0) tuple.TP++; else if(answerOption.compareTo(Answer.NO)==0) //Ignores IDK tuple.FN++; } else{ if(answerOption.compareTo(Answer.NO)==0) tuple.TN++; else if(answerOption.compareTo(Answer.YES)==0) //Ignores IDK tuple.FP++; } tuple.questionID = questionID; return tuple; } private String getDurationOrderFileHeader(){ String header = "FirstJavaMethod,FirstID,FirstDuration, FirstTP, FirstTN, FirstFN, FirstFP,FirstOption,"+ "SecondJavaMethod,SecondID,SecondDuration, SecondTP, SecondTN, SecondFN, SecondFP,SecondOption,"+ "ThirdJavaMethod,ThirdID,ThirdDuration, ThirdTP, ThirdTN, ThirdFN, ThirdFP,ThirdOption"; return header; } public void printDurationOrderLists(){ String destination = "C://firefly//answerOrderDuration.csv"; BufferedWriter log; try { log = new BufferedWriter(new FileWriter(destination)); //Print file header log.write(getDurationOrderFileHeader()+"\n"); boolean allEmpty = false; int i=0; while(!allEmpty){ Tuple firstValue = getElement(firstAnswerList,i); Tuple secondValue = getElement(secondAnswerList,i); Tuple thirdValue = getElement (thirdAnswerList, i); String line= firstValue.toString()+","+ secondValue.toString()+","+thirdValue.toString(); log.write(line+"\n"); if(firstValue.isEmpty && secondValue.isEmpty && thirdValue.isEmpty) allEmpty=true; i++; } log.close(); System.out.println("file written at: "+destination); } catch (Exception e) { System.out.println("ERROR while processing file:" + destination); e.printStackTrace(); } } private Tuple getElement(ArrayList<Tuple> list, int i){ if(list.size()>i) return list.get(i); else return new Tuple(); } private double computeListAccuracy(ArrayList<Tuple> tupleList){ double TP=0.0; double TN=0.0; double FN=0.0; double FP=0.0; for(Tuple tuple: tupleList){ TP = TP + tuple.TP; TN = TN + tuple.TN; FN = FN + tuple.FN; FP = FP + tuple.FP; } double accuracy = (TP+TN)/(TP+TN+FP+FN); return accuracy; } public void printQuartileAccuracy(){ System.out.print("1stAnswer: "+computeListAccuracy(this.firstAnswerList)+"; "); System.out.print("2ndAnswer: "+computeListAccuracy(this.secondAnswerList)+"; "); System.out.println("3rdAnswer: "+computeListAccuracy(this.thirdAnswerList)); } public int getTotalQuartileAnswers(){ return (this.firstAnswerList.size() + this.secondAnswerList.size() + this.thirdAnswerList.size()); } public int getTotalQuartileWorkers(){ return (this.firstAnswerList.size() + this.secondAnswerList.size() + this.thirdAnswerList.size()); } public void printNumberOfAnswersByOrder(){ System.out.print("1stAnswer size: "+this.firstAnswerList.size()+"; "); System.out.print("2ndAnswer size: "+this.secondAnswerList.size()+"; "); System.out.println("3rdAnswer size: "+this.thirdAnswerList.size()); } public void printNumberOfWorkersByOrder(){ System.out.print("1stAnswer Worker Count: "+this.firstWorkerCount.size()+"; "); System.out.print("2ndAnswer Worker Count: "+this.secondWorkerCount.size()+"; "); System.out.println("3rdAnswer Worker Count: "+this.thirdWorkerCount.size()); } public HashMap<String,String> getAllWorkersMap(){ HashMap<String,String> allMap = new HashMap<String, String>(); allMap.putAll(this.firstWorkerCount); allMap.putAll(this.secondWorkerCount); allMap.putAll(this.thirdWorkerCount); return allMap; } public static void main(String args[]){ analyseAllAnswers(); //analysesQuartiles(); } public static void analyseAllAnswers(){ for(int i=0;i<4;i++){ AnswerOrderCounter order = new AnswerOrderCounter(0, 7200,0, 7200,0, 7200); FileSessionDTO sessionDTO = new FileSessionDTO(); HashMap<String,Microtask> microtaskMap = (HashMap<String, Microtask>) sessionDTO.getMicrotasks(); order.buildDurationsByOrder(microtaskMap); order.printDurationOrderLists();//CSV FILE } } public static void analysesQuartiles(){ double[] firstAnswerQuartileVector = {0,167.4,333.4,683.9,3600}; double[] secondAnswerQuartileVector = {0,69.9,134.0,266.4,3600}; double[] thirdAnswerQuartileVector = {0,55.8,104.9,202.6,3600}; HashMap<String, String> distinctWorkersMap = new HashMap<String, String>(); for(int i=0;i<4;i++){ AnswerOrderCounter order = new AnswerOrderCounter(firstAnswerQuartileVector[i], firstAnswerQuartileVector[i+1], secondAnswerQuartileVector[i], secondAnswerQuartileVector[i+1], thirdAnswerQuartileVector[i], thirdAnswerQuartileVector[i+1]); FileSessionDTO sessionDTO = new FileSessionDTO(); HashMap<String,Microtask> microtaskMap = (HashMap<String, Microtask>) sessionDTO.getMicrotasks(); order.buildDurationsByOrder(microtaskMap); order.printDurationOrderLists();//CSV FILE System.out.println(); System.out.print("Quartile "+i +" :"); order.printQuartileAccuracy(); System.out.println("Quartile "+i +" number of answers= " +order.getTotalQuartileAnswers()); order.printNumberOfAnswersByOrder(); System.out.println("Quartile "+i +" number of workers= " +order.getTotalQuartileWorkers()); order.printNumberOfWorkersByOrder(); distinctWorkersMap.putAll(order.getAllWorkersMap()); } System.out.println("Distinct workers in quartile = "+distinctWorkersMap.size()); } }
/* * 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 menuItem; import input.MouseInput; import java.awt.Graphics; import java.awt.Rectangle; import java.awt.image.BufferedImage; import util.Util; /** * * @author Perlt */ public class Button { private BufferedImage image; private Rectangle hitbox; private int x, y; private MouseInput mouse; private boolean render = true, clickAble = true; public Button(String path, int x, int y, MouseInput mouse) { this.x = x; this.y = y; this.mouse = mouse; image = Util.getImage(path); hitbox = new Rectangle(x, y, image.getWidth(), image.getHeight()); } public void update() { } public void render(Graphics g) { if (render) { g.drawImage(image, x, y, null); } } public boolean isClicked() { if (clickAble) { return hitbox.contains(mouse.getX(), mouse.getY()); } return false; } public void setClickAble(boolean clickAble) { this.clickAble = clickAble; } public void setRender(boolean render) { this.render = render; } }
package test.forkjoin; import java.util.concurrent.ExecutionException; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.Future; import java.util.concurrent.RecursiveTask; /** * Created by maguoqiang on 16/9/22. * * fork/join 见java并发编程的艺术 第六章 Fork/join框架。 * 通过fork/join框架做一个简单的需求。计算1+2+3+4的结果 */ public class CountTask extends RecursiveTask<Integer> { private static final int THRESHOLD=2;//阀值 private int start; private int end; public CountTask(int start,int end){ this.start=start; this.end=end; } @Override protected Integer compute() { int sum=0; //如果任务足够小就计算任务 boolean canCompute=(end-start)<=THRESHOLD; if (canCompute){ for (int i = start; i <= end; i++) { sum+=1; } }else { //如果任务大于阀值。就分裂成两个子任务计算 int middle=(end -start)/2; System.out.println("middle is "+middle); CountTask leftTask=new CountTask(start,middle); CountTask rightTask=new CountTask(middle+1,end); System.out.println("zhixing"); //执行子任务 leftTask.fork(); rightTask.fork(); //等待子任务完成,并得到其结果 int leftResult=leftTask.join(); int rightResult=rightTask.join(); //合并子任务 sum=leftResult+rightResult; System.out.println("合并任务完成"); } return sum; } public static void main(String[] args) { ForkJoinPool forkJoinPool=new ForkJoinPool(); //生成一个计算任务,负责计算 1+2+3+4 CountTask task=new CountTask(1,4); //执行一个任务 Future<Integer> result=forkJoinPool.submit(task); try { System.out.println(result.get()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }
package cn.chinaunicom.monitor.beans; /** * Created by yfYang on 2017/10/27. */ public class HostIpEntity { public String ip; public String desc; public String pic; }
package com.rekoe.application.policy; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.handler.timeout.ReadTimeoutException; import org.jboss.netty.handler.timeout.ReadTimeoutHandler; import org.jboss.netty.util.CharsetUtil; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timer; import org.nutz.lang.Files; import org.nutz.log.Log; import org.nutz.log.Logs; import com.rekoe.codec.FlashPolicyServerDecoder; import com.rekoe.mvc.GameContext; import com.rekoe.mvc.IServer; import com.rekoe.mvc.config.GameConfig; /** * @author 科技㊣²º¹³ * Feb 16, 2013 2:35:33 PM * http://www.rekoe.com * QQ:5382211 */ public class PolicyServer extends SimpleChannelUpstreamHandler implements IServer { private Log log = Logs.get(); private final Timer timer = new HashedWheelTimer(); private static final String FLASH_POLICY_FILE = "sample_flash_policy.xml"; private final StringBuffer FLASH_POLICY_STR = new StringBuffer(); private final static int PORT = 843; private static final String NEWLINE = "\r\n"; @Override public void connect(GameConfig config) { GameContext context = config.getGameContext(); ServerBootstrap bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool())); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("timeout", new ReadTimeoutHandler(timer, 30)); pipeline.addLast("decoder", new FlashPolicyServerDecoder()); pipeline.addLast("handler", PolicyServer.this); return pipeline; } }); bootstrap.bind(new InetSocketAddress(PORT)); context.setAttribute("BOOT_STRAP_POLICY", bootstrap); if (log.isInfoEnabled()) log.infof("Flash Server Start application Monitor at Port %s" ,PORT); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelFuture f = e.getChannel().write(this.getPolicyFileContents()); f.addListener(ChannelFutureListener.CLOSE); } private ChannelBuffer getPolicyFileContents() throws Exception { return ChannelBuffers.copiedBuffer(FLASH_POLICY_STR.toString()+ NEWLINE,CharsetUtil.UTF_8); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (e.getCause() instanceof ReadTimeoutException) { log.info("Connection timed out."); e.getChannel().close(); } else { e.getCause().printStackTrace(); e.getChannel().close(); } } @Override public void initMessageExecutor() { FLASH_POLICY_STR.append(Files.read(FLASH_POLICY_FILE)); } @Override public void stopServer() throws Exception { } }
package com.msir.service; import com.msir.pojo.LocationDO; import java.util.List; public interface MTimeService { /** * 以下从时光网上面获取的资源信息 */ int saveLocation(); int saveLocation(LocationDO locationDO); int updateLocation(LocationDO locationDO); int updateLocation(); LocationDO getLocation(String cityName); List<LocationDO> listLocation(); Object getMTimeShowTime(String locationId); Object getMTimeMovieComingNew(String locationId); Object getMTimeMovieDetail(String locationId, String movieId); Object getMTimeMovieCreditsWithTypes(String movieId); Object getMTimeVideo(String pageIndex, String movieId); Object getMTimeImageAll(String movieId); }
package com.brd.brdtools.model.rest; public class RequestParameter { private String beanName; private String sqlQuery; public String getBeanName() { return beanName; } public void setBeanName(String beanName) { this.beanName = beanName; } public String getSqlQuery() { return sqlQuery; } public void setSqlQuery(String sqlQuery) { this.sqlQuery = sqlQuery; } }
package qaInterviewprep; import java.util.ArrayList; import java.util.Arrays; public class reverseStringManual { public static String reverseString(String str) { String newString=""; for (int i= str.length()-1 ; i>=0 ; i--) { newString =newString +str.charAt(i); } return newString; } public static void reverseArrayList(ArrayList<String> arr){ ArrayList<String> reversed =new ArrayList<String>(); for (int i=arr.size()-1; i>=0; i--){ reversed.add(reverseString(arr.get(i))); } System.out.println(reversed); } public static void main(String[] args) { ArrayList<String> myArray =new ArrayList<String>(Arrays.asList("automation ", "bootcamp")); System.out.println(myArray); String newString="automation"; System.out.println(reverseString(newString)); } }
import org.jblas.DoubleMatrix; /** * Created by igoryan on 30.10.15. */ public interface SolverSLAU { final double eps = Math.pow(10, -6); public DoubleMatrix getX(); public void solve(); public int getN(); }
package com.note.model; import java.io.Serializable; /** * Created by nguyenlinh on 21/02/2017. */ public class Notes implements Serializable { private int ID; private String Title; private String Content; private String CreatedDate; private String Alarm; private String Background; // TODO create varilable phoito bitmap private String images; // String image : path+path+path+..... after crack = String.split -> array images[] public Notes(int id, String title, String content, String createdDate, String alarm, String background) { ID = id; Title = title; Content = content; CreatedDate = createdDate; Alarm = alarm; Background = background; } public Notes() { } public int getID() { return ID; } public void setID(int id) { ID = id; } public String getTitle() { return Title; } public void setTitle(String title) { Title = title; } public String getContent() { return Content; } public void setContent(String content) { Content = content; } public String getCreatedDate() { return CreatedDate; } public void setCreatedDate(String createdDate) { CreatedDate = createdDate; } public String getAlarm() { return Alarm; } public void setAlarm(String alarm) { Alarm = alarm; } public String getBackground() { return Background; } public void setBackground(String background) { Background = background; } @Override public String toString() { return this.Title; } public String getImages() { return images; } public void setImages(String images) { this.images = images; } }
package MasterClass.Characters; import MasterClass.Models.Character; import MasterClass.Utils.Messages; import MasterClass.Utils.TimelineFailedException; import java.util.logging.*; public class Gublin extends Character{ private Messages messageManager = new Messages(); private Logger logger = Logger.getLogger(Gublin.class.getName()); public Gublin(int pv, int attack, int attackBonus, int vel, int defense, int dash, int exp, String name) { super(pv, attack, attackBonus, vel, defense, dash, exp, name); } @Override public String getStats() { return String.format("%s: %d de vida, %d de ataque, %d de bonus, %d de velocidad, %d de defensa, %f de dash, %d de experiencia.", this.getName(), this.getPv(), this.getAttack(), this.getAttackBonus(), this.getVel(), this.getDefense(), this.getDash(), this.getExp()); } private int randomNumber(int max , int min){ return (int)(Math.random() * (max - min + 1) + min); } @Override public int dealDamage() { if (this.randomNumber(5 ,1) == 1){ logger.log(Level.INFO, "El gublin fallo y golpeo el suelo."); }else { return this.getAttack() + this.getAttackBonus(); } return 0; } @Override public int receiveDamage(int damage, int enemyVel) { int dashChance = (int) (Math.random() * (10 - this.getDash() + 1) + this.getDash()); int damageReceived = (dashChance > enemyVel) ? damage - this.getDefense() : 0; if (damageReceived == 0) { this.messageManager.getMessage("damageDashed", "", this.getName()); } else { if (randomNumber(5 , 1) == 1) { logger.log(Level.WARNING , "El gublin se asusto y se curo."); heal(randomNumber(5,1)); } this.messageManager.getMessage("damageReceived", String.valueOf(damageReceived), this.getName()); } return damageReceived; } @Override public void heal(int healedPv) { this.setPv(this.getPv() + healedPv); this.messageManager.getMessage("healed", String.valueOf(healedPv), this.getName()); } @Override public boolean isAlive() throws TimelineFailedException { return this.getPv() > 0; } @Override public void levelUp(int expGained) { } }
package models; public enum VehicleType { CAR, MOTORBIKE; @Override public String toString() { return super.toString(); } }
package com.tencent.mm.plugin.sns.model; import com.tencent.mm.bt.h.d; class af$12 implements d { af$12() { } public final String[] xb() { return com.tencent.mm.plugin.sns.storage.d.diD; } }
package Lab05.Zad5; public class Main { public static void main(String[] args) { Decorator printer = new Start(0,0,50); Decorator line1 = new Draw(printer, 10, 10); Decorator line2 = new Draw(line1, 20, 20); Decorator line3 = new Draw(line2, 30, 30); Decorator line4 = new Draw(line3, 40, 40); line4.Position(6,7); System.out.println("Actions: "); System.out.println(line4.History()); System.out.println(); System.out.println("Ink: " + line4.getInk()); } }
package ru.moneydeal.app.pages; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import ru.moneydeal.app.GroupViewModel; import ru.moneydeal.app.IRouter; import ru.moneydeal.app.R; public class GroupFragment extends Fragment { private static String GROUP_ID = "GROUP_ID"; private GroupViewModel mGroupViewModel; private TextView mName; private TextView mDescription; private String mGroupId; private Button mShowStatsButton; public static GroupFragment getInstance(String groupId) { Bundle bundle = new Bundle(); bundle.putString(GROUP_ID, groupId); GroupFragment fragment = new GroupFragment(); fragment.setArguments(bundle); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mGroupViewModel = new ViewModelProvider(getActivity()).get(GroupViewModel.class); View view = inflater.inflate(R.layout.group_fragment, container, false); Bundle bundle = getArguments(); if (bundle == null) { return view; } mGroupId = bundle.getString(GROUP_ID); bindViews(view); createUsersList(); createChecksList(); createAddingParticipant(); return view; } private void bindViews(View view) { mName = view.findViewById(R.id.group_item_name); mDescription = view.findViewById(R.id.group_item_description); bindShowStatsButton(view); } private void bindShowStatsButton(View view) { mShowStatsButton = view.findViewById(R.id.group_show_stat_button); mShowStatsButton.setOnClickListener(v -> { switchToStats(); }); } private void createUsersList() { GroupUsersFragment groupUsers = GroupUsersFragment.getInstance(mGroupId); getChildFragmentManager().beginTransaction() .replace(R.id.group_users_container, groupUsers) .commit(); } private void createChecksList() { GroupChecksFragment groupUsers = GroupChecksFragment.getInstance(mGroupId); getChildFragmentManager().beginTransaction() .replace(R.id.group_checks_container, groupUsers) .commit(); } private void createAddingParticipant() { GroupAddingParticipant fragment = GroupAddingParticipant.getInstance(mGroupId); getChildFragmentManager().beginTransaction() .replace(R.id.group_add_participant_container, fragment) .commit(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { mGroupViewModel.getGroup().observe(getViewLifecycleOwner(), group -> { if (group == null) { return; } mName.setText(group.name); mDescription.setText(group.description); }); if (mGroupId == null) { return; } mGroupViewModel.selectGroup(mGroupId); } private void switchToStats() { IRouter activity = (IRouter) getActivity(); if (activity == null) { return; } activity.showStatistics(mGroupId); } }
package byow.lab12; /** * Draws a world consisting of hexagonal regions. */ public class HexWorld { }
package com.example.dimensionquery; import java.net.URI; import java.net.URISyntaxException; import org.junit.Test; public class WebSocketTest { @Test public void test() { try { // open websocket final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint( new URI("ws://node20.morado.com:10001/pubsub")); // add listener clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() { public void handleMessage(String message) { System.out.println(message); } }); // send message to websocket clientEndPoint.sendMessage("{\"type\":\"subscribe\",\"topic\":\"QueryResult-AppWithDCWithoutDe.0.1\"}"); System.out.println("subscribe topic"); clientEndPoint.sendMessage("{\"type\":\"publish\",\"topic\":\"Query-AppWithDCWithoutDe\",\"data\":{\"id\":0.1,\"type\":\"dataQuery\",\"data\":{\"time\":{\"bucket\":\"10s\",\"latestNumBuckets\":10},\"incompleteResultOK\":true,\"keys\":{\"campaignId\":\"0005c563-dec5-4ec3-b3f4-fb6e084a8f26\"},\"fields\":[\"time\",\"campaignId\",\"latency:MAX\",\"latency:COUNT\",\"latency:SUM\",\"latency:AVG\"]},\"countdown\":299,\"incompleteResultOK\":true}}"); System.out.println("publish topic"); // wait 5 seconds for messages from websocket Thread.sleep(5000); } catch (InterruptedException ex) { System.err.println("InterruptedException exception: " + ex.getMessage()); } catch (URISyntaxException ex) { System.err.println("URISyntaxException exception: " + ex.getMessage()); } } }
package com.tencent.mm.ak.a.a; import android.content.Context; import com.tencent.mm.ak.a.b.c; import com.tencent.mm.ak.a.b.d; import com.tencent.mm.ak.a.b.g; import com.tencent.mm.ak.a.b.i; import com.tencent.mm.ak.a.c.a; import com.tencent.mm.ak.a.c.b; import com.tencent.mm.ak.a.c.e; import com.tencent.mm.ak.a.c.f; import com.tencent.mm.ak.a.c.h; import com.tencent.mm.ak.a.c.j; import com.tencent.mm.ak.a.c.k; import com.tencent.mm.ak.a.c.m; import com.tencent.mm.ak.a.c.n; import java.util.concurrent.Executor; import java.util.concurrent.Executors; public class b$a { Context context; int dXi = b.dXg; int dXj = 5; c dXk = null; public m dXl = null; a dXm = null; public b dXn = null; f dXo = null; j dXp = null; e dXr = null; h dXs = null; Executor dXt; n dXu = null; k dXv = null; public b$a(Context context) { this.context = context.getApplicationContext(); } public final b Ps() { if (this.dXk == null) { this.dXk = new c.a().Pt(); } if (this.dXl == null) { this.dXl = new com.tencent.mm.ak.a.b.f(); } if (this.dXm == null) { this.dXm = new com.tencent.mm.ak.a.b.a(); } if (this.dXn == null) { this.dXn = new com.tencent.mm.ak.a.b.b(); } if (this.dXo == null) { this.dXo = new d(); } if (this.dXp == null) { this.dXp = new i(); } if (this.dXs == null) { this.dXs = a.bf(this.dXi, this.dXj); } if (this.dXt == null) { this.dXt = Executors.newSingleThreadExecutor(); } if (this.dXv == null) { this.dXv = new com.tencent.mm.ak.a.b.e(); } if (this.dXr == null) { this.dXr = new c(); } if (this.dXu == null) { this.dXu = new g(); } return new b(this); } }
package com.jim.multipos.ui.reports.vendor; import android.support.v4.app.Fragment; import com.jim.multipos.config.scope.PerFragment; import dagger.Binds; import dagger.Module; /** * Created by Sirojiddin on 20.01.2018. */ @Module( includes = VendorReportPresenterModule.class ) public abstract class VendorReportFragmentModule { @Binds @PerFragment abstract Fragment provideFragment(VendorReportFragment vendorReportFragment); @Binds @PerFragment abstract VendorReportView provideVendorReportView(VendorReportFragment vendorReportFragment); }
package com.appc.report.model; import com.appc.framework.mybatis.annotation.Query; import com.appc.framework.mybatis.annotation.Where; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.util.Date; /** * CommonRegion * * @author : panda * @version : Ver 1.0 * @date : 2017-9-14 */ @Entity @Table @Data @NoArgsConstructor @Query public class CommonRegion implements Serializable { /** * */ private static final long serialVersionUID = 1L; /** * */ @Id @Where @Getter(onMethod = @__({@ApiModelProperty("")})) @Setter(onMethod = @__({@ApiModelProperty("")})) private java.lang.String commonRegionId; /** * */ @Where @Getter(onMethod = @__({@ApiModelProperty("")})) @Setter(onMethod = @__({@ApiModelProperty("")})) private java.lang.String regionName; /** * */ @Where @Getter(onMethod = @__({@ApiModelProperty("")})) @Setter(onMethod = @__({@ApiModelProperty("")})) private java.lang.String parentRegionId; /** * */ @Where @Getter(onMethod = @__({@ApiModelProperty("")})) @Setter(onMethod = @__({@ApiModelProperty("")})) private java.lang.String regionDescription; /** * */ @Where @Getter(onMethod = @__({@ApiModelProperty("")})) @Setter(onMethod = @__({@ApiModelProperty("")})) private java.lang.String regionPath; private Date createTime; }
package sample; public class User { private int Id; private String Quantity; private String Login; private String Password; public User() { } public int getId() { return Id; } public void setId(Integer id) { Id = id; } public String getQuantity() { return Quantity; } public void setQuantity(String quantity) { Quantity = quantity; } public String getLogin() { return Login; } public void setLogin(String login) { Login = login; } public String getPassword() { return Password; } public void setPassword(String password) { Password = password; } }
package com.septacore.ripple.preprocess.algos; import com.septacore.ripple.preprocess.apps.PPAppBase; import com.septacore.ripple.preprocess.types.PPType; import com.septacore.ripple.preprocess.types.PPTypeString; import java.util.Map; import java.util.HashMap; import java.util.LinkedList; public class Time { private static final int MAX_ENTRIES = 100; private static Map<Integer, Integer> sourceConnections = new HashMap<Integer, Integer>(); private static LinkedList<Integer> ordered100Source = new LinkedList<Integer>(); private static Map<Integer, Integer> destConnections = new HashMap<Integer, Integer>(); private static LinkedList<Integer> ordered100Dest = new LinkedList<Integer>(); public static class PPSource100 extends PPAppBase { public PPSource100() { super(new PPTypeString(), new PPType[] {new PPTypeString()}); } public static Integer source100(String ip) { Integer ipAddress = Integer.parseInt(ip); if (!sourceConnections.containsKey(ipAddress)) { Integer i = 1; sourceConnections.put(ipAddress, i); } else { Integer i = (Integer) sourceConnections.get(ipAddress); i++; sourceConnections.put(ipAddress, i); } ordered100Source.add(ipAddress); if (ordered100Source.size() > MAX_ENTRIES) { Integer oldIP = ordered100Source.removeLast(); Integer i = (Integer) sourceConnections.get(oldIP); i--; sourceConnections.put(oldIP, i); } return (Integer) sourceConnections.get(ipAddress); } @Override public Object applyPreprocessor(Object[] argVals) { return (Object) source100((String)argVals[0]); } } public static class PPDest100 extends PPAppBase { public PPDest100() { super(new PPTypeString(), new PPType[] {new PPTypeString()}); } public static Integer dest100(String ip) { Integer ipAddress = Integer.parseInt(ip); if (!destConnections.containsKey(ipAddress)) { Integer i = 1; destConnections.put(ipAddress, i); } else { Integer i = (Integer) destConnections.get(ipAddress); i++; destConnections.put(ipAddress, i); } ordered100Dest.add(ipAddress); if (ordered100Dest.size() > MAX_ENTRIES) { Integer oldIP = ordered100Dest.removeLast(); Integer i = (Integer) destConnections.get(oldIP); i--; destConnections.put(oldIP, i); } return (Integer) destConnections.get(ipAddress); } @Override public Object applyPreprocessor(Object[] argVals) { return (Object) dest100((String)argVals[0]); } } }
package edu.hust.se.seckill.controller; import edu.hust.se.seckill.domain.MiaoshaOrder; import edu.hust.se.seckill.domain.MiaoshaUser; import edu.hust.se.seckill.domain.OrderInfo; import edu.hust.se.seckill.rabbitmq.MQConfig; import edu.hust.se.seckill.rabbitmq.MQSender; import edu.hust.se.seckill.rabbitmq.MiaoshaMessage; import edu.hust.se.seckill.redis.RedisService; import edu.hust.se.seckill.result.CodeMsg; import edu.hust.se.seckill.result.Result; import edu.hust.se.seckill.service.GoodsService; import edu.hust.se.seckill.service.MiaoshaService; import edu.hust.se.seckill.service.OrderService; import edu.hust.se.seckill.vo.GoodsVo; import org.springframework.amqp.core.AmqpTemplate; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; import static edu.hust.se.seckill.redis.GoodsKey.getMiaoshaGoodsStock; @Controller @RequestMapping("/miaosha") public class MiaoshaController implements InitializingBean { @Autowired private GoodsService goodsService; @Autowired private OrderService orderService; @Autowired private MiaoshaService miaoshaService; @Autowired private RedisService redisService; @Autowired private MQSender mqSender; //系统初始化 @Override public void afterPropertiesSet() throws Exception { List<GoodsVo> goodsVos = goodsService.listGoodsVo(); if(goodsVos == null) { return ; }else { for (GoodsVo goodsVo: goodsVos) { redisService.set(getMiaoshaGoodsStock, ""+goodsVo.getId(),goodsVo.getStockCount()); } } } @RequestMapping("/do_miaosha") @ResponseBody public Result<Integer> doMiaosha(Model model, MiaoshaUser user, @RequestParam("goodsId")long goodsId) { if (user == null) { return Result.error(CodeMsg.SESSION_ERROR); } long stock = redisService.decr(getMiaoshaGoodsStock,""+goodsId); //判断库存 if(stock <= 0) { return Result.error(CodeMsg.MIAO_SHA_OVER); } //判断是否已经秒杀到了 MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId); if (order != null) { return Result.error(CodeMsg.REPEATE_MIAOSHA); } MiaoshaMessage miaoshaMessage = new MiaoshaMessage(); miaoshaMessage.setGoodsId(goodsId); miaoshaMessage.setMiaoshaUser(user); mqSender.sengMiaoshaMessage(miaoshaMessage); return Result.success(0);//排队中 // if (order != null) { // return Result.error(CodeMsg.REPEATE_MIAOSHA); // } // //判断库存 // GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId); // if (goods.getStockCount() <= 0) { // return Result.error(CodeMsg.MIAO_SHA_OVER); // } // //判断是否已经秒杀到了 // MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId); // if (order != null) { // return Result.error(CodeMsg.REPEATE_MIAOSHA); // } // //减库存 下订单 写入秒杀订单 // OrderInfo orderInfo = miaoshaService.miaosha(user, goods); // model.addAttribute("orderInfo", orderInfo); // model.addAttribute("goods", goods); // return Result.success(orderInfo); } /** * 秒杀成功 * orderId:成功 * -1:秒杀失败 * 0:秒杀排队 * @param model * @param user * @param goodsId * @return */ @RequestMapping("/result") @ResponseBody public Result<Long> miaoshaResult(Model model, MiaoshaUser user, @RequestParam("goodsId")long goodsId) { if (user == null) { return Result.error(CodeMsg.SESSION_ERROR); } long result = miaoshaService.getMiaoshaResult(user.getId(), goodsId); return Result.success(result); } }
package com.yongin.blog.blogbackend.service; import com.yongin.blog.blogbackend.dao.BoardDao; import com.yongin.blog.blogbackend.repository.BoardRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service public class BoardService { private BoardRepository boardRepository; @Autowired public BoardService(BoardRepository boardRepository) { this.boardRepository = boardRepository; } // 글쓰기 public BoardDao save(BoardDao boardDao) { boardRepository.save(boardDao); return boardDao; } // 글 목록 불러오기 public List<BoardDao> findAll() { List<BoardDao> boards = new ArrayList<>(); boardRepository.findAll().forEach(e->boards.add(e)); return boards; } // 글 삭제 public void deleteById(Long id) { boardRepository.deleteById(id); } // 좋아요 public Optional<BoardDao> updateById(Long id) { Optional<BoardDao> b = boardRepository.findById(id); if(b.isPresent()){ int likes = b.get().getLikes(); b.get().setLikes(likes+1); boardRepository.save(b.get()); } return b; } }
package com.training.day21.maps; import java.util.HashMap; import java.util.LinkedHashMap; public class SecondHashMap { public static void main(String[] args) { Student s3= new Student(2,"Uttej"); Student s4= new Student(3,"Arshith"); Student s5= new Student(1,"Kalyan"); Student s6= new Student(4,"Varun"); Student s7= new Student(3,"Arshith"); Student s8= new Student(2,"Uttej"); Student s9= new Student(5,"Varun"); Student s10= new Student(1,"Kalyan"); Student s1= new Student(1,"Kalyan"); Student s2= new Student(1,"Kalyan"); HashMap map1 = new HashMap(); map1.put(2, s3); map1.put(3, s4); map1.put(1, s5); map1.put(4, s6); map1.put(3, s7); map1.put(2, s8); map1.put(4, s9); map1.put(1, s10); map1.put(1, s1); map1.put(1, s1); //System.out.println(map1); HashMap lmap = new HashMap(); lmap.put(s3, s3); lmap.put(s6, s6); lmap.put(s9, s9); lmap.put(s8, s8); for (Object o : lmap.keySet()) { Student s = (Student)o; System.out.println("s.getStudentNo()" + s.getStudentNo() + "s.hashCode()" +s.hashCode()); } //System.out.println(lmap); System.out.println(lmap.size()); } }
package ru.mmk.okpposad.client; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Set; import ru.mmk.okpposad.client.datasource.GridDataSource; import com.google.gwt.i18n.client.DateTimeFormat; import com.smartgwt.client.data.Criteria; import com.smartgwt.client.data.DSCallback; import com.smartgwt.client.data.DSRequest; import com.smartgwt.client.data.DSResponse; import com.smartgwt.client.data.Record; import com.smartgwt.client.types.AutoFitWidthApproach; import com.smartgwt.client.widgets.grid.CellFormatter; import com.smartgwt.client.widgets.grid.ListGrid; import com.smartgwt.client.widgets.grid.ListGridField; import com.smartgwt.client.widgets.grid.ListGridRecord; import com.smartgwt.client.widgets.grid.events.CellSavedEvent; import com.smartgwt.client.widgets.grid.events.CellSavedHandler; import com.smartgwt.client.widgets.layout.VLayout; public class ContentLayout extends VLayout { ListGrid grid = new ListGridWithRowSpan(); final DateTimeFormat dateFormat = DateTimeFormat.getFormat("dd/MM/yyyy HH:mm"); private static ContentLayout instance = null; public static ContentLayout getInstance() { if (instance == null) { instance = new ContentLayout(); } return instance; } private ContentLayout() { // grid.setShowFilterEditor(true); grid.setAllowRowSpanning(true); ListGridField rowNumberField = new ListGridField("rowNumber", "#"); rowNumberField.setAutoFitWidth(true); rowNumberField.setAutoFitWidthApproach(AutoFitWidthApproach.BOTH); rowNumberField.setCanFilter(false); ListGridField dateField = new ListGridField("date", "Дата"); dateField.setCanFilter(false); dateField.setWidth(100); dateField.setCellFormatter(new CellFormatter() { public String format(Object value, ListGridRecord record, int rowNum, int colNum) { if (value != null) { // TODO временное решение проблемы отставания на 1 час value = (Long) value + 60 * 60 * 1000; return dateFormat.format(new Date(Long.valueOf((Long) value))); } return null; } }); ListGridField meltNumField = new ListGridField("meltNum", "№ плавки"); meltNumField.setCanFilter(false); ListGridField markField = new ListGridField("mark", "Марка"); ListGridField mnlzNumField = new ListGridField("mnlzNum", "№ МНЛЗ"); ListGridField sectionField = new ListGridField("section", "Сечение"); ListGridField techWasteField = new ListGridField("techWaste", "Техотходы, т"); ListGridField brakField = new ListGridField("brak", "Брак, т"); ListGridField npCountField = new ListGridField("npCount", "НП, шт"); ListGridField npWeightField = new ListGridField("npWeight", "НП, т"); ListGridField lgCountField = new ListGridField("lgCount", "ЛГ, шт"); ListGridField lgWeightField = new ListGridField("lgWeight", "ЛГ, т"); ListGridField reasonField = new ListGridField("reason", "Виновник"); grid.setFields(rowNumberField, dateField, meltNumField, markField, mnlzNumField, sectionField, techWasteField, brakField, npCountField, npWeightField, lgCountField, lgWeightField, reasonField); grid.setDataSource(GridDataSource.getInstance()); addMember(grid); } public void fetchData(Date dateFrom, Date dateTo) { final Criteria criteria = new Criteria(); criteria.addCriteria("dateFrom", dateFrom); criteria.addCriteria("dateTo", dateTo); grid.getDataSource().setCacheAllData(false); grid.getDataSource().fetchData(criteria, new DSCallback() { public void execute(DSResponse dsResponse, Object data, DSRequest dsRequest) { Record[] records = dsResponse.getData(); ListGridRecord[] listGridRecords = new ListGridRecord[records.length]; for (int i = 0; i < records.length; i++) { listGridRecords[i] = new ListGridRecord(records[i].getJsObj()); } grid.getDataSource().setCacheAllData(true); grid.getDataSource().setCacheData(listGridRecords); grid.setData(listGridRecords); } }); } public ListGrid getGrid() { return grid; } public class ListGridWithRowSpan extends ListGrid { public int getRowSpan(ListGridRecord record, int rowNum, int colNum) { Set<Integer> columns = new HashSet<Integer>(Arrays.asList(new Integer[] { 0, 1, 4, 5, 12 })); if (columns.contains(colNum)) return 2; return 1; }; public ListGridWithRowSpan() { addCellSavedHandler(new CellSavedHandler() { @Override public void onCellSaved(CellSavedEvent event) { // ListGridWithRowSpan.this.setEditValue(event.getRowNum(), // event.getColNum(), event.getNewValue()); ListGridWithRowSpan.this.getField("reason").setCanEdit(false); } }); } }; }
import org.junit.*; import org.cse.springtute.*; import java.lang.Exception; public class TestRep { SimpleStudentRepository repo; @Before public void setUp(){ repo = new SimpleStudentRepository(); } @After public void tearDown(){ } @Test public void testSaveStudent() throws Exception{ Student s1 = new Student("Isuru","Jayaweera",100227l,"Veyangoda"); repo.saveStudent(s1); try{ repo.saveStudent(s1); Assert.fail("Exception expected"); } catch(Exception e){ System.out.println("Two students can't have same key"); } } @Test public void testFindStudent() throws Exception{ Student s2 = new Student("Lahiru","Kodikara",100473l,"Gampaha"); repo.saveStudent(s2); try{ Student found = repo.findStudent(100473); System.out.println("Student Found with name : "+found.getFirstName()); } catch(Exception e){ Assert.fail("No exception expected"); } } @Test public void testdeleteStudent()throws Exception{ Student s3 = new Student(); try{ repo.deleteStudent(s3); Assert.fail("Exception expected"); } catch(Exception e){ System.out.println("Student's records are deleted"); } } @Test public void testupdateStudent()throws Exception{ Student s4 = new Student(); try{ repo.updateStudent(s4); Assert.fail("Exception expected"); } catch(Exception e){ System.out.println("No such student exsists"); } } }
package cn.canlnac.onlinecourse.data.repository; import java.io.File; import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; import cn.canlnac.onlinecourse.data.entity.mapper.UploadEntityDataMapper; import cn.canlnac.onlinecourse.data.repository.datasource.UploadDataStore; import cn.canlnac.onlinecourse.data.repository.datasource.UploadDataStoreFactory; import cn.canlnac.onlinecourse.domain.Upload; import cn.canlnac.onlinecourse.domain.repository.UploadRepository; import rx.Observable; /** * 上传数据接口,提供给domain调用. */ @Singleton public class UploadDataRepository implements UploadRepository { private final UploadDataStore uploadDataStore; private final UploadEntityDataMapper uploadEntityDataMapper; @Inject public UploadDataRepository( UploadDataStoreFactory uploadDataStoreFactory, UploadEntityDataMapper uploadEntityDataMapper ) { this.uploadDataStore = uploadDataStoreFactory.create(); this.uploadEntityDataMapper = uploadEntityDataMapper; } @Override public Observable<List<Upload>> uploadFiles(List<File> files) { return uploadDataStore.uploadFiles(files).map(uploadEntityDataMapper::transform); } @Override public Observable<File> download(String fileUrl, File targetFile) { return uploadDataStore.download(fileUrl, targetFile); } }
public class Principal{ public static void main (String[] args){ Acc c = new Acc(1, 6000); Acc c2 = new Acc(2, 5000); Acc c3 = new Acc(3, 4000); System.out.println(Acc.numContas); } }
package br.com.functional.programming.suppliers; import br.com.functional.programming.dto.Person; import org.junit.Assert; import org.junit.Test; import java.util.List; public class SupplierInterfaceTest { @Test public void isPersonListSupplierSuccess() { List<Person> list = SupplierInterface.adhocPersonList.get(); Assert.assertNotNull(list); Assert.assertEquals(2, list.size()); Assert.assertEquals(list.get(0).getName(), SupplierInterface.MATT_NAME); Assert.assertEquals(list.get(1).getName(), SupplierInterface.JANE_NAME); } @Test public void isMattPersonListSupplierSuccess() { Person matt = SupplierInterface.mattFromAdhocPersonList.get(); Assert.assertNotNull(matt); Assert.assertEquals(matt.getName(), SupplierInterface.MATT_NAME); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package classinfo; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; /** * * @author Nathan */ public class ClassFile implements Access { int magic, major_version, minor_version; ConstantPool constant_pool; int access_flags, this_class, super_class; private int[] interfaces; private FieldInfo[] fields; private MethodInfo[] methods; private AttributeInfo[] attributes; public ClassFile(InputStream inputStream) { try { DataInputStream dis = new DataInputStream(inputStream); magic = dis.readInt(); major_version = dis.readUnsignedShort(); minor_version = dis.readUnsignedShort(); constant_pool = new ConstantPool(); constant_pool.read(dis); access_flags = dis.readUnsignedShort(); this_class = dis.readUnsignedShort(); super_class = dis.readUnsignedShort(); { int count = dis.readUnsignedShort(); interfaces = new int[count]; for(int i = 0; i < count; i++) { interfaces[i] = dis.readUnsignedShort(); } } { int count = dis.readUnsignedShort(); fields = new FieldInfo[count]; for(int i = 0; i < count; i++) { fields[i] = new FieldInfo(constant_pool, dis); } } { int count = dis.readUnsignedShort(); methods = new MethodInfo[count]; for(int i = 0; i < count; i++) { methods[i] = new MethodInfo(constant_pool, dis); } } { int count = dis.readUnsignedShort(); attributes = new AttributeInfo[count]; for(int i = 0; i < count; i++) { attributes[i] = AttributeInfo.read(constant_pool, dis); } } } catch (IOException ex) { } } /** * @return the interfaces */ public int[] getInterfaces() { return interfaces; } /** * @return the fields */ public FieldInfo[] getFields() { return fields; } /** * @return the methods */ public MethodInfo[] getMethods() { return methods; } /** * @return the attributes */ public AttributeInfo[] getAttributes() { return attributes; } }
class Task2 { int getThreeNumberCount(int[] numbers) //// counting amount of 3's { int cntr = 0; for (int number : numbers) { while (number > 0) { if (number % 10 == 3) { cntr++; } number /= 10; } } return cntr; } }
package controllers; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Security; import util.HTTPTool; import util.LocalStoreTool; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; /** * Created by shanmao on 15-12-21. */ public class AssetsControllers extends Controller { @Security.Authenticated(Secured.class) public Result getImage(String imagename) { String realfilename = imagename; try { realfilename = URLDecoder.decode(imagename, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if(!imagename.contains(".")){ return notFound(); } byte[] content = LocalStoreTool.getImage(realfilename); response().setContentType(HTTPTool.getContentTypeBySuffix(realfilename)); return ok(content); } }
package com.example.demo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { private final QuoteService quoteService; @Autowired public Controller(QuoteService quoteService) { this.quoteService = quoteService; } @PostMapping(value = "/") public ApiResponse getPost(@RequestBody ApiRequest request) { return quoteService.getQuote(request.getValue()); } }
package com.IRCTradingDataGenerator.tradingDataGenerator.Controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class TestController { @GetMapping("/") public String root() { //TradeField Loan_Amount = new TradeField(1, "Loan_Amount", "0.0"); //TradeType MarginLending = new TradeType("Margin_Lending", "1,2,3,4"); //tradeTypeDao.saveAndFlush(MarginLending); //tradeFieldDao.saveAndFlush(Loan_Amount); return "Index"; } }
package io.github.amitg87.semaphore.problems.readerWriter.v1; import io.github.amitg87.semaphore.lib.LightSwitch; import io.github.amitg87.semaphore.lib.Mutex; import io.github.amitg87.semaphore.lib.Semaphore; import io.github.amitg87.semaphore.util.Runner; import io.github.amitg87.semaphore.util.ThreadUtil; /** * Multiple readers are allowed together, only one writer at a time. * First reader to come in marks the room as occupied, last reader marks room as available. * Writer blocks until room is empty. * * Problem: writer starvation: writer waits for empty room, while reader come and go. */ public class ReaderWriter { private final static int READER_COUNT=10; private final static int WRITER_COUNT=3; private static Semaphore roomEmpty=new Semaphore(); private static int readerCount = 0; private static Mutex mutex = new Mutex(); public static void main(String args[]){ for(int i=1; i<=READER_COUNT; i++){ new Reader("Reader-"+i); } for(int i=1; i<=WRITER_COUNT; i++){ new Writer("Writer-"+i); } } static class Reader extends Runner{ public Reader(String name) { super(name); } @Override public void loop() { ThreadUtil.println("trying to get in"); mutex.enter(); readerCount++; if(readerCount == 1){ //first reader marks room occupied roomEmpty.acquire(); } mutex.leave(); ThreadUtil.println("reading"); ThreadUtil.randomDelay(100); mutex.enter(); readerCount--; if(readerCount == 0){ roomEmpty.release(); } mutex.leave(); ThreadUtil.println("out of room"); ThreadUtil.randomDelay(2000); } } static class Writer extends Runner{ public Writer(String name) { super(name); } @Override public void loop() { ThreadUtil.println("trying to get in"); roomEmpty.acquire(); ThreadUtil.println("writing"); ThreadUtil.randomDelay(100); ThreadUtil.println("out of room"); roomEmpty.release(); ThreadUtil.randomDelay(200); } } }
package com.nks.whatsapp; public class Country { }
package com.test01; import java.awt.*; import javax.swing.JFrame; @SuppressWarnings("serial") public class MTest04 extends JFrame { Panel p1; TextField t1, t2, t3; Label l1, l2, l3; List b1; public MTest04() { super(); p1 = new Panel(); l1 = new Label("A"); l2 = new Label("B"); l3 = new Label("="); t1 = new TextField("", 5); t2 = new TextField("", 5); t3 = new TextField("", 5); b1 = new List(4,false); b1.add("+"); b1.add("-"); b1.add("*"); b1.add("/"); } public void Calc() { p1.add(l1); p1.add(t1); p1.add(b1); p1.add(l2); p1.add(t2); p1.add(l3); p1.add(t3); add(p1); setFont(new Font("±¼¸²", Font.BOLD, 20)); setLayout(new GridLayout(1,7)); setSize(450, 120); setVisible(true); } public static void main(String[] args) { new MTest04().Calc(); } }
package com.paleimitations.schoolsofmagic.client.screen; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import com.paleimitations.schoolsofmagic.References; import com.paleimitations.schoolsofmagic.common.containers.MortarContainer; import com.paleimitations.schoolsofmagic.common.containers.TeapotContainer; import net.minecraft.client.gui.screen.inventory.ContainerScreen; import net.minecraft.client.gui.widget.button.Button; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import java.awt.*; @OnlyIn(Dist.CLIENT) public class TeapotScreen extends ContainerScreen<TeapotContainer> { private static final ResourceLocation TEAPOT_LOCATION = new ResourceLocation(References.MODID, "textures/gui/teapot_gui.png"); public TeapotScreen(TeapotContainer container, PlayerInventory inv, ITextComponent textComponent) { super(container, inv, textComponent); } @Override protected void init() { super.init(); this.updateButtons(); this.inventoryLabelX = 119; } public void render(MatrixStack matrix, int partial, int p_230430_3_, float p_230430_4_) { this.renderBackground(matrix); super.render(matrix, partial, p_230430_3_, p_230430_4_); this.renderTooltip(matrix, partial, p_230430_3_); } private void updateButtons() { } @Override protected void renderBg(MatrixStack matrix, float partial, int p_230450_3_, int p_230450_4_) { this.updateButtons(); RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); this.minecraft.getTextureManager().bind(TEAPOT_LOCATION); this.blit(matrix, leftPos, topPos, 0, 0, this.imageWidth, this.imageHeight); if(this.menu.hasHeat()) this.blit(matrix, leftPos+33, topPos+59, 190, 0, 16, 21); if(this.menu.liquidLevel()>0) { int height = Math.round(41f * (float)this.menu.liquidLevel()/3f); Color color = new Color(menu.liquidColor()); RenderSystem.color4f(color.getRed()/255f, color.getGreen()/255f, color.getBlue()/255f, 1.0F); this.blit(matrix, leftPos+38, topPos+15+41-height, 176, 41-height, 7, height); RenderSystem.color4f(1.0F, 1.0F, 1.0F, 0.5F); this.blit(matrix, leftPos+38, topPos+15+41-height, 220, 41-height, 7, height); this.blit(matrix, leftPos+38, topPos+15+41-height, 220, 0, 7, 1); } if(this.menu.tickHeight() > 0) { RenderSystem.color4f(1.0F, 1.0F, 1.0F, 1.0F); this.blit(matrix, leftPos+115, topPos+5+16-this.menu.tickHeight(), 183, 16-this.menu.tickHeight(), 7, this.menu.tickHeight()); } } }