text
stringlengths
10
2.72M
import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public Class loginauth extends HttpServlet { PreparedStatement ps,ps1; Connection c; public void init(ServletConfig config) { /*try { Class.forName("oracle.jdbc.driver.OracleDriver"); c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager"); // out.println("initt"); } catch(Exception e) { e.printStackTrace(); }*/ } public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter out=res.getWriter(); //out.println("vhjgdyrs"); HttpSession session=req.getSession(); try { try { Class.forName("oracle.jdbc.driver.OracleDriver"); c=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system","manager"); //ps=c.prepareStatement("select rollno from students"); ps1=c.prepareStatement("select rollno,sname from students where rollno=? AND password=? "); //out.println("initt"); } catch(Exception e) { e.printStackTrace(); } out.println("vhjgdyrs"); String rollnof="",passwordf="",rollnodb="",passworddb="",test,sname; int n=0,chkfill=0,cont=0; ResultSet rs = null; rollnof=req.getParameter("rollno").toUpperCase(); passwordf=req.getParameter("password"); out.println("vhjgdyrs"); /*RequestDispatcher rd = req.getRequestDispatcher("/refresh.html"); RequestDispatcher rd1= req.getRequestDispatcher("/regdbvalid.html"); RequestDispatcher rd2= req.getRequestDispatcher("/main1.html"); RequestDispatcher rd4= req.getRequestDispatcher("/newreg.html");*/ //out.println("vhjgdyrs1"); //out.println("HBCTH"); ps1.setString(1,rollnof); ps1.setString(2,passwordf); ps1.executeUpdate(); ResultSet rs1=ps1.getResultSet(); if(rs1.next()==true) { sname=rs1.getString(2); session.setAttribute("rollno",rollnof); session.setAttribute("name",sname); res.sendRedirect("http://localhost:8081/network/main.html"); } else res.sendRedirect("http://localhost:8081/network/refresh.html"); /*rollnodb=rs1.getString(1); passworddb=rs1.getString(2); chkfill=rs1.getInt(3); out.println("roll"+rollnodb+"pass"+passworddb+"chk"+chkfill); } out.println("chk"+chkfill+" rdb "+rollnodb+" pdb "+passworddb); if(chkfill==1) { if((passworddb.equals(passwordf))) { res.sendRedirect("http://localhost:8081/network/main1.html"); } else { //out.println("second time reques"); res.sendRedirect("http://localhost:8081/network/refresh.html"); //rd.forward(req,res); } } else { //rd4.forward(req,res); res.sendRedirect("http://localhost:8081/network/newreg.html"); } } out.println("n value is "+n);*/ rs1.close(); ps1.close(); c.close(); } catch(Exception e) { e.printStackTrace(); } } }
package com.java.practice.datastructure.linkedlist; import java.util.Arrays; import java.util.List; public class SortedArrayToBalancedBST { public static void main(String[] args) { List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6); TreeNode root = sortedArrayToBST(values); traverseInorder(root); } private static TreeNode sortedArrayToBST(List<Integer> values) { if (values.isEmpty()) { return null; } return insertBalanced(values, 0, values.size() - 1); } private static TreeNode insertBalanced(List<Integer> values, int start, int end) { if (start > end) { return null; } int mid = (start + end) / 2; TreeNode node = new TreeNode(values.get(mid)); node.setLeft(insertBalanced(values, start, mid - 1)); node.setRight(insertBalanced(values, mid + 1, end)); return node; } private static void traverseInorder(TreeNode root) { if (root == null) { return; } traverseInorder(root.getLeft()); System.out.print(root.getVal() + " "); traverseInorder(root.getRight()); } } class TreeNode { private int val; private TreeNode left; private TreeNode right; public TreeNode(int val) { this.val = val; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } public int getVal() { return val; } public void setVal(int val) { this.val = val; } }
package com.show.comm.utils.ext; import com.show.comm.utils.StringUtils; /** * 生成随机目录 * * @author HeHongxin * @date 2014-2-10 * */ public class FileFolderRuleRandom extends FileFolderRule { private int length = 0; /** * 生成随机字符文件目录 * * @param 当前时间毫秒13位数字 */ public FileFolderRuleRandom() { } /** * 生成随机字符文件目录 * * @param length * 0:当前时间毫秒13位数字<br/> * 4-15:随机字符串<br/> * 其它:抛出RuntimeException("length>=4 and length<=15") */ public FileFolderRuleRandom(int length) { if (length > 0) { if (length < 4 || length > 15) { throw new RuntimeException("length>=4 and length<=15"); } } this.length = length; } /** * 创建随机目录 */ @Override public String createFolder() { if (length > 0) { return StringUtils.ranStr(length); } else { return String.valueOf(System.currentTimeMillis()); } } }
package com.metoo.module.weixin.view.action; import java.math.BigInteger; 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 java.util.UUID; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.nutz.json.Json; import org.nutz.json.JsonFormat; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.metoo.core.ip.IPSeeker; import com.metoo.core.mv.JModelAndView; import com.metoo.core.security.support.SecurityUserHolder; import com.metoo.core.service.IQueryService; import com.metoo.core.tools.CommUtil; import com.metoo.foundation.domain.Area; import com.metoo.foundation.domain.BuyGift; import com.metoo.foundation.domain.CombinPlan; import com.metoo.foundation.domain.EnoughReduce; import com.metoo.foundation.domain.Favorite; import com.metoo.foundation.domain.FootPoint; import com.metoo.foundation.domain.Goods; import com.metoo.foundation.domain.GoodsCart; import com.metoo.foundation.domain.GoodsClass; import com.metoo.foundation.domain.GoodsLog; import com.metoo.foundation.domain.Group; import com.metoo.foundation.domain.GroupGoods; import com.metoo.foundation.domain.IntegralLog; import com.metoo.foundation.domain.Store; import com.metoo.foundation.domain.User; import com.metoo.foundation.service.IAreaService; import com.metoo.foundation.service.IBuyGiftService; import com.metoo.foundation.service.ICombinPlanService; import com.metoo.foundation.service.IEnoughReduceService; import com.metoo.foundation.service.IFavoriteService; import com.metoo.foundation.service.IFootPointService; import com.metoo.foundation.service.IGoodsCartService; import com.metoo.foundation.service.IGoodsClassService; import com.metoo.foundation.service.IGoodsLogService; import com.metoo.foundation.service.IGoodsService; import com.metoo.foundation.service.IIntegralLogService; import com.metoo.foundation.service.ISysConfigService; import com.metoo.foundation.service.IUserConfigService; import com.metoo.foundation.service.IUserService; import com.metoo.manage.admin.tools.UserTools; import com.metoo.manage.seller.tools.TransportTools; import com.metoo.view.web.tools.ActivityViewTools; import com.metoo.view.web.tools.ConsultViewTools; import com.metoo.view.web.tools.EvaluateViewTools; import com.metoo.view.web.tools.GoodsViewTools; /** * * zhuzhi * */ @Controller public class WeixinOutdoorsGoodsViewAction { @Autowired private ISysConfigService configService; @Autowired private IUserConfigService userConfigService; @Autowired private IGoodsService goodsService; @Autowired private IGoodsClassService goodsClassService; @Autowired private IGoodsCartService goodsCartService; @Autowired private IAreaService areaService; @Autowired private GoodsViewTools goodsViewTools; @Autowired private UserTools userTools; @Autowired private TransportTools transportTools; @Autowired private ConsultViewTools consultViewTools; @Autowired private EvaluateViewTools evaluateViewTools; @Autowired private IUserService userService; @Autowired private IEnoughReduceService enoughReduceService; @Autowired private IFootPointService footPointService; @Autowired private ActivityViewTools activityViewTools; @Autowired private IGoodsLogService goodsLogService; @Autowired private ICombinPlanService combinplanService; @Autowired private IFavoriteService favoriteService; @Autowired private IBuyGiftService buyGiftService; @Autowired private IQueryService queryService; @Autowired private IIntegralLogService integralLogService; /** * 手机客户端商城首页商品详情请求 * * @param request * @param response * @param store_id * @return */ @SuppressWarnings("unused") @RequestMapping("/wap/outdoors_goods_details.htm") public ModelAndView goods(HttpServletRequest request, HttpServletResponse response, String id, String puid) { ModelAndView mv = null; System.out.println("...OutDoors..."); try { User user = SecurityUserHolder.getCurrentUser();// 当前用户 if (StringUtils.isEmpty(puid)) { puid = request.getParameter("puid"); } User parent_user = null; Goods obj = null; // 打开分享内容,建立父子级关系 if (!StringUtils.isEmpty(puid) && !puid.equals(user.getId())) { parent_user = this.userService.getObjByProperty(null, "openId", puid);// 父级用户 if (user.getParent() == null) { user = this.userService.getObjById(user.getId()); if (parent_user != null) { List<User> ulists = new ArrayList<User>(); ulists.add(user); parent_user.setChilds(ulists); this.userService.update(parent_user); user.setParent(parent_user); this.userService.update(user); } // 分享者增加10积分 parent_user.setIntegral(parent_user.getIntegral() + 10); this.userService.save(parent_user); IntegralLog log = new IntegralLog(); log.setAddTime(new Date()); log.setContent("分享商品增加" + this.configService.getSysConfig() .getMemberDayLogin() + "分"); log.setIntegral(this.configService.getSysConfig() .getMemberDayLogin()); log.setIntegral_user(user); log.setType("share"); this.integralLogService.save(log); } } obj = this.goodsService.getObjById(CommUtil.null2Long(id)); // System.out.println("未开启二级域名"); // 利用cookie添加浏览过的商品 Cookie[] cookies = request.getCookies(); Cookie goodscookie = null; int k = 0; if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("goodscookie")) { String goods_ids = cookie.getValue(); int m = 6; int n = goods_ids.split(",").length; if (m > n) { m = n + 1; } String[] new_goods_ids = goods_ids.split(",", m); for (int i = 0; i < new_goods_ids.length; i++) { if ("".equals(new_goods_ids[i])) { for (int j = i + 1; j < new_goods_ids.length; j++) { new_goods_ids[i] = new_goods_ids[j]; } } } String[] new_ids = new String[6]; for (int i = 0; i < m - 1; i++) { if (id.equals(new_goods_ids[i])) { k++; } } if (k == 0) { new_ids[0] = id; for (int j = 1; j < m; j++) { new_ids[j] = new_goods_ids[j - 1]; } goods_ids = id + ","; if (m == 2) { for (int i = 1; i <= m - 1; i++) { goods_ids = goods_ids + new_ids[i] + ","; } } else { for (int i = 1; i < m; i++) { goods_ids = goods_ids + new_ids[i] + ","; } } goodscookie = new Cookie("goodscookie", goods_ids); } else { new_ids = new_goods_ids; goods_ids = ""; for (int i = 0; i < m - 1; i++) { goods_ids += new_ids[i] + ","; } goodscookie = new Cookie("goodscookie", goods_ids); } goodscookie.setMaxAge(60 * 60 * 24 * 7); goodscookie.setDomain(CommUtil.generic_domain(request)); response.addCookie(goodscookie); break; } else { goodscookie = new Cookie("goodscookie", id + ","); goodscookie.setMaxAge(60 * 60 * 24 * 7); goodscookie.setDomain(CommUtil.generic_domain(request)); response.addCookie(goodscookie); } } } else { goodscookie = new Cookie("goodscookie", id + ","); goodscookie.setMaxAge(60 * 60 * 24 * 7); goodscookie.setDomain(CommUtil.generic_domain(request)); response.addCookie(goodscookie); } boolean admin_view = false;// 超级管理员可以查看未审核得到商品信息 if (user != null) { // 登录用户记录浏览足迹信息 Map<String, Object> params = new HashMap<String, Object>(); params.put("fp_date", CommUtil.formatDate(CommUtil .formatShortDate(new Date()))); params.put("fp_user_id", user.getId()); List<FootPoint> fps = this.footPointService .query("select obj from FootPoint obj where obj.fp_date=:fp_date and obj.fp_user_id=:fp_user_id", params, -1, -1); if (fps.size() == 0) { FootPoint fp = new FootPoint(); fp.setAddTime(new Date()); fp.setFp_date(new Date()); fp.setFp_user_id(user.getId()); fp.setFp_user_name(user.getUsername()); fp.setFp_goods_count(1); Map<String, Object> map = new HashMap<String, Object>(); map.put("goods_id", obj.getId()); map.put("goods_name", obj.getGoods_name()); map.put("goods_sale", obj.getGoods_salenum()); map.put("goods_time", CommUtil.formatLongDate(new Date())); map.put("goods_img_path", obj.getGoods_main_photo() != null ? CommUtil .getURL(request) + "/" + obj.getGoods_main_photo().getPath() + "/" + obj.getGoods_main_photo().getName() : CommUtil.getURL(request) + "/" + this.configService.getSysConfig() .getGoodsImage().getPath() + "/" + this.configService.getSysConfig() .getGoodsImage().getName()); map.put("goods_price", obj.getGoods_current_price()); map.put("goods_class_id", CommUtil.null2Long(obj.getGc().getId())); map.put("goods_class_name", CommUtil.null2String(obj.getGc().getClassName())); List<Map> list = new ArrayList<Map>(); list.add(map); fp.setFp_goods_content(Json.toJson(list, JsonFormat.compact())); this.footPointService.save(fp); } else { FootPoint fp = fps.get(0); List<Map> list = Json.fromJson(List.class, fp.getFp_goods_content()); boolean add = true; for (Map map : list) {// 排除重复的商品足迹 if (CommUtil.null2Long(map.get("goods_id")).equals( obj.getId())) { add = false; } } if (add) { Map<String, Object> map = new HashMap<String, Object>(); map.put("goods_id", obj.getId()); map.put("goods_name", obj.getGoods_name()); map.put("goods_sale", obj.getGoods_salenum()); map.put("goods_time", CommUtil.formatLongDate(new Date())); map.put("goods_img_path", obj.getGoods_main_photo() != null ? CommUtil .getURL(request) + "/" + obj.getGoods_main_photo().getPath() + "/" + obj.getGoods_main_photo().getName() : CommUtil.getURL(request) + "/" + this.configService .getSysConfig() .getGoodsImage() .getPath() + "/" + this.configService .getSysConfig() .getGoodsImage() .getName()); map.put("goods_price", obj.getGoods_current_price()); map.put("goods_class_id", CommUtil.null2Long(obj.getGc().getId())); map.put("goods_class_name", CommUtil.null2String(obj .getGc().getClassName())); list.add(0, map);// 后浏览的总是插入最前面 fp.setFp_goods_count(list.size()); fp.setFp_goods_content(Json.toJson(list, JsonFormat.compact())); this.footPointService.update(fp); } } if (("ADMIN").equals(user.getUserRole())) { admin_view = true; } } // 记录商品点击日志 if (obj != null) { GoodsLog todayGoodsLog = this.goodsViewTools .getTodayGoodsLog(obj.getId()); todayGoodsLog .setGoods_click(todayGoodsLog.getGoods_click() + 1); String click_from_str = todayGoodsLog.getGoods_click_from(); Map<String, Integer> clickmap = (click_from_str != null && !click_from_str .equals("")) ? (Map<String, Integer>) Json .fromJson(click_from_str) : new HashMap<String, Integer>(); String from = clickfrom_to_chinese(CommUtil.null2String(request .getParameter("from"))); if (from != null && !from.equals("")) { if (clickmap.containsKey(from)) { clickmap.put(from, clickmap.get(from) + 1); } else { clickmap.put(from, 1); } } else { if (clickmap.containsKey("unknow")) { clickmap.put("unknow", clickmap.get("unknow") + 1); } else { clickmap.put("unknow", 1); } } todayGoodsLog.setGoods_click_from(Json.toJson(clickmap, JsonFormat.compact())); this.goodsLogService.update(todayGoodsLog); } if (obj != null && obj.getGoods_status() == 0 || admin_view) { if (obj.getGoods_type() == 0) {// 平台自营商品 mv = new JModelAndView("wap/outdoors_goods_details.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 1, request, response); obj.setGoods_click(obj.getGoods_click() + 1); if (this.configService.getSysConfig().isZtc_status() && obj.getZtc_status() == 2) { obj.setZtc_click_num(obj.getZtc_click_num() + 1); } boolean groupFlag = false; GroupGoods gg = null; List<GroupGoods> ggList = obj.getGroup_goods_list(); if (null != ggList && 0 < ggList.size()) { for (GroupGoods ggs : ggList) { if (ggs.getGg_status() == 1) { gg = ggs; groupFlag = true; } } } /* if (obj.getGroup() != null && obj.getGroup_buy() == 2) { */// 如果是团购商品,检查团购是否过期 if (groupFlag) { mv = new JModelAndView("wap/goods_group_details.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 1, request, response); mv.addObject("groupObj", gg); // 判断当前用户是否已经参加团购(开团或参团) Long userId = user.getId(); Long gid = gg.getId(); Map<String, Object> params = new HashMap<String, Object>(); params.put("gid", gid); params.put("userId", userId); String qSql = "SELECT count(1) from metoo_group_joiner a, metoo_group_goods b " + "where " + "a.rela_group_goods_id=b.id " + "and a.status=1 " + "and b.gg_status=1 " + "and b.id=:gid " + "and a.create_time > b.beginTime " + "and a.create_time < b.endTime " + " and now() < date_sub(a.create_time,interval - b.gg_max_count HOUR) " + " and now() > a.create_time " + "and a.user_id=:userId"; List tList = this.queryService.nativeQuery(qSql, params, -1, -1); String jGFlag = "0"; if (null != tList && 0 < tList.size()) { BigInteger oa = (BigInteger) tList.get(0); long count = oa.longValue(); if (count > 0) { jGFlag = "1"; } } mv.addObject("jGFlag", jGFlag); mv.addObject("group_gid", gid); List list = null; if (jGFlag.equals("1")) { // 已经参加团购,查询当前用户参加团的信息:参加人昵称、图像、团剩余时间、剩余人数 String nql = "SELECT t.rela_group_goods_id, t.child_group_id, t1.trueName, t1.headImgUrl, (t2.gg_group_count-t.joiner_count), t.is_group_creator, " + " (UNIX_TIMESTAMP(date_sub(t.create_time,interval - t2.gg_max_count HOUR)) - UNIX_TIMESTAMP(now())), DATE_ADD(t.create_time, INTERVAL t2.gg_max_count HOUR) from metoo_group_joiner t, " + " metoo_user t1, metoo_group_goods t2 where t.user_id=t1.id and t.rela_group_goods_id=t2.id " + " and t.status=1 and t2.gg_status=1" + " and now() < date_sub(t.create_time,interval - t2.gg_max_count HOUR) " + " and now() > t.create_time " + " and t.child_group_id in ( " + " SELECT a.child_group_id from metoo_group_joiner a where a.user_id=:userId and a.rela_group_goods_id=:gid) " + " order by t.is_group_creator desc"; list = this.queryService.nativeQuery(nql, params, -1, -1); if (null != list && list.size() > 0) { mv.addObject("group_my_flag", "yes"); } } else { // 未参加团购,查询可参团列表信息:参加人昵称、图像、团剩余时间、剩余人数 String sql = "SELECT t.rela_group_goods_id, t.child_group_id, t1.trueName, t1.headImgUrl, (t2.gg_group_count-t.joiner_count), t.is_group_creator, " + " (UNIX_TIMESTAMP(date_sub(t.create_time,interval - t2.gg_max_count HOUR)) - UNIX_TIMESTAMP(now())), DATE_ADD(t.create_time, INTERVAL t2.gg_max_count HOUR) from metoo_group_joiner t, metoo_user t1, metoo_group_goods t2 where" + " t.user_id=t1.id and t.rela_group_goods_id=t2.id and t2.gg_status=1" + " and t.user_id!=:userId" + " and t.rela_group_goods_id=:gid and t.status='1'" + " and is_group_creator = '1'" + " and now() < date_sub(t.create_time,interval - t2.gg_max_count HOUR)" + " and (t2.gg_group_count-t.joiner_count) > 0" + " and now() > t.create_time order by (t2.gg_group_count-t.joiner_count), t.create_time asc"; if (null != parent_user) { Map<String, Object> tmp = new HashMap<String, Object>(); tmp.put("gid", gid); tmp.put("userId", parent_user.getId()); List ssList = this.queryService.nativeQuery( qSql, tmp, -1, -1); if (null != ssList && 0 < ssList.size()) { BigInteger oa = (BigInteger) ssList.get(0); long count = oa.longValue(); if (count > 0) { String nql = "SELECT t.rela_group_goods_id, t.child_group_id, t1.trueName, t1.headImgUrl, (t2.gg_group_count-t.joiner_count), t.is_group_creator, " + " (UNIX_TIMESTAMP(date_sub(t.create_time,interval - t2.gg_max_count HOUR)) - UNIX_TIMESTAMP(now())), DATE_ADD(t.create_time, INTERVAL t2.gg_max_count HOUR) from metoo_group_joiner t, " + " metoo_user t1, metoo_group_goods t2 where t.user_id=t1.id and t.rela_group_goods_id=t2.id " + " and t.status=1 and t2.gg_status=1" + " and now() < date_sub(t.create_time,interval - t2.gg_max_count HOUR) " + " and now() > t.create_time " + " and t.child_group_id in ( " + " SELECT a.child_group_id from metoo_group_joiner a where a.user_id=:userId and a.rela_group_goods_id=:gid) " + " and t.is_group_creator='1'" + " order by t.is_group_creator desc"; list = this.queryService.nativeQuery( nql, tmp, -1, -1); } else { list = this.queryService.nativeQuery( sql, params, -1, -1); } } } else { list = this.queryService.nativeQuery(sql, params, -1, -1); } if (null != list && list.size() > 0) { mv.addObject("group_child_flag", "yes"); } } List<Map<String, Object>> nList = new ArrayList<Map<String, Object>>(); Map<String, Object> map; if (null != list && list.size() > 0) { if (jGFlag.equals("0")) { int index = 0; for (Object o : list) { if (index <= 1) { Object[] oa = (Object[]) o; map = new HashMap<String, Object>(); map.put("ggid", oa[0]); map.put("cgid", oa[1]); map.put("userName", oa[2]); map.put("imgUrl", oa[3]); map.put("joinerCount", oa[4]); map.put("isCreator", oa[5]); BigInteger rt = (BigInteger) oa[6]; String remainTime = secToTime(rt .intValue()); map.put("remainTime", remainTime); Date endTime = (Date) oa[7]; Calendar endC = Calendar.getInstance(); endC.setTime(endTime); int endYear = endC.get(Calendar.YEAR); int endMonth = endC.get(Calendar.MONTH); int endDay = endC .get(Calendar.DAY_OF_MONTH); int endHour = endC .get(Calendar.HOUR_OF_DAY); int endMin = endC.get(Calendar.MINUTE); int endSec = endC.get(Calendar.SECOND); map.put("endTime", (Date) oa[7]); map.put("endYear", endYear); map.put("endMonth", endMonth); map.put("endDay", endDay); map.put("endHour", endHour); map.put("endMin", endMin); map.put("endSec", endSec); nList.add(map); index++; } } } else { for (Object o : list) { Object[] oa = (Object[]) o; map = new HashMap<String, Object>(); map.put("ggid", oa[0]); map.put("cgid", oa[1]); map.put("userName", oa[2]); map.put("imgUrl", oa[3]); map.put("joinerCount", oa[4]); map.put("isCreator", oa[5]); BigInteger rt = (BigInteger) oa[6]; String remainTime = secToTime(rt.intValue()); map.put("remainTime", remainTime); Date endTime = (Date) oa[7]; Calendar endC = Calendar.getInstance(); endC.setTime(endTime); int endYear = endC.get(Calendar.YEAR); int endMonth = endC.get(Calendar.MONTH); int endDay = endC .get(Calendar.DAY_OF_MONTH); int endHour = endC .get(Calendar.HOUR_OF_DAY); int endMin = endC.get(Calendar.MINUTE); int endSec = endC.get(Calendar.SECOND); map.put("endTime", (Date) oa[7]); map.put("endYear", endYear); map.put("endMonth", endMonth); map.put("endDay", endDay); map.put("endHour", endHour); map.put("endMin", endMin); map.put("endSec", endSec); nList.add(map); } } } mv.addObject("groupJoinList", nList); obj.setGroup_buy(2); obj.setGoods_current_price(gg.getGg_price()); } if (obj.getCombin_status() == 1) {// 如果是组合商品,检查组合是否过期 Map<String, Object> params = new HashMap<String, Object>(); params.put("endTime", new Date()); params.put("main_goods_id", obj.getId()); List<CombinPlan> combins = this.combinplanService .query("select obj from CombinPlan obj where obj.endTime<=:endTime and obj.main_goods_id=:main_goods_id", params, -1, -1); if (combins.size() > 0) { for (CombinPlan com : combins) { if (com.getCombin_type() == 0) { if (obj.getCombin_suit_id().equals( com.getId())) { obj.setCombin_suit_id(null); } } else { if (obj.getCombin_parts_id().equals( com.getId())) { obj.setCombin_parts_id(null); } } obj.setCombin_status(0); } } } if (obj.getOrder_enough_give_status() == 1) { BuyGift bg = this.buyGiftService.getObjById(obj .getBuyGift_id()); if (bg != null && bg.getEndTime().before(new Date())) { bg.setGift_status(20); List<Map> maps = Json.fromJson(List.class, bg.getGift_info()); maps.addAll(Json.fromJson(List.class, bg.getGoods_info())); for (Map map : maps) { Goods goods = this.goodsService .getObjById(CommUtil.null2Long(map .get("goods_id"))); if (goods != null) { goods.setOrder_enough_give_status(0); goods.setOrder_enough_if_give(0); goods.setBuyGift_id(null); this.goodsService.update(goods); } } this.buyGiftService.update(bg); } if (bg != null && bg.getGift_status() == 10) { mv.addObject("isGift", true); } } if (obj.getOrder_enough_if_give() == 1) { BuyGift bg = this.buyGiftService.getObjById(obj .getBuyGift_id()); if (bg != null && bg.getGift_status() == 10) { mv.addObject("isGive", true); } } this.goodsService.update(obj); if (obj.getEnough_reduce() == 1) {// 如果是满就减商品,未到活动时间不作处理,活动时间显示满减信息,已过期则删除满减信息 EnoughReduce er = this.enoughReduceService .getObjById(CommUtil.null2Long(obj .getOrder_enough_reduce_id())); if (er.getErstatus() == 10 && er.getErbegin_time().before(new Date()) && er.getErend_time().after(new Date())) {// 正在进行 mv.addObject("enoughreduce", er); } } mv.addObject("obj", obj); mv.addObject("goodsViewTools", goodsViewTools); mv.addObject("transportTools", transportTools); mv.addObject("parent_user", parent_user); // 计算当期访问用户的IP地址,并计算对应的运费信息 String current_ip = CommUtil.getIpAddr(request);// 获得本机IP if (CommUtil.isIp(current_ip)) { IPSeeker ip = new IPSeeker(null, null); String current_city = ip.getIPLocation(current_ip) .getCountry(); mv.addObject("current_city", current_city); } else { mv.addObject("current_city", "未知地区"); } // 查询运费地区 List<Area> areas = this.areaService .query("select obj from Area obj where obj.parent.id is null order by obj.sequence asc", null, -1, -1); mv.addObject("areas", areas); mv.addObject("userTools", userTools); mv.addObject("goodsViewTools", goodsViewTools); mv.addObject("activityViewTools", activityViewTools); if (SecurityUserHolder.getCurrentUser() != null) { Map<String, Object> map = new HashMap<String, Object>(); map.put("gid", obj.getId()); map.put("uid", SecurityUserHolder.getCurrentUser() .getId()); List<Favorite> favorites = this.favoriteService .query("select obj from Favorite obj where obj.goods_id=:gid and obj.user_id=:uid", map, -1, -1); if (favorites.size() > 0) { mv.addObject("mark", 1); } } String type = CommUtil.null2String(request .getAttribute("type")); String cart_session_id = ""; Cookie[] cookies1 = request.getCookies(); if (cookies1 != null) { for (Cookie cookie : cookies1) { if (cookie.getName().equals("cart_session_id")) { cart_session_id = CommUtil.null2String(cookie .getValue()); } } } if (cart_session_id.equals("")) { cart_session_id = UUID.randomUUID().toString(); Cookie cookie = new Cookie("cart_session_id", cart_session_id); cookie.setDomain(CommUtil.generic_domain(request)); } List<GoodsCart> carts_list = new ArrayList<GoodsCart>();// 用户整体购物车 List<GoodsCart> carts_cookie = new ArrayList<GoodsCart>();// 未提交的用户cookie购物车 List<GoodsCart> carts_user = new ArrayList<GoodsCart>();// 未提交的用户user购物车 Map<String, Object> cart_map = new HashMap<String, Object>(); if (user != null) { // user = userService.getObjById(user.getId()); if (!cart_session_id.equals("")) { cart_map.clear(); cart_map.put("cart_session_id", cart_session_id); cart_map.put("cart_status", 0); carts_cookie = this.goodsCartService .query("select obj from GoodsCart obj where obj.cart_session_id=:cart_session_id and obj.cart_status=:cart_status ", cart_map, -1, -1); // 如果用户拥有自己的店铺,删除carts_cookie购物车中自己店铺中的商品信息 cart_map.clear(); cart_map.put("user_id", user.getId()); cart_map.put("cart_status", 0); carts_user = this.goodsCartService .query("select obj from GoodsCart obj where obj.user.id=:user_id and obj.cart_status=:cart_status ", cart_map, -1, -1); } else { cart_map.clear(); cart_map.put("user_id", user.getId()); cart_map.put("cart_status", 0); carts_user = this.goodsCartService .query("select obj from GoodsCart obj where obj.user.id=:user_id and obj.cart_status=:cart_status ", cart_map, -1, -1); } } else { if (!cart_session_id.equals("")) { cart_map.clear(); cart_map.put("cart_session_id", cart_session_id); cart_map.put("cart_status", 0); carts_cookie = this.goodsCartService .query("select obj from GoodsCart obj where obj.cart_session_id=:cart_session_id and obj.cart_status=:cart_status ", cart_map, -1, -1); } } // 将cookie购物车与user购物车合并,并且去重 if (user != null) { for (GoodsCart cookie : carts_cookie) { boolean add = true; for (GoodsCart gc2 : carts_user) { if (cookie.getGoods().getId() .equals(gc2.getGoods().getId())) { if (cookie.getSpec_info().equals( gc2.getSpec_info())) { add = false; this.goodsCartService.delete(cookie .getId()); } } } if (add) {// 将cookie去重并添加到cart_list中 cookie.setCart_session_id(null); cookie.setUser(user); this.goodsCartService.update(cookie); carts_list.add(cookie); } } } else { for (GoodsCart gc : carts_cookie) {// 将carts_cookie添加到cart_list中 carts_list.add(gc); } } for (GoodsCart gc : carts_user) {// 将carts_user添加到cart_list中 carts_list.add(gc); } // 组合套装处理,只显示套装主购物车,套装内其他购物车不显示 List<GoodsCart> combin_carts_list = new ArrayList<GoodsCart>(); for (GoodsCart gc : carts_list) { if (gc.getCart_type() != null && gc.getCart_type().equals("combin")) { if (gc.getCombin_main() != 1) { combin_carts_list.add(gc); } } } if (combin_carts_list.size() > 0) { carts_list.removeAll(combin_carts_list); } mv.addObject("carts", carts_list); } else { mv = new JModelAndView("wap/outdoors_goods_details.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 1, request, response); obj.setGoods_click(obj.getGoods_click() + 1); if (this.configService.getSysConfig().isZtc_status() && obj.getZtc_status() == 2) { obj.setZtc_click_num(obj.getZtc_click_num() + 1); } if (obj.getGroup() != null && obj.getGroup_buy() == 2) {// 如果是团购商品,检查团购是否过期 Group group = obj.getGroup(); if (group.getEndTime().before(new Date())) { obj.setGroup(null); obj.setGroup_buy(0); obj.setGoods_current_price(obj.getStore_price()); } } if (obj.getCombin_status() == 1) {// 如果是组合商品,检查组合是否过期 Map<String, Object> params = new HashMap<String, Object>(); params.put("endTime", new Date()); params.put("main_goods_id", obj.getId()); List<CombinPlan> combins = this.combinplanService .query("select obj from CombinPlan obj where obj.endTime<=:endTime and obj.main_goods_id=:main_goods_id", params, -1, -1); if (combins.size() > 0) { for (CombinPlan com : combins) { if (com.getCombin_type() == 0) { if (obj.getCombin_suit_id().equals( com.getId())) { obj.setCombin_suit_id(null); } } else { if (obj.getCombin_parts_id().equals( com.getId())) { obj.setCombin_parts_id(null); } } obj.setCombin_status(0); } } } if (obj.getOrder_enough_give_status() == 1) { BuyGift bg = this.buyGiftService.getObjById(obj .getBuyGift_id()); if (bg != null && bg.getEndTime().before(new Date())) { bg.setGift_status(20); List<Map> maps = Json.fromJson(List.class, bg.getGift_info()); maps.addAll(Json.fromJson(List.class, bg.getGoods_info())); for (Map map : maps) { Goods goods = this.goodsService .getObjById(CommUtil.null2Long(map .get("goods_id"))); if (goods != null) { goods.setOrder_enough_give_status(0); goods.setOrder_enough_if_give(0); goods.setBuyGift_id(null); this.goodsService.update(goods); } } this.buyGiftService.update(bg); } if (bg != null && bg.getGift_status() == 10) { mv.addObject("isGift", true); } } if (obj.getOrder_enough_if_give() == 1) { BuyGift bg = this.buyGiftService.getObjById(obj .getBuyGift_id()); if (bg != null && bg.getGift_status() == 10) { mv.addObject("isGive", true); } } this.goodsService.update(obj); if (obj.getEnough_reduce() == 1) {// 如果是满就减商品,未到活动时间不作处理,活动时间显示满减信息 EnoughReduce er = this.enoughReduceService .getObjById(CommUtil.null2Long(obj .getOrder_enough_reduce_id())); if (er.getErstatus() == 10 && er.getErbegin_time().before(new Date()) && er.getErend_time().after(new Date())) {// 正在进行 mv.addObject("enoughreduce", er); } } // if (obj.getGoods_store().getStore_status() == 15) {// // 店铺为开通状态 mv.addObject("obj", obj); mv.addObject("store", obj.getGoods_store()); mv.addObject("goodsViewTools", goodsViewTools); mv.addObject("transportTools", transportTools); // 计算当期访问用户的IP地址,并计算对应的运费信息 String current_ip = CommUtil.getIpAddr(request);// 获得本机IP if (CommUtil.isIp(current_ip)) { IPSeeker ip = new IPSeeker(null, null); String current_city = ip.getIPLocation(current_ip) .getCountry(); mv.addObject("current_city", current_city); } else { mv.addObject("current_city", "未知地区"); } // 查询运费地区 List<Area> areas = this.areaService .query("select obj from Area obj where obj.parent.id is null order by obj.sequence asc", null, -1, -1); mv.addObject("areas", areas); this.generic_evaluate(obj.getGoods_store(), mv); mv.addObject("userTools", userTools); mv.addObject("goodsViewTools", goodsViewTools); mv.addObject("activityViewTools", activityViewTools); } // 查询评论次数 int evaluates_count = this.evaluateViewTools.queryByEva( obj.getId().toString(), "all").size(); mv.addObject("evaluates_count", evaluates_count); int consul_count = this.consultViewTools.queryByType(null, obj.getId().toString()).size(); mv.addObject("consul_count", consul_count); } else { mv = new JModelAndView("wap/error.html", configService.getSysConfig(), this.userConfigService.getUserConfig(), 1, request, response); mv.addObject("op_title", "参数错误,商品查看失败"); mv.addObject("url", CommUtil.getURL(request) + "/index.htm"); } } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } return mv; } /** * 加载店铺评分信息 * * @param store * @param mv */ private void generic_evaluate(Store store, ModelAndView mv) { double description_result = 0; double service_result = 0; double ship_result = 0; GoodsClass gc = this.goodsClassService .getObjById(store.getGc_main_id()); if (store != null && gc != null && store.getPoint() != null) { float description_evaluate = CommUtil.null2Float(gc .getDescription_evaluate()); float service_evaluate = CommUtil.null2Float(gc .getService_evaluate()); float ship_evaluate = CommUtil.null2Float(gc.getShip_evaluate()); float store_description_evaluate = CommUtil.null2Float(store .getPoint().getDescription_evaluate()); float store_service_evaluate = CommUtil.null2Float(store.getPoint() .getService_evaluate()); float store_ship_evaluate = CommUtil.null2Float(store.getPoint() .getShip_evaluate()); // 计算和同行比较结果 description_result = CommUtil.div(store_description_evaluate - description_evaluate, description_evaluate); service_result = CommUtil.div(store_service_evaluate - service_evaluate, service_evaluate); ship_result = CommUtil.div(store_ship_evaluate - ship_evaluate, ship_evaluate); } if (description_result > 0) { mv.addObject("description_css", "value_strong"); mv.addObject( "description_result", CommUtil.null2String(CommUtil.mul(description_result, 100) > 100 ? 100 : CommUtil.mul(description_result, 100)) + "%"); } if (description_result == 0) { mv.addObject("description_css", "value_normal"); mv.addObject("description_result", "-----"); } if (description_result < 0) { mv.addObject("description_css", "value_light"); mv.addObject( "description_result", CommUtil.null2String(CommUtil.mul(-description_result, 100)) + "%"); } if (service_result > 0) { mv.addObject("service_css", "value_strong"); mv.addObject("service_result", CommUtil.null2String(CommUtil.mul(service_result, 100)) + "%"); } if (service_result == 0) { mv.addObject("service_css", "value_normal"); mv.addObject("service_result", "-----"); } if (service_result < 0) { mv.addObject("service_css", "value_light"); mv.addObject("service_result", CommUtil.null2String(CommUtil.mul(-service_result, 100)) + "%"); } if (ship_result > 0) { mv.addObject("ship_css", "value_strong"); mv.addObject("ship_result", CommUtil.null2String(CommUtil.mul(ship_result, 100)) + "%"); } if (ship_result == 0) { mv.addObject("ship_css", "value_normal"); mv.addObject("ship_result", "-----"); } if (ship_result < 0) { mv.addObject("ship_css", "value_light"); mv.addObject("ship_result", CommUtil.null2String(CommUtil.mul(-ship_result, 100)) + "%"); } } private String secToTime(int time) { String timeStr = ""; int hour = 0; int minute = 0; int second = 0; if (time <= 0) return "00:00"; else { minute = time / 60; if (minute < 60) { second = time % 60; timeStr = unitFormat(minute) + ":" + unitFormat(second); } else { hour = minute / 60; if (hour > 99) return "99:59:59"; minute = minute % 60; second = time - hour * 3600 - minute * 60; timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second); } } return timeStr; } private String unitFormat(int i) { String retStr = ""; if (i >= 0 && i < 10) retStr = "0" + i; else retStr = "" + i; return retStr; } public String clickfrom_to_chinese(String key) { String str = "其它"; if (key.equals("search")) { str = "搜索"; } if (key.equals("floor")) { str = "首页楼层"; } if (key.equals("gcase")) { str = "橱窗"; } return str; } }
package com.mobiquityinc.packer; import com.mobiquityinc.exception.APIException; /** * Class to represent a Package Item. It holds the index, weight and cost of a single * package item. * @author Lucas Henrique Vicente <lucashv@gmail.com> */ public class PackageItem { private static final double MAX_ITEM_WEIGHT = 100.0; private static final double MAX_ITEM_COST = 100.0; private final int index; private final double weight; private final double cost; public PackageItem(int index, double weight, double cost) throws APIException { // Check if exceded that max item weight if (weight > MAX_ITEM_WEIGHT) throw new APIException("The Weight of the item can not pass " + MAX_ITEM_WEIGHT); // Check if exceded the max item cost if (cost > MAX_ITEM_COST) throw new APIException("The Cost of the item can not pass " + MAX_ITEM_COST); this.index = index; this.weight = weight; this.cost = cost; } public int getIndex() { return index; } public double getWeight() { return weight; } public double getCost() { return cost; } @Override public String toString() { return String.format("(%d, %.2f, %.2f)", this.index, this.weight, this.cost); } }
package com.ants.theantsgo.tools; /** * App中的一些常量 * * @author Txunda_HZj * <p> * 2017年4月8日下午1:43:27 */ public class ConstantUtils { /** * 微信支付App_id wxaed69e76fe603aa8 */ public static final String APP_ID = "wxaed69e76fe603aa8"; public static final String URL = "http://wxpay.weixin.qq.com/pub_v2/app/app_pay.php?plat=android"; public static final String WX_PAY_RECEIVER_ACTION = "wxPay"; /** * android pid */ public static final String PID = "mm_25125028_43298536_316522611"; // TODO========== 支付宝相关 ========== // TODO========== 支付宝相关 ========== // TODO========== 支付宝相关 ========== public static final String ALI_PID = ""; public static final String APPID = ""; public static final String RSA2_PRIVATE = ""; public static final String TARGET_ID = ""; }
package org.giddap.dreamfactory.leetcode.onlinejudge; /** * https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/ * <p/> * Evaluate the value of an arithmetic expression in Reverse Polish Notation. * <p/> * Valid operators are +, -, *, /. Each operand may be an integer or another * expression. * <pre> * Some examples: * ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 * ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 * </pre> */ public interface EvaluateReversePolishNotation { int evalRPN(String[] tokens); }
package co.sblock.users; import java.util.Collection; import java.util.HashMap; /** * Represents canon Classes, including those of mythological roles. * * @author FireNG, Jikoo */ public class UserClass { private static final HashMap<String, UserClass> REGISTRY = new HashMap<>(); static { REGISTRY.put("bard", new UserClass("Bard", 3)); REGISTRY.put("douche", new UserClass("Douche", 4)); REGISTRY.put("gent", new UserClass("Gent", 3)); REGISTRY.put("heir", new UserClass("Heir", 3)); REGISTRY.put("knight", new UserClass("Knight", 5)); REGISTRY.put("lord", new UserClass("Lord", 7)); REGISTRY.put("mage", new UserClass("Mage", 4)); REGISTRY.put("maid", new UserClass("Maid", 4)); REGISTRY.put("muse", new UserClass("Muse", 0)); REGISTRY.put("nerd", new UserClass("Nerd", 0)); REGISTRY.put("page", new UserClass("Page", 2)); REGISTRY.put("prince", new UserClass("Prince", 6)); REGISTRY.put("rogue", new UserClass("Rogue", 2)); REGISTRY.put("seer", new UserClass("Seer", 1)); REGISTRY.put("sylph", new UserClass("Sylph", 1)); REGISTRY.put("thief", new UserClass("Thief", 5)); REGISTRY.put("waste", new UserClass("Waste", 3)); REGISTRY.put("witch", new UserClass("Witch", 6)); } private final String name; private final int activity; private UserClass(String name, int activity) { this.name = name; this.activity = activity; } /** * Gets the display name of the UserClass. * * @return the display name of this UserClass */ public String getDisplayName() { return this.name; } /** * Gets the number of active abilities granted by this UserClass. * * @return the number of abilities */ public int getActiveSkills() { return activity; } /** * Gets the number of passive or reactive abilities granted by this UserClass. * * @return the number of abilities */ public int getPassiveSkills() { return 7 - activity; } @Override public String toString() { return this.name; } /** * Gets the UserClass. * * @param name the name of a UserClass * * @return the UserClass */ public static UserClass getClass(String name) { String lowName = name.toLowerCase(); if (REGISTRY.containsKey(lowName)) { return REGISTRY.get(lowName); } return new UserClass(name, 4); } /** * Get a Collection of all registered UserClasses. * * @return the UserClasses */ public static Collection<UserClass> values() { return REGISTRY.values(); } }
package rbtc.control; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import rbtc.dao.BukuDAO; import rbtc.dao.MahasiswaDAO; import rbtc.dao.PinjamDAO; import rbtc.model.Buku; import rbtc.model.Mahasiswa; import rbtc.model.Peminjaman; @Controller @RequestMapping("pinjam") @SessionAttributes("model") public class PinjamController { @Autowired PinjamDAO dao; @Autowired BukuDAO bukudao; @Autowired MahasiswaDAO mhsdao; @RequestMapping(value="prosesPinjam", method=RequestMethod.GET) public String prosesPinjam(@RequestParam("id") String isbn, @RequestParam("nrp") String nrp) { Peminjaman pinjam = new Peminjaman(); //ngatur bukunya Buku buku = bukudao.getBuku(isbn); buku.setStatus("Dipinjam"); bukudao.editStatus(buku); Mahasiswa mhs = mhsdao.getMhs(nrp); //ngatur pinjamnya DateFormat d = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.DAY_OF_YEAR, 7); pinjam.setJudulbuku(buku.getJudul()); pinjam.setIsbn(isbn); pinjam.setStatus_peminjaman("Menunggu"); pinjam.setTgl_pinjam(d.format(date)); pinjam.setTgl_kembali(d.format(c.getTime())); pinjam.setDenda(0); pinjam.setNrp(nrp); pinjam.setNamaMhs(mhs.getNama()); dao.savePinjam(pinjam); return "redirect:/mhs/home-mhs"; } }
package com.meizu.scriptkeeper.schedule; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.annotation.JSONField; import com.alibaba.fastjson.annotation.JSONType; import com.alibaba.fastjson.serializer.SerializerFeature; import java.util.ArrayList; import java.util.Calendar; import java.util.List; /** * Author: jinghao * Date: 2015-03-20 */ @SuppressWarnings("unused") @JSONType(orders = {"id", "deadline", "task", "target"}, asm = false) public class Schedule { private static Schedule schedule = null; @JSONField(name = "deadline") private String deadline = String.valueOf(Calendar.getInstance().getTimeInMillis()); @JSONField(name = "task") private List<Task> task = new ArrayList<Task>(); @JSONField(name = "target") private String target = ""; @JSONField(name = "id") private long id ; private Schedule(){} public static synchronized Schedule getInstance() { if (schedule == null) { schedule = new Schedule(); } return schedule; } public static synchronized Schedule newInstance(){ schedule = new Schedule(); return schedule; } public static synchronized Schedule loadSchedule(String jsonStr){ schedule = JSON.parseObject(jsonStr, Schedule.class); return schedule; } public String toString(){ return JSON.toJSONString(schedule); } public String toString(SerializerFeature serializerFeature){ return JSON.toJSONString(schedule, serializerFeature); } public long getId(){ return id; } public void setId(long id){ this.id = id; } public String getDeadline() { return deadline; } public void setDeadline(String deadline) { this.deadline = deadline; } public List<Task> getTask() { return task; } public void setTask(List<Task> task) { this.task = task; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public Task getTask(int id) { return getTask().get(id); } @JSONField(serialize = false) public String getTaskListString(){ String taskListString = ""; int size = getTask().size(); for(int i=0;i<size;i++){ taskListString += getTaskName(i) + (i==size-1? "" :","); } return taskListString; } @JSONField(serialize = false) public int getCounts() { return this.getTask().size(); } @JSONField(serialize = false) public List<Task> getUnfinishedTasks() { List<Task> unfinishedTasks = new ArrayList<Task>(); int count = getCounts(); for (int i = 0; i < count; i++) { if (!isTaskComplete(i)) { unfinishedTasks.add(getTask(i)); } } return unfinishedTasks; } @JSONField(serialize = false) public boolean isTaskComplete() { for (int i = 0; i < getCounts(); i++) { if (!isTaskComplete(i)) { return false; } } return true; } @JSONField(serialize = false) public boolean isTaskExist(long id){ for (int i = 0; i < getCounts(); i++) { if (id == getTaskId(i)) { return true; } } return false; } public void clearTask(){ this.getTask().clear(); } public void removeTask(int position){ this.getTask().remove(position); } public void removeTask(long taskId){ int size = this.getCounts(); for(int i=0;i<size;i++){ if(id == (this.getTaskId(i))){ this.getTask().remove(i); break; } } } public void addTask(Task task) { this.getTask().add(task); } public boolean isTaskComplete(int id) { return this.getTask(id).isComplete(); } public long getTaskId(int id) { return this.getTask(id).getId(); } public String getTaskType(int id) { return this.getTask(id).getType(); } public String getTaskName(int id) { return this.getTask(id).getName(); } public int getTaskTimes(int id) { return this.getTask(id).getTimes(); } public String getTaskDescription(int id) { return this.getTask(id).getDescription(); } public void setTaskComplete(int id, Boolean status) { this.getTask(id).setComplete(status); } }
package orm.integ.eao; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.jdbc.core.RowMapper; import orm.integ.dao.DataAccessObject; import orm.integ.dao.sql.PageRequest; import orm.integ.dao.sql.QueryRequest; import orm.integ.dao.sql.StatementAndValue; import orm.integ.dao.sql.TabQuery; import orm.integ.dao.sql.Where; import orm.integ.eao.cache.MemoryCache; import orm.integ.eao.cache.NoExistsCache; import orm.integ.eao.cache.QueryManager; import orm.integ.eao.model.Entity; import orm.integ.eao.model.EntityModel; import orm.integ.eao.model.EntityModelBuilder; import orm.integ.eao.model.FieldInfo; import orm.integ.eao.model.FieldMapping; import orm.integ.eao.model.ForeignUse; import orm.integ.eao.model.FromOrmHelper; import orm.integ.eao.model.TableModels; import orm.integ.eao.transaction.ChangeFactory; import orm.integ.eao.transaction.DataChange; import orm.integ.eao.transaction.DataChangeListener; import orm.integ.eao.transaction.TransactionManager; import orm.integ.utils.IntegError; import orm.integ.utils.MyLogger; import orm.integ.utils.PageData; import orm.integ.utils.Record; public class EntityAccessObject<T extends Entity> extends TableHandler<T> { public static int queryByIdsCount = 0; private EntityModel em; private final Class<T> entityClass; private final RowMapper rowMapper; private final EaoAdapter<T> adapter; private final MemoryCache<T> cache = new MemoryCache<>(); private final NoExistsCache notExistsCache = new NoExistsCache(); private final QueryManager<T> queryManager ; private final List<DataChangeListener> dataChangeListeners = new ArrayList<>(); private final DataAccessObject dao; @SuppressWarnings("unchecked") public EntityAccessObject(EaoAdapter<T> adapter) { this.adapter = adapter; this.dao = adapter.getDao(); Type t = adapter.getClass().getGenericSuperclass(); Type[] ts = ((ParameterizedType) t).getActualTypeArguments(); entityClass = (Class<T>)ts[0]; EntityModelBuilder emBuilder = new EntityModelBuilder(entityClass, dao); adapter.setEntityConfig(emBuilder); em = emBuilder.buildModel(); super.init(dao, em); queryManager = new QueryManager<T>(dao); dataChangeListeners.add(cache); dataChangeListeners.add(queryManager); dataChangeListeners.add(notExistsCache); Eaos.addEao(this); rowMapper = new TableRowMapper(); } public DataAccessObject getDAO() { return dao; } public EntityModel getEntityModel() { return em; } public QueryManager<T> getQueryManager() { return this.queryManager; } public DataChangeListener[] getDataChangeListeners() { return dataChangeListeners.toArray(new DataChangeListener[0]); } public EntityQuery newQuery() { return new EntityQuery(this); } public EntityQuery newQuery(PageRequest page, String order ) { return (EntityQuery) new EntityQuery(this) .setOrder(order) .setPageInfo(page); } public EntitySqlQuery newSqlQuery(StatementAndValue sql){ return new EntitySqlQuery(this, sql); } public EntitySqlQuery newSqlQuery(String sql, Object...values) { StatementAndValue stmt = new StatementAndValue(sql, values); return new EntitySqlQuery(this, stmt); } public T getById(Object id) { if (id==null) { return null; } T en = cache.get(id.toString()); if (en==null) { if (!notExistsCache.isNotExistId(id)) { en = load(id); if (en!=null) { putToCache(en); } else { notExistsCache.signNotExist(id); } } } return en; } @SuppressWarnings("unchecked") public T load(Object id) { T en = (T) dao.queryById(em.getFullTableName(), em.getKeyColumn(), id, rowMapper); return en; } @SuppressWarnings({ "rawtypes", "unchecked" }) public List<T> getByIds(Collection ids) { LinkedHashSet set = new LinkedHashSet(); T en; for (Object id: ids) { en = cache.get(id.toString()); if (en==null) { set.add(id); } } if (set.size()>0) { List<T> listNew = dao.queryByIds(em.getFullTableName(), em.getKeyColumn(), set.toArray(), rowMapper); queryByIdsCount++; for (T obj: listNew) { putToCache(obj); } } List<T> list = new ArrayList<>(); for (Object id: ids) { list.add(cache.get(id)); } return list; } protected void putToCache(T entity) { if (entity!=null) { cache.put(entity); fillSolidMappingFields(entity); adapter.fillExtendFields(entity); } } private void fillSolidMappingFields(T entity) { for (FieldInfo field: em.getFields()) { if (field.isMapping() && field.isNormal()) { this.getFieldValue(entity, field, true); } } } public List<T> getAll(int maxReturn) { TabQuery query = new TabQuery(); query.setMaxReturnRowNum(maxReturn); query.setPageInfo(1, maxReturn); return this.query(query); } public List<T> getAll() { return getAll(100000); } T queryFirst(QueryRequest req) { req.setPageInfo(1, 1); List<T> list = this.query(req); if (list!=null && list.size()>0) { return list.get(0); } return null; } public void insert(T entity) { String id = entity.getId(); if (id==null) { id = this.createNewIdNoRepeat(); entity.setId(id); } if (FromOrmHelper.isFromOrm(entity)) { throw new IntegError("record exists! can not insert again."); } entity.setCreateTime(new Date()); DataChange change = ChangeFactory.newInsert(entity); adapter.beforeChange(change); super.insert(entity); afterChange(change); putToCache(entity); adapter.afterChange(change); } protected String createNewIdNoRepeat() { String newId; int testCount = 0, count; do { newId = adapter.createNewId().toString(); count = queryCount(em.getKeyColumn()+"=?", newId); testCount++; } while (count>0 && testCount<10); if (testCount>=10) { throw new IntegError("产生主键值程序有错误,已连续产生了"+testCount+"个重复主键!"); } return newId; } int queryCount(String whereStmt, Object... values) { TabQuery tq = new TabQuery(em); tq.addWhereItem(whereStmt, values); return queryCount(tq); } int queryCount(QueryRequest query) { return queryManager.queryCount(query); } public void deleteById(Object id, boolean checkForeignUse) { T entity = this.getById(id); if (entity==null) { MyLogger.print("entity is null!"); return; } if (checkForeignUse) { testForienUseBeforeDelete(id); } DataChange change = ChangeFactory.newDelete(entity); adapter.beforeChange(change); dao.deleteById(em.getFullTableName(), em.getKeyColumn(), id); afterChange(change); adapter.afterChange(change); } public void deleteById(Object id) { deleteById(id, true); } @SuppressWarnings("rawtypes") public void testForienUseBeforeDelete(Object id) { List<FieldInfo> fkFields = TableModels.getForeignKeyFields(entityClass); for (FieldInfo fkField: fkFields) { if (fkField.columnExists()) { EntityAccessObject eao = Eaos.getEao(fkField.getOwnerClass()); int count = eao.queryCount(fkField.getColumnName()+"=?", id); if (count>0) { String tabName = eao.getEntityModel().getTableName(); throw new IntegError(tabName+"."+fkField.getColumnName()+"="+id+" 已有数据,不能删除"); } } } } @SuppressWarnings("rawtypes") public List<ForeignUse> scanForeignUse(Object id) { List<ForeignUse> uses = new ArrayList<>(); List<FieldInfo> fkFields = TableModels.getForeignKeyFields(entityClass); for (FieldInfo fkField: fkFields) { if (fkField.columnExists()) { EntityAccessObject eao = Eaos.getEao(fkField.getOwnerClass()); int count = eao.queryCount(fkField.getColumnName()+"=?", id); if (count>0) { uses.add(new ForeignUse(fkField, count)); } } } return uses; } @SuppressWarnings("rawtypes") public void printForeignUse(Object id) { List<FieldInfo> fkFields = TableModels.getForeignKeyFields(entityClass); List<ForeignUse> uses = scanForeignUse(id); int total = 0; for (ForeignUse fu: uses) { total+=fu.getRecordCount(); } String info = "实体类 "+entityClass.getSimpleName()+" 的主键 " + em.getTableName() + "."+em.getKeyColumn()+" 总共对应 "+fkFields.size()+" 外键字段," + "id值 "+id+" 在 "+uses.size()+" 个外键字段出现了 "+total+" 次:"; System.out.println("\n"+info); for (ForeignUse fu: uses) { FieldInfo fkField = fu.getForeignKeyField(); EntityAccessObject eao = Eaos.getEao(fkField.getOwnerClass()); String fieldName = eao.getEntityModel().getTableName()+"."+fkField.getColumnName(); info = fieldName + "=" + id + " -- " + fu.getRecordCount()+" record"; System.out.println(info); } System.out.println(); } public void update(T entity) { if (entity==null) { MyLogger.printError(new Throwable(), "entity is null!"); return; } if (!FromOrmHelper.isFromOrm(entity)) { throw new IntegError("entity is not created by integ, can not be update."); } T old = this.load(entity.getId()); if (old==null) { return; } DataChange change = ChangeFactory.newUpdate(old, entity); adapter.beforeChange(change); Map<String, Object> updateFields = super.calcUpdateFields(old, entity); if (updateFields.size()==0) { return ; } Where where = new Where(em.getKeyColumn()+"=?", entity.getId()); dao.update(em.getTableName(), updateFields, where); afterChange(change); adapter.fillExtendFields(entity); adapter.afterChange(change); } @SuppressWarnings("unchecked") List<T> query(QueryRequest req) { req.setTableInfo(em); if (req.getLast()<=QueryRequest.PAGE_QUERY_MAX_RETURN) { List<String> ids = queryManager.queryIdList(req); return this.getByIds(ids); } else { List<T> list = dao.query(req, rowMapper); if (list.size()<20000) { for (T en: list) { this.putToCache(en); } } return list; } } public List<T> queryByIds(List<String> ids) { List<T> list = new ArrayList<>(); T entity; for (String id: ids) { entity = this.getById(id); list.add(entity); } return list; } PageData pageQuery(QueryRequest req) { req.setTableInfo(em); List<String> ids = queryManager.queryIdList(req); int count = queryManager.queryCount(req); List<T> list = this.getByIds(ids); String[] fields = req.getViewFields(); if (fields==null || fields.length==0) { fields = em.getListFields(); } List<Record> viewList = this.toRecords(list, fields); return new PageData(viewList, count); } public Record toRecord(T entity, String[] viewFields) { if (entity==null) { return null; } Object value; Record record = new Record(); FieldInfo field; for (String fieldName:viewFields) { field = em.getField(fieldName); value = getFieldValue(entity, field, true); if (value!=null) { record.put(fieldName, value); } } return record; } public Record toDetailRecord(T entity) { return toRecord(entity, em.getDetailFields()); } public Record toListRecord(T entity) { return toRecord(entity, em.getListFields()); } Map<Class<? extends Entity>, Set<Object>> getForeignIds(Collection<T> list) { Map<Class<? extends Entity>, Set<Object>> foreignIds = new HashMap<>(); Set<Object> ids, idsAll = new HashSet<>(); for (FieldInfo fi: em.getFields()) { ids = getValueSet(list, fi.getName()); idsAll = foreignIds.get(fi.getMasterClass()); if (idsAll==null) { idsAll = new HashSet<>(); foreignIds.put(fi.getMasterClass(), idsAll); } idsAll.addAll(ids); } return foreignIds; } @SuppressWarnings("rawtypes") void batchLoadRelEntities(Collection<T> list, String[] fields) { EntityAccessObject relEao ; Set<Object> ids; Map<Class<? extends Entity>, Set<Object>> foreignIds = getForeignIds(list); for (Class clazz: foreignIds.keySet()) { relEao = Eaos.getEao(clazz); if (relEao!=null) { ids = foreignIds.get(clazz); relEao.getByIds(ids); } } } public List<Record> toRecords(Collection<T> list) { return toRecords(list, em.getListFields()); } public List<Record> toRecords(Collection<T> list, String[] fields) { List<Record> records = new ArrayList<>(); if (list==null || fields==null || fields.length==0) { return records; } batchLoadRelEntities(list, fields); Record record = new Record(); for (T entity: list) { record = toRecord(entity, fields); records.add(record); } return records; } Set<Object> getValueSet(Collection<T> list, String fieldName) { Set<Object> values = new LinkedHashSet<>(); Object value; for (T entity: list) { value = this.getFieldValue(entity, fieldName, false); if (value!=null) { values.add(value); } } return values; } @SuppressWarnings("unchecked") public <X> X getFieldValue(T entity, String fieldName) { FieldInfo field = em.getField(fieldName); return (X) getFieldValue(entity, field, false); } @SuppressWarnings("unchecked") public <X> X getFieldValue(T entity, String fieldName, boolean dynamicRefresh) { FieldInfo field = em.getField(fieldName); return (X) getFieldValue(entity, field, dynamicRefresh); } private Object getFieldValue(T entity, FieldInfo field, boolean dynamicRefresh) { if (entity==null||field==null) { return null; } Object value = null; if (field.isNormal()) { value = field.getValue(entity); } if (dynamicRefresh) { Object value2 = null; if (field.isMapping()) { value2 = getMappingFieldValue(entity, field); } if (value2!=null) { if (field.isNormal()) { field.setValue(entity, value2); } value = value2; } } return value; } @SuppressWarnings({ "rawtypes", "unchecked" }) private Object getMappingFieldValue(T entity, FieldInfo field) { FieldMapping mapping = field.getMapping(); FieldInfo fkField = em.getField(mapping.getForeignKeyField()); Object relKeyId = getFieldValue(entity, fkField.getName()); EntityAccessObject relEao = Eaos.getEao(fkField.getMasterClass()); if (relEao!=null) { Entity relEntity = relEao.getById(relKeyId); Object relValue = relEao.getFieldValue(relEntity, mapping.getMasterField()); return relValue; } else { System.out.println("关联EAO未建立"); return null; } } private void afterChange(DataChange change) { TransactionManager.afterChange(change, dataChangeListeners); } public void cleanCache() { if (cache.size()>0 || queryManager.size()>0) { System.out.println("clean "+em.getEntityClass().getSimpleName()+"'s cache"); this.queryManager.clear(); this.cache.clear(); } } }
package io.haitaoc.service.impl; import com.github.pagehelper.PageHelper; import io.haitaoc.mapper.UserMapper; import io.haitaoc.model.User; import io.haitaoc.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tk.mybatis.mapper.entity.Example; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User queryUserById(String userId) { return userMapper.selectByPrimaryKey(userId); } @Override public List<User> queryUserListPaged(User user, Integer page, Integer pageSize) { // 开始分页 PageHelper.startPage(page, pageSize); List<User> userList = userMapper.selectAll(); return userList; } }
package com.atguigu.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.atguigu.dao.UserDao; import com.atguigu.dao.UserDaoImpl; public class ValidUsernameServlet extends HttpServlet { private UserDao userDao; public ValidUsernameServlet() { userDao=new UserDaoImpl(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); response.setContentType("text/html;charset=utf-8"); try { boolean ifExist = userDao.validUsernameExist(username); if (!ifExist) { response.getWriter().print("用户名不存在,请检查后再填写!"); }else { response.getWriter().print(""); } } catch (Exception e) { e.printStackTrace(); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package GTEs; import java.io.File; import java.io.IOException; import java.net.DatagramSocket; import java.net.SocketException; /** * manages datagram sockets: aliveSignalEmitter and SchedulerListener * @author babz * */ public class EngineManager implements Runnable { private int tcp; private int udp; private String host; private int alivePeriod; private int minConsumption; private int maxConsumption; private DatagramSocket datagramSocket; private SchedulerListener scheduleListener; private AliveSignalEmitter emitter; private File taskDir; private int load; private ConnectionListener connectionListener; public EngineManager(int udpPort, int tcpPort, String schedulerHost, int alivePeriod, int minConsumption, int maxConsumption, File taskDir) throws SocketException { udp = udpPort; datagramSocket = new DatagramSocket(); tcp = tcpPort; host = schedulerHost; this.alivePeriod = alivePeriod; this.minConsumption = minConsumption; this.maxConsumption = maxConsumption; this.taskDir = taskDir; this.load = 0; } @Override public void run() { try { emitter = new AliveSignalEmitter(datagramSocket, udp, tcp, host, alivePeriod, minConsumption, maxConsumption); new Thread(emitter).start(); scheduleListener = new SchedulerListener(datagramSocket, emitter); new Thread(scheduleListener).start(); connectionListener = new ConnectionListener(tcp, taskDir, this); new Thread(connectionListener).start(); } catch (SocketException e) { } catch (IOException e) { } } public int getLoad() { return load; } public synchronized void addLoad(int loadToAdd) { load += loadToAdd; } public synchronized void removeLoad(int loadToRemove) { load -= loadToRemove; } public void terminate() { connectionListener.terminate(); scheduleListener.terminate(); emitter.terminate(); datagramSocket.close(); } }
package yedamOracle.com; import java.util.Scanner; public class Rec2 { public static void main(String[] args) { Scanner sr = new Scanner(System.in); double i = sr.nextDouble(); //입력 받을 변수(i)를 선언하고 //System.out.(tr.getArea(i)); 를 쓴다 Rec tr = new Rec(1,3); tr.getArea(); // void 값 찍어냄 System.out 생략 void에 system.out썻기때문에 System.out.println(tr.getArea(i)); // 입력받을 변수 작성 } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Enumeration; //import static java.lang.System.out; import java.util.EnumSet; /** * * @author rm */ public class MainClass { public static void main(String[] args) { //to showw all information insid the inemoretion for (Enumeration object : Enumeration.values()) { // System.out.printf("s%,s%,s%",object,object.getcountry(),object.getpopulation()); System.out.println(object + "\t" + object.getcountry() + "\t" + object.getpopulation()); } ///////////////////////////////////////////////// // to showw one information insid the inemoretion String s1, s2; s1 = Enumeration.Egypt.getcountry(); s2 = Enumeration.Egypt.getpopulation(); //System.out.printf("my country is: s% \t s\t%",s1,s2); System.out.println(s1 + "\t" + s2); /////////////////////////////////////////// //to some all information insid the inemoretion for (Enumeration objject : EnumSet.range(Enumeration.USA, Enumeration.esomal)) { System.out.println(objject + "\t" + objject.getcountry() + "\t" + objject.getpopulation()); } } }
package chartsGenerators; import hadoopManager.SingleUrlGenerator; import java.awt.BasicStroke; import java.awt.Color; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.logging.Logger; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartUtilities; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.Range; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import com.orsoncharts.util.Scale2D; /** * * @author Romano Simone - www.sromano.altervista.org * To generate complex charts the library 'charts4j' * has problem becouse max request that googleApi could * support is 2048 URL length. Then for multilines chart * This class uses JFreeChart(http://www.jfree.org/). */ public class JFreeChartGenerator{ private static String OUTPUT_FOLDER_NAME = "png_charts"; private static Logger log = Logger.getLogger("global"); public static int MINUTE = 5, SECOND = 6, HOUR = 7; /** * Creates a chart dataset. * @return chart dataset. */ private XYDataset createDataset(double[] data1, ArrayList<double[]> data2, int interval, int scaleIn, String data1Title, ArrayList<String> dstatFilePath) { XYSeriesCollection dataset = new XYSeriesCollection(); XYSeries firstChart = new XYSeries(data1Title); double distanceBetweenPoints = 0.0; if (scaleIn == MINUTE) distanceBetweenPoints = 100.0/60.0/(double)interval; if (scaleIn == SECOND) distanceBetweenPoints = 100.0/1.0/(double)interval; if (scaleIn == HOUR) distanceBetweenPoints = 100.0/3600.0/(double)interval; //creating dataset for first chart double actualPoint = 0.0; for (double y:data1){ firstChart.add(actualPoint, y); actualPoint += distanceBetweenPoints; } dataset.addSeries(firstChart); //creating dataset for others dataset actualPoint = 0.0; int i=0; for(double[] data:data2){ XYSeries tmp = new XYSeries(SingleUrlGenerator.getLineName(dstatFilePath.get(i))); i++; for(double y:data){ tmp.add(actualPoint, y); actualPoint += distanceBetweenPoints; } dataset.addSeries(tmp); actualPoint = 0.0; } return dataset; } /** * Create JFreeChart from input dataset * @param dataset * @return */ private JFreeChart createChart(XYDataset dataset, String title, int scaleIn, String yLabel, boolean isPercentage, boolean isDashedLine) { // create the chart... String xAxis = checkXAxis(scaleIn); final JFreeChart chart = ChartFactory.createXYLineChart( title, // chart title xAxis, // x axis label yLabel, // y axis label dataset, // data PlotOrientation.VERTICAL, true, // include legend true, // tooltips false // urls ); // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART... chart.setBackgroundPaint(Color.white); XYPlot plot = chart.getXYPlot(); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); if (isDashedLine){ XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); for (int i=0; i<dataset.getSeriesCount(); i++) renderer.setSeriesStroke( i, new BasicStroke( 1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] {5.0f, 3.0f}, 0.0f ) ); } NumberAxis range = (NumberAxis) plot.getRangeAxis(); range.setLowerBound(0); if (isPercentage) plot.getRangeAxis().setRange(new Range(0, 100), false, true); return chart; } private String checkXAxis(int scaleIn) { String xAxis = ""; if (scaleIn == MINUTE) xAxis = "Minutes"; if (scaleIn == SECOND) xAxis = "Seconds"; if (scaleIn == HOUR) xAxis = "Hours"; return xAxis; } private String createImg(JFreeChart chart, String outputPath, String fileName) { //createOutputDir File dir = new File(outputPath + File.separator + JFreeChartGenerator.OUTPUT_FOLDER_NAME); dir.mkdir(); String outputFilePath =outputPath + File.separator + OUTPUT_FOLDER_NAME + File.separator + fileName + ".png"; File fileImg = new File(outputFilePath); try { ChartUtilities.saveChartAsPNG(fileImg, chart, 600, 400); } catch (IOException e) { log.severe("Error creating JFreeChart img: " + e.getMessage()); e.printStackTrace(); } log.info("JFreeChart img created..."); return outputFilePath; } /** * This method make chart and returns its path. * @return */ public String getChart(double[] data1, int interval, int scaleIn, boolean isPercentage, ArrayList<double[]> data2, String title, String data1Title, String yLabel, boolean isGrayScale, boolean isDashedLine, String outputPath, String fileName, ArrayList<String> dstatFilePath){ XYDataset dataset = createDataset(data1, data2, interval, scaleIn, data1Title, dstatFilePath); JFreeChart chart = createChart(dataset, title, scaleIn, yLabel, isPercentage, isDashedLine); String outputFile = createImg(chart, outputPath, fileName); return outputFile; } }
/* * Estrazioni con controllo versione. */ package estrazioni; /** * * @author 3Ai */ public class Estrazioni { /** * @param args the command line arguments */ public static void main(String[] args) { int[] pippicalzelunghe = new int[10]; Vettore v = new Vettore(pippicalzelunghe); v.carica(); System.out.println(v); System.out.println("Il min e': " + v.getMin()); System.out.println("Il max e': " + v.getMax()); System.out.println("Il med e': " + v.getAverage()); System.out.println("La percentuale di PARI e': " + v.getCountPari()); v.bubbleSort(); System.out.println(v); } }
import java.util.HashMap; import java.util.Map; import java.util.Set; import javax.jws.HandlerChain; import javax.jws.WebMethod; import javax.jws.WebService; @WebService(endpointInterface="BookServiceInterface", targetNamespace="http://localhost:8888/ws/book", portName="BookPort", name="Book", serviceName="BookService") //@HandlerChain(file="handler-chain.xml") public class BookServiceMethods implements BookServiceInterface { @Override public Book getBookById(String id) { return Book.constructBook(Book.retrieveBookById(id)); } @Override public Book[] getBooksByTitle(String title) { return Book.constructBooks(Book.retrieveBooksByTitle(title.replace(" ", "+"))); } @Override public Book getRandomBookByCategories(String categories) { return Book.constructBook(Book.retrieveBookByCategories(categories.replace(" ", "+"))); } @Override public boolean buyBook(String bookId, int userBankId, int numOfBooks) { return Book.buyBook(bookId, userBankId, numOfBooks) == 0; } }
package com.kirer.voice.api; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by xinwb on 2016/12/15. */ public class ApiFactory { private final Gson mGsonDateFormat; public ApiFactory() { mGsonDateFormat = new GsonBuilder() .setDateFormat("yyyy-MM-dd hh:mm:ss") .create(); } private static class SingletonHolder { private static final ApiFactory INSTANCE = new ApiFactory(); } public static ApiFactory getInstance() { return SingletonHolder.INSTANCE; } /** * create a service * * @param serviceClass * @param <S> * @return */ public <S> S createService(Class<S> serviceClass) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://api.huiwutong.cn/api/") .client(getOkHttpClient()) .addConverterFactory(GsonConverterFactory.create(mGsonDateFormat)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); return retrofit.create(serviceClass); } private final static long DEFAULT_TIMEOUT = 3; private OkHttpClient getOkHttpClient() { //定制OkHttp OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); //设置超时时间 httpClientBuilder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); httpClientBuilder.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); httpClientBuilder.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS); httpClientBuilder.addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request() .newBuilder() .addHeader("Content-Type","application/json") .build(); return chain.proceed(request); } }); return httpClientBuilder.build(); } }
package com.team2915.POWER_UP.commands; import com.team2915.POWER_UP.Robot; import edu.wpi.first.wpilibj.command.Command; public class RunClimber extends Command { public RunClimber(){ requires(Robot.climber); } @Override protected void execute() { if (Robot.io.getXbox().getRawButton(1)){ Robot.climber.setMotor(-0.8); }else{ Robot.climber.setMotor(0); } } @Override protected boolean isFinished() { return false; } }
/* * UNIVERSIDAD ICESI * ALGORITMOS Y PROGRAMACION II * PROYECTO FINAL DEL CURSO * SANTIAGO RODAS Y JULIAN ANDRES RIVERA * GRUPO BANCARIO */ package application; import excepciones.InformacionExisteExcepcion; import excepciones.InformacionVacia; import excepciones.NoExisteInformacionExcepcion; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import modelo.Persona; public class ControladoraBeneficio { // --------------------------------------------------------------------------------------- private Persona persona; // --------------------------------------------------------------------------------------- public ControladoraBeneficio() { persona = new Persona(null, null, null, null, null); } // --------------------------------------------------------------------------------------- @FXML private TextField nombreBeneficio; @FXML private TextField idBeneficio; @FXML private TextField claveBeneficio; @FXML private TextField valorBeneficio; @FXML private Button agregarBoton; // --------------------------------------------------------------------------------------- @FXML private TextField buscarTexto; @FXML private Button buscarBoton; @FXML private Label nombrela; @FXML private Label clavela; @FXML private Label valorla; // --------------------------------------------------------------------------------------- @FXML private TextField eliminarTexto; @FXML private Button eliminarBoton; // --------------------------------------------------------------------------------------- @FXML private Button informeBoton; @FXML private Label numerola; @FXML private Label valorla1; @FXML private Label promediola; // --------------------------------------------------------------------------------------- @FXML public void agregar(ActionEvent event) { try { String nombre = nombreBeneficio.getText(); String id = idBeneficio.getText(); String clave = claveBeneficio.getText(); Integer valor = Integer.parseInt(valorBeneficio.getText()); if(nombre.isEmpty() == false && id.isEmpty() == false && clave.isEmpty() == false && valor != null) { persona.agregarBeneficioDescuento(nombre, id, clave, valor); Alert alert1277877 = new Alert(AlertType.INFORMATION); alert1277877.setTitle("Informacion importante"); alert1277877.setHeaderText(null); alert1277877.setContentText("Beneficio agregado correctamente"); alert1277877.showAndWait(); nombreBeneficio.setText(null); idBeneficio.setText(null); claveBeneficio.setText(null); valorBeneficio.setText(null); } else { throw new InformacionVacia("INFORMACION VACIA, POR FAVOR LLENE LOS CAMPOS"); } } catch(InformacionExisteExcepcion ejemplo) { Alert alert1399711 = new Alert(AlertType.ERROR); alert1399711.setTitle("Error"); alert1399711.setHeaderText("No se puede agregar el beneficio"); alert1399711.setContentText("Esta informacion ya existe en el sistema"); alert1399711.showAndWait(); nombreBeneficio.setText(null); idBeneficio.setText(null); claveBeneficio.setText(null); valorBeneficio.setText(null); } catch(InformacionVacia ejemplo1) { Alert alert1499411 = new Alert(AlertType.WARNING); alert1499411.setTitle("Atencion"); alert1499411.setHeaderText("No se puede agregar el beneficio"); alert1499411.setContentText("Digite la informacion correspondiente"); alert1499411.showAndWait(); } catch(NullPointerException a2) { Alert alert1599411 = new Alert(AlertType.WARNING); alert1599411.setTitle("Atencion"); alert1599411.setHeaderText("No se puede agregar el beneficio"); alert1599411.setContentText("Digite la informacion correspondiente"); alert1599411.showAndWait(); } catch(NumberFormatException a3) { Alert alert15994114 = new Alert(AlertType.WARNING); alert15994114.setTitle("Atencion"); alert15994114.setHeaderText("No se puede agregar el beneficio"); alert15994114.setContentText("Datos erroneos para el sistema"); alert15994114.showAndWait(); } } // --------------------------------------------------------------------------------------- @FXML public void buscar(ActionEvent event) { nombrela.setText("..."); clavela.setText("..."); valorla.setText("..."); try { String id = buscarTexto.getText(); if(id.isEmpty() == false) { if(persona.buscarBeneficio(id) == true) { nombrela.setText(persona.buscarBeneficioBeneficio(id).getNombre()); clavela.setText(persona.buscarBeneficioBeneficio(id).getContrasena()); valorla.setText(Integer.toString(persona.buscarBeneficioBeneficio(id).getValor())); buscarTexto.setText(null); } else { buscarTexto.setText(null); throw new NoExisteInformacionExcepcion("LA INFORMACION BUSCADA NO EXISTE EN EL PROGRAMA"); } } else { throw new InformacionVacia("INFORMACION VACIA, POR FAVOR LLENE LOS CAMPOS"); } } catch(NoExisteInformacionExcepcion a1) { Alert alert16441288 = new Alert(AlertType.ERROR); alert16441288.setTitle("Error"); alert16441288.setHeaderText("No se puede buscar el beneficio"); alert16441288.setContentText("Esta informacion no existe en el sistema"); alert16441288.showAndWait(); } catch(NullPointerException a2) { Alert alert17441288 = new Alert(AlertType.WARNING); alert17441288.setTitle("Atencion"); alert17441288.setHeaderText("No se puede buscar el beneficio"); alert17441288.setContentText("Digite la informacion correspondiente"); alert17441288.showAndWait(); } catch(InformacionVacia ejemplo1) { Alert alert18441277 = new Alert(AlertType.WARNING); alert18441277.setTitle("Atencion"); alert18441277.setHeaderText("No se puede buscar el beneficio"); alert18441277.setContentText("Digite la informacion correspondiente"); alert18441277.showAndWait(); } } // --------------------------------------------------------------------------------------- @FXML public void eliminar(ActionEvent event) { String id = eliminarTexto.getText(); try { if(id.isEmpty() == false) { persona.eliminarBeneficio(id); Alert alert19114444 = new Alert(AlertType.INFORMATION); alert19114444.setTitle("Informacion importante"); alert19114444.setHeaderText(null); alert19114444.setContentText("Beneficio eliminado correctamente"); alert19114444.showAndWait(); eliminarTexto.setText(null); } else { throw new InformacionVacia("INFORMACION VACIA, POR FAVOR LLENE LOS CAMPOS"); } } catch(NullPointerException e) { Alert alert2044779 = new Alert(AlertType.WARNING); alert2044779.setTitle("Atencion"); alert2044779.setHeaderText("No se puede eliminar el beneficio"); alert2044779.setContentText("Digite la informacion correspondiente"); alert2044779.showAndWait(); } catch(NoExisteInformacionExcepcion e1) { Alert alert2188113 = new Alert(AlertType.ERROR); alert2188113.setTitle("Error"); alert2188113.setHeaderText("No se puede eliminar el beneficio"); alert2188113.setContentText("Esta informacion no existe en el sistema"); alert2188113.showAndWait(); eliminarTexto.setText(null); } catch(InformacionVacia ejemplo1) { Alert alert2277664 = new Alert(AlertType.WARNING); alert2277664.setTitle("Atencion"); alert2277664.setHeaderText("No se puede eliminar el beneficio"); alert2277664.setContentText("Digite la informacion correspondiente"); alert2277664.showAndWait(); } } // --------------------------------------------------------------------------------------- @FXML public void informe(ActionEvent event) { try { numerola.setText(Integer.toString(persona.calcular())); valorla1.setText(Integer.toString(persona.total())); promediola.setText(Integer.toString(persona.promedio())); } catch(ArithmeticException ae) { Alert alert700 = new Alert(Alert.AlertType.ERROR); alert700.setHeaderText(null); alert700.setTitle("Error"); alert700.setContentText("No se puede realizar el informe, no hay datos"); alert700.showAndWait(); } } // --------------------------------------------------------------------------------------- }
/** * Kenny Akers * Mr. Paige * Homework #13 * 12/8/17 */ public class Homework_13 { public static void main(String[] args) { if (args.length <= 2) { // If not enough arguments were entered (either nothing for the tree or nothing to search for)... System.out.println("Not enough arguments. Please specify values for the tree followed by two values to find LCA of."); return; } String[] array = new String[args.length - 2]; for (int i = 0; i < array.length; i++) { // For the first n-2 arguments (the numbers in the tree)... array[i] = args[i].equals("-") ? null : args[i]; } Tree<String> tree = new Tree<String>(array); tree.getLCA(tree.root(), args[array.length], args[array.length + 1]); System.out.println("Number of Leaves: " + tree.numberLeaves(tree.root())); } }
package com.java.OOP; public class Manager extends Employee { public Manager(Long id, String firstName, String lastName) { super(id, firstName, lastName); // TODO Auto-generated constructor stub } public static void main(String[] args) { Manager manager = new Manager(120L, "Nick", "Falls"); System.out.println(manager); } } class Employee { Long id; String firstName; String lastName; public Employee(Long id, String firstName, String lastName) { super(); this.id = id; this.firstName = firstName; this.lastName = lastName; } @Override public String toString() { return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]"; } }
package Service_Layer; public class ComplaintController { public boolean add_complaint(String description){ // שליחת התראה למנהל המערכת return true; } }
package org.firstinspires.ftc.teamcode; public class HelloWorld { //This is so coooooooooooool! }
package de.cuuky.varo.gui.report; import org.bukkit.Material; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.ItemStack; import de.cuuky.varo.Main; import de.cuuky.varo.gui.SuperInventory; import de.cuuky.varo.gui.utils.PageAction; import de.cuuky.varo.item.ItemBuilder; import de.cuuky.varo.player.VaroPlayer; import de.cuuky.varo.report.Report; import de.cuuky.varo.version.types.Materials; public class ReportPickGUI extends SuperInventory { private Report report; private VaroPlayer varoPlayer; public ReportPickGUI(VaroPlayer opener, Report report) { super("§cReport " + report.getId(), opener.getPlayer(), 9, false); this.report = report; this.varoPlayer = opener; open(); } @Override public boolean onOpen() { linkItemTo(0, new ItemBuilder().displayname("§5Teleport").itemstack(new ItemStack(Material.ENDER_PEARL)).build(), new Runnable() { @Override public void run() { if(report.getReported().isOnline()) { varoPlayer.getPlayer().teleport(report.getReported().getPlayer()); varoPlayer.sendMessage(Main.getPrefix() + "§7Du wurdest zum reporteten Spieler teleportiert!"); return; } varoPlayer.sendMessage(Main.getPrefix() + "§7Der reportete Spieler ist nicht mehr online!"); } }); linkItemTo(8, new ItemBuilder().displayname("§cClose").itemstack(Materials.REDSTONE.parseItem()).build(), new Runnable() { @Override public void run() { varoPlayer.sendMessage(Main.getPrefix() + "§7Du hast den Report §c" + +report.getId() + " §7geschlossen"); report.close(); new ReportListGUI(varoPlayer.getPlayer()); } }); return true; } @Override public void onClose(InventoryCloseEvent event) {} @Override public void onClick(InventoryClickEvent event) {} @Override public void onInventoryAction(PageAction action) {} @Override public boolean onBackClick() { new ReportListGUI(varoPlayer.getPlayer()); return true; } }
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Date; import java.text.ParseException; import java.text.SimpleDateFormat; public class ExceptionTest { public static void main(String[] args) { // TODO Auto-generated method stub File f = new File("d:/test.exe"); try { System.out.println("try open d:/test.exe"); new FileInputStream(f); System.out.println("successful"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date d = sdf.parse("2016-06-03"); } // catch (FileNotFoundException e) { // System.out.println("file not exist"); // e.printStackTrace(); // } // catch (ParseException e) { // System.out.println("data format parse wrong"); // e.printStackTrace(); // } catch(FileNotFoundException | ParseException e) { if (e instanceof FileNotFoundException) System.out.println("file not exist"); if (e instanceof ParseException) System.out.println("date format parse wrong"); } finally { System.out.println("lastest run"); } } }
package com.example.diceouttesttutorial; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Random; public class MainActivity extends AppCompatActivity { TextView rollResult; TextView topRollText; TextView scoreText; int tries; int score; int topRoll; ArrayList<Integer> dice; ArrayList<ImageView> diceImages; Random rand; IRollingLogic rollingLogic; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { rollDice(view); } }); score = 0; topRoll = 0; tries = 0; rollResult = findViewById(R.id.rollResult); topRollText = findViewById(R.id.topRoll); scoreText = findViewById(R.id.scoreText); rand = new Random(); dice = new ArrayList<Integer>(); diceImages = new ArrayList<ImageView>(); diceImages.add((ImageView) findViewById(R.id.dice1Image)); diceImages.add((ImageView) findViewById(R.id.dice2Image)); diceImages.add((ImageView) findViewById(R.id.dice3Image)); rollingLogic = new RollingLogic(); } public void rollDice(View v){ dice.clear(); for (int i = 0 ; i < 3 ; i++){ int die = rand.nextInt(6) +1; dice.add(die); updateDieImage(i, die); } int rollScore= rollingLogic.getRollScore(dice); rollResult.setText("You scored " + rollScore); score += rollScore; scoreText.setText("Score: " + score); handleRollMessage(rollScore); } private void updateDieImage(int imageNumber, int die) { String imageId="die_" + die; int image = getResources().getIdentifier(imageId, "drawable", getPackageName()); diceImages.get(imageNumber).setImageResource(image); } private void handleRollMessage(int roll) { if(roll > topRoll){ String message = "New Top Roll!"; if(roll >= 100){ message += " and it's a Triple!"; } else if (roll > 18) { message += " and it's a Double!"; } Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); topRoll = roll; topRollText.setText("Top Roll: " + topRoll); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
/* * Copyright © 2018 www.noark.xyz All Rights Reserved. * * 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 ! * 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件: * * http://www.noark.xyz/LICENSE * * 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播; * 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本; * 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利; * 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明! */ package xyz.noark.core.lang; import java.util.ArrayList; import java.util.Collection; /** * StringList其实就是JDK的ArrayList&lt;String&gt; * <p> * 仅限于策划模板配置中使用,请忽略带到ORM的实体类中 * * @author 小流氓[176543888@qq.com] * @since 3.3.1 */ public class StringList extends ArrayList<String> { private static final long serialVersionUID = 1462861076140500174L; public StringList() { } public StringList(int initialCapacity) { super(initialCapacity); } public StringList(Collection<String> list) { super(list); } }
package com.youthlin.example.plugin.hello; import com.youthlin.example.plugin.IPlugin; import lombok.extern.slf4j.Slf4j; /** * @author youthlin.chen * @date 2020-04-15 19:10 */ @Slf4j public class HelloPlugin implements IPlugin<Object> { @Override public void onActive(Object context) { log.debug("onActive!! {} {}", context, this.getClass().getClassLoader()); } @Override public void onDisabled(Object context) { log.debug("onDisabled!! {}", context); } }
package com.aikiinc.coronavirus.data; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.aikiinc.coronavirus.exception.CoronaVirusException; import com.aikiinc.coronavirus.utility.CoronaVirusUtil; import java.net.URL; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class CoronaVirusRemoteData extends CoronaVirusCommon implements CornaVirusData { private Logger log = LoggerFactory.getLogger(CoronaVirusRemoteData.class); public final static String SOURCE_URL_PREFIX = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_daily_reports/"; private static String sourceUrlPrefix; private URL remoteUrl; private CoronaVirusRemoteData() { } private CoronaVirusRemoteData(String sourceUrlPrefix) throws CoronaVirusException { CoronaVirusRemoteData.sourceUrlPrefix = sourceUrlPrefix; log.debug(CoronaVirusRemoteData.sourceUrlPrefix); } /** * Create a CoronaVirusLocalData instance and process loading the data * * @return * @throws CoronaVirusException */ public static final CoronaVirusRemoteData getInstance() throws CoronaVirusException { CoronaVirusRemoteData CoronaVirusRemoteData = new CoronaVirusRemoteData(sourceUrlPrefix); return CoronaVirusRemoteData; } public void process() throws CoronaVirusException { setRemoteConnection(); setURL(); readData(); extractData(); CoronaVirusUtil.closeBuffer(); } void setURL() { super.coroSiteURL = remoteUrl; } void setRemoteConnection() throws CoronaVirusException { // String sdate = // LocalDate.now().format(DateTimeFormatter.ofPattern("MM-dd-yyyy")); /** * Get prior date */ String sdate = LocalDate.now().minusDays(1).format(DateTimeFormatter.ofPattern("MM-dd-yyyy")); log.debug("Load coronavirus data for date: " + sdate); String sourceUrl = SOURCE_URL_PREFIX + sdate + ".csv"; try { this.remoteUrl = new URL(sourceUrl); remoteUrl.getContent(); log.debug("\tLoading data from: " + remoteUrl); } catch (Exception e) { log.warn("\tCould not load data from: " + sourceUrl); log.warn("\tException: " + e.getMessage()); } } }
package com.arthur.leetcode; /** * @program: leetcode * @description: II. 平衡二叉树 * @title: JZoffer55_2 * @Author hengmingji * @Date: 2022/1/3 15:08 * @Version 1.0 */ public class JZoffer55_2 { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public boolean isBalanced(TreeNode root) { return dfs(root) != -1; } private int dfs(TreeNode root) { if (root == null) { return 0; } int left = dfs(root.left); if (left == -1) { return -1; } int right = dfs(root.right); if (right == -1) { return -1; } if (Math.abs(left - right) < 2) { return Math.max(left, right) + 1 ; } else { return -1; } } }
package codeu.controller; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.time.Instant; import java.util.List; import java.util.UUID; import codeu.model.data.User; import codeu.model.data.Post; import codeu.model.store.basic.UserStore; import codeu.model.store.basic.PostStore; import codeu.model.store.persistence.PersistentStorageAgent; import org.jsoup.Jsoup; import org.jsoup.safety.Whitelist; public class PostServlet extends HttpServlet{ private UserStore userStore; private PostStore postStore; @Override public void init() throws ServletException{ super.init(); setUserStore(UserStore.getInstance()); setPostStore(PostStore.getInstance()); } void setUserStore(UserStore userStore) { this.userStore = userStore; } void setPostStore(PostStore PostStore) { this.postStore = postStore; } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String userName = request.getParameter("user"); User currentUser = userStore.getUser(userName); UUID currentUserID = currentUser.getId(); request.getRequestDispatcher("/WEB-INF/view/profile.jsp").forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String userName = (String) request.getSession().getAttribute("user"); String postContent = request.getParameter("post"); String cleanedPostContent = Jsoup.clean(postContent, Whitelist.none()); Post post = new Post( UUID.randomUUID(), userStore.getUser(userName).getId(), Instant.now(), cleanedPostContent); PostStore.getInstance().addPost(post); // redirect to a GET request response.sendRedirect("/user/" + userName); } }
package com.atlassian.theplugin.idea.action.bamboo.onebuild; import com.intellij.openapi.actionSystem.AnActionEvent; /** * User: jgorycki * Date: Jan 7, 2009 * Time: 2:23:11 PM */ public class ViewBuildAction extends AbstractBuildDetailsAction { public void actionPerformed(AnActionEvent e) { openBuildInBrowser(e); } }
package Services.InfoService; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; @XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name ="RuleResponse", namespace="Rule") public class RuleResponse { private int id; private int ownerID; private String query; private int yesEdge; private int noEdge; private String relativeResults; public int getId() { return id; } public int getOwnerID() { return ownerID; } public String getQuery() { return query; } public int getYesEdge() { return yesEdge; } public int getNoEdge() { return noEdge; } public String getRelativeResults() { return relativeResults; } public void setId(int id) { this.id = id; } public void setOwnerID(int ownerID) { this.ownerID = ownerID; } public void setQuery(String query) { this.query = query; } public void setYesEdge(int yesEdge) { this.yesEdge = yesEdge; } public void setNoEdge(int noEdge) { this.noEdge = noEdge; } public void setRelativeResults(String relativeResults) { this.relativeResults = relativeResults; } @Override public String toString() { return id + ownerID + query + yesEdge + noEdge + relativeResults; } }
package com.example.bootcamp.serviceImpl; import java.util.Base64; import java.util.Optional; import javax.validation.Valid; import org.apache.commons.lang.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.bootcamp.commons.ResponseBody; import com.example.bootcamp.commons.ResponseMessage; import com.example.bootcamp.commons.ResponseStatus; import com.example.bootcamp.entity.UserPasswordToken; import com.example.bootcamp.entity.Users; import com.example.bootcamp.model.ResetPasswordModel; import com.example.bootcamp.repo.UserPasswordTokenRepo; import com.example.bootcamp.repo.UsersRepo; import com.example.bootcamp.service.UserPasswordTokenService; import com.example.bootcamp.utils.CommonUtils; import com.example.bootcamp.utils.Constant; import com.example.bootcamp.utils.EmailSender; import com.example.bootcamp.utils.JsonUtils; import com.example.bootcamp.utils.Timings; import com.google.gson.Gson; @Service public class userPasswordTokenServiceImpl implements UserPasswordTokenService{ @Autowired UserPasswordTokenRepo userPasswordTokenRepo; @Autowired UsersRepo usersRepo; @Override public String sendPasswordResetLink(@Valid String emailOrPhone) { Users userByEmail = usersRepo.findByEmailOrPhone(emailOrPhone); if(null != userByEmail) { if(null != userByEmail.getEmail()) { UserPasswordToken userPasswordToken = new UserPasswordToken(); userPasswordToken.setUserId(userByEmail.getUserId()); userPasswordToken.setIsActive(true); userPasswordToken.setCreation(Timings.currentTime()); userPasswordToken.setPasswordToken(RandomStringUtils.randomAlphanumeric(20)); userPasswordTokenRepo.save(userPasswordToken); String encodedToken = Base64.getEncoder().encodeToString(userPasswordToken.getPasswordToken().getBytes()); String encodedEmail = Base64.getEncoder().encodeToString(userByEmail.getEmail().getBytes()); String link = ""; if (Constant.LIVE_SERVER) link = Constant.FORGOT_PASSWORD_LINK_PRODUCTION + "?token="+encodedToken+"&email="+encodedEmail; else link = Constant.FORGOT_PASSWORD_LINK_DEVELOPMENT +"?token="+ encodedToken+"&email="+encodedEmail; String text = "Hi " + userByEmail.getFirstName() + "" + ",<br><br> Please find the Link below to reset password <br><br>" + link; EmailSender.sendEmail(userByEmail.getEmail(), "Set Password", "", text,Constant.BUSINESS_NAME); return JsonUtils.getResponseJson(ResponseStatus.SUCCESS, ResponseMessage.RESET_LINK_SUCCESS, link); }else { return JsonUtils.getResponseJson(ResponseStatus.NO_DATA_FOUND, ResponseMessage.EMAIL_NOT_FOUND, null); } }else { return JsonUtils.getResponseJson(ResponseStatus.NO_DATA_FOUND, ResponseMessage.EMAIL_OR_PHONE_NOT_FOUND, null); } } @Override public String verifyPasswordResetLink(String resetLink) { String[] splitByEquals = resetLink.split("=", 4); String encodedEmail = splitByEquals[3]; String encodedToken = splitByEquals[1]; byte[] decodedBytes_token = Base64.getDecoder().decode(encodedToken); String decodedToken = new String(decodedBytes_token); byte[] decodedBytes_email = Base64.getDecoder().decode(encodedEmail); String decodedEmail = new String(decodedBytes_email); Optional<UserPasswordToken> userPasswordToken = userPasswordTokenRepo.findByPasswordToken(decodedToken); if(!userPasswordToken.isPresent()) { return JsonUtils.getResponseJson(ResponseStatus.NO_DATA_FOUND, ResponseMessage.EMAIL_OR_RESET_LINK_INVALID, null); }else { if(!userPasswordToken.get().getIsActive()) { return JsonUtils.getResponseJson(ResponseStatus.FAILED, ResponseMessage.RESET_LINK_EXPIRED, null); }else { Optional<Users> user = usersRepo.findById(userPasswordToken.get().getUserId()); if(!user.isPresent()) { return JsonUtils.getResponseJson(ResponseStatus.FAILED, ResponseMessage.NO_DATA_FOUND, null); }else { if(!user.get().getEmail().equalsIgnoreCase(decodedEmail)) { return JsonUtils.getResponseJson(ResponseStatus.FAILED, ResponseMessage.EMAIL_OR_RESET_LINK_INVALID, null); }else { long expiryTime =userPasswordToken.get().getCreation() + 10 * 60 * 1000; if (expiryTime < Timings.currentTime()) { userPasswordToken.get().setIsActive(false); userPasswordTokenRepo.save(userPasswordToken.get()); return JsonUtils.getResponseJson(ResponseStatus.FAILED, ResponseMessage.EMAIL_OR_RESET_LINK_INVALID, null); } return JsonUtils.getResponseJson(ResponseStatus.SUCCESS, ResponseMessage.RESET_LINK_VERIFIED, encodedEmail); } } } } } @Override public String updatePassword(ResetPasswordModel resetPasswordModel,String resetLink) { String[] splitByEquals = resetLink.split("=", 4); String encodedToken = splitByEquals[1]; byte[] decodedBytes_token = Base64.getDecoder().decode(encodedToken); String decodedToken = new String(decodedBytes_token); byte[] decodedBytes_email = Base64.getDecoder().decode(resetPasswordModel.getEmail()); String decodedEmail = new String(decodedBytes_email); if(!resetPasswordModel.getConfirmPassword().equalsIgnoreCase(resetPasswordModel.getNewPassword())) return JsonUtils.getResponseJson(ResponseStatus.FAILED, ResponseMessage.MATCH_FAIL, null); Optional<Users> user = usersRepo.findByEmail(decodedEmail); if(!user.isPresent()) return JsonUtils.getResponseJson(ResponseStatus.FAILED, ResponseMessage.EMAIL_NOT_FOUND, null); if(CommonUtils.matchPassword(user.get().getPassword(),resetPasswordModel.getNewPassword())) return JsonUtils.getResponseJson(ResponseStatus.FAILED, ResponseMessage.OLD_PASSWORD_INCORRECT, null); String verifiedResponse = this.verifyPasswordResetLink(resetLink); Gson gson = new Gson(); ResponseBody resp = gson.fromJson(verifiedResponse.toString(), ResponseBody.class); if(resp.getStatus()!=101) return verifiedResponse; Optional<UserPasswordToken> userPasswordToken = userPasswordTokenRepo.findByPasswordToken(decodedToken); if(!userPasswordToken.isPresent()) return JsonUtils.getResponseJson(ResponseStatus.NO_DATA_FOUND, ResponseMessage.EMAIL_OR_RESET_LINK_INVALID, null); userPasswordToken.get().setIsActive(false); userPasswordTokenRepo.save(userPasswordToken.get()); user.get().setPassword(CommonUtils.hashPassword(resetPasswordModel.getNewPassword())); usersRepo.save(user.get()); return JsonUtils.getResponseJson(ResponseStatus.SUCCESS, ResponseMessage.RESET_PASSWORD_SUCCESS, null); } }
package ${package}.${MainClassNameLow}.resource.mapper; import ${package}.${MainClassNameLow}.resource.response.${MainClassName}Response; import ${package}.data.model.${MainClassName}; import com.prosegur.rest.mapper.configuration.DefaultRequestMapperConfig; import org.mapstruct.Mapper; @Mapper(componentModel = "spring", config = DefaultRequestMapperConfig.class) public interface ${MainClassName}Mapper { ${MainClassName}Response toResponse(${MainClassName} ${MainClassNameObj}); }
package com.asiainfo.worktime.entity; import java.io.Serializable; import javax.persistence.*; import java.util.List; /** * The persistent class for the TB_RPOC_TYPE database table. * */ @Entity @Table(name="TB_RPOC_TYPE") //@NamedQuery(name="TbRpocType.findAll", query="SELECT t FROM TbRpocType t") public class RpocTypeEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name="PROC_TYPE") private String procType; @Column(name="PROC_NAME") private String procName; //bi-directional many-to-one association to TbProc @OneToMany(mappedBy="tbRpocType") private List<ProcEntity> tbProcs; public RpocTypeEntity() { } public String getProcType() { return this.procType; } public void setProcType(String procType) { this.procType = procType; } public String getProcName() { return this.procName; } public void setProcName(String procName) { this.procName = procName; } public List<ProcEntity> getTbProcs() { return this.tbProcs; } public void setTbProcs(List<ProcEntity> tbProcs) { this.tbProcs = tbProcs; } public ProcEntity addTbProc(ProcEntity tbProc) { getTbProcs().add(tbProc); tbProc.setTbRpocType(this); return tbProc; } public ProcEntity removeTbProc(ProcEntity tbProc) { getTbProcs().remove(tbProc); tbProc.setTbRpocType(null); return tbProc; } }
package app.com.thetechnocafe.eventos.DataSync; import android.content.Context; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; /** * Created by gurleensethi on 15/10/16. * Singleton class to maintain a single request queue over the lifetime of the app */ public class VolleyQueue { private static VolleyQueue mInstance; private RequestQueue mRequestQueue; private static Context mContext; //Private constructor to make class singleton private VolleyQueue(Context context) { mContext = context; mRequestQueue = getRequestQueue(); } //Return instance of this class public static VolleyQueue getInstance(Context context) { //Check if function is called first time if (mInstance == null) { mInstance = new VolleyQueue(context); } return mInstance; } //Return the request queue public RequestQueue getRequestQueue() { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext()); } return mRequestQueue; } }
/* * Copyright 2002-2020 the original author or authors. * * 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 * * https://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.springframework.context.annotation; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.core.type.AnnotatedTypeMetadata; /** * A single {@code condition} that must be {@linkplain #matches matched} in order * for a component to be registered. * * <p>Conditions are checked immediately before the bean-definition is due to be * registered and are free to veto registration based on any criteria that can * be determined at that point. * * <p>Conditions must follow the same restrictions as {@link BeanFactoryPostProcessor} * and take care to never interact with bean instances. For more fine-grained control * of conditions that interact with {@code @Configuration} beans consider implementing * the {@link ConfigurationCondition} interface. * * @author Phillip Webb * @since 4.0 * @see ConfigurationCondition * @see Conditional * @see ConditionContext */ @FunctionalInterface public interface Condition { /** * Determine if the condition matches. * @param context the condition context * @param metadata the metadata of the {@link org.springframework.core.type.AnnotationMetadata class} * or {@link org.springframework.core.type.MethodMetadata method} being checked * @return {@code true} if the condition matches and the component can be registered, * or {@code false} to veto the annotated component's registration */ boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata); }
package com.udacity.jwdnd.course1.cloudstorage; import com.udacity.jwdnd.course1.cloudstorage.model.Note; import com.udacity.jwdnd.course1.cloudstorage.pages.HomePage; import com.udacity.jwdnd.course1.cloudstorage.pages.ResultPage; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class NoteTests extends CloudStorageApplicationTests { /** Test that creates a new note and verifies that it is displayed */ @Test public void testCreateAndDisplay(){ String noteTit = "Test Note"; String noteDesc = "This is a test note."; HomePage homePage = signUpAndLogin(); createNote(noteTit,noteDesc,homePage); homePage.navToNotesTab(); homePage = new HomePage(driver); Note note = homePage.getFirstNote(); Assertions.assertEquals(noteTit, note.getNoteTit()); // Test to validate displayed note title Assertions.assertEquals(noteDesc, note.getNoteDesc()); // Test to validate displayed note description deleteNote(homePage); homePage.logout(); } /** Test that deletes a note and verifies that it is not displayed */ @Test public void testDelete(){ String noteTitle = "Test Note"; String noteDescription = "This is a test note."; HomePage homePage = signUpAndLogin(); createNote(noteTitle,noteDescription,homePage); homePage.navToNotesTab(); homePage = new HomePage(driver); Assertions.assertFalse(homePage.noNotes(driver)); // Test to confirm note addition deleteNote(homePage); Assertions.assertTrue(homePage.noNotes(driver)); // Test to confirm note deletion } /** Test that modifies a note and verifies that the changes are displayed */ @Test public void testModify(){ String noteTitle = "Test Note"; String noteDescription = "This is a test note."; HomePage homePage = signUpAndLogin(); createNote(noteTitle,noteDescription,homePage); homePage.navToNotesTab(); homePage = new HomePage(driver); homePage.editNote(); String modNoteTitle = "Modified note"; String modNoteDescription = "This is a modified note."; homePage.modifyNoteTitle(modNoteTitle); homePage.modifyNoteDescription(modNoteDescription); homePage.saveNoteChanges(); ResultPage resultPage = new ResultPage(driver); resultPage.clickOk(); homePage.navToNotesTab(); Note note = homePage.getFirstNote(); Assertions.assertEquals(modNoteTitle, note.getNoteTit()); // Testing modified note title Assertions.assertEquals(modNoteDescription, note.getNoteDesc()); // Testing modified note description } private void createNote(String noteTit, String noteDesc, HomePage homePage){ homePage.navToNotesTab(); homePage.addNewNote(); homePage.setNoteTitle(noteTit); homePage.setNoteDescription(noteDesc); homePage.saveNoteChanges(); ResultPage resultPage = new ResultPage(driver); resultPage.clickOk(); homePage.navToNotesTab(); } private void deleteNote(HomePage homePage) { homePage.deleteNote(); ResultPage resultPage = new ResultPage(driver); resultPage.clickOk(); } }
public class arrayManipulation { static long arrayManipulation(int n, int[][] queries) { int[] values = new int[n+2]; int rows = queries.length; int i = 0; while (i < rows) { values[queries[i][0]] += queries[i][n - 1]; values[queries[i][1]+1] -= queries[i][n - 1]; i++; } int max = Integer.MIN_VALUE; for (i = 1; i <= n; i++) { values[i] += values[i - 1]; max = Math.max(values[i], max); } return max; } public static void main(String[] args) { int[][] q = {{1, 5, 3},{4, 8, 7},{6, 9, 1}}; System.out.println(arrayManipulation(3, q)); } }
package com.practice; import java.util.Scanner; public class Array_Q8 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //Reading n from user System.out.print("Enter the number of elements you want in the array: "); byte n = sc.nextByte(); //Creating array of size n int [] array = new int[n]; //Taking array elements System.out.println("Enter array elements: "); for(int i = 0 ; i < n ; i++){ array[i] = sc.nextInt(); } int flag = 0; for(int i=0;i<n-1;i++){ if(array[i]>=array[i+1]){ flag = 1; } } if(flag == 0) System.out.println("Array is Sorted :-)"); else System.out.println("Array is not Sorted :-("); } }
package ru.aggregator.object.request; import ru.aggregator.object.Page; /** * Created by user on 03.01.2015. */ public class SearchGeneRequest extends Page { private Long id; private String name; private String dsc; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDsc() { return dsc; } public void setDsc(String dsc) { this.dsc = dsc; } }
package com.youthlin.example.concurrent; import java.util.AbstractQueue; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Queue; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; /** * Copyright (C) Qunar.com - All Rights Reserved. * * @author Mingxin Wang * @date 2018-05-30 */ public class MutexQueue<T> extends AbstractQueue<T> implements Queue<T> { private static final AtomicReferenceFieldUpdater<Node, Node> QUEUE_TAIL_UPDATER = AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "next"); private static final AtomicReferenceFieldUpdater<Node, Node> QUEUE_HEAD_UPDATER = AtomicReferenceFieldUpdater.newUpdater(Node.class, Node.class, "prev"); private static final AtomicIntegerFieldUpdater<MutexQueue> COUNT_UPDATER = AtomicIntegerFieldUpdater.newUpdater(MutexQueue.class, "count"); private static final class Node<T> { private T data; volatile Node<T> prev; volatile Node<T> next; private Node(T data) { this.data = data; } } private volatile Node<T> head = new Node<>(null); private volatile Node<T> tail = head; private volatile int count = 0; @Override public boolean offer(T data) { Node<T> current = new Node<>(data); for (; ; ) { if (QUEUE_TAIL_UPDATER.weakCompareAndSet(tail, null, current)) { COUNT_UPDATER.incrementAndGet(this); current.prev = tail; tail = current; return true; } } } @Override public T poll() { for (; ; ) { Node<T> next = head.next; if (next == null) { return null; } if (QUEUE_HEAD_UPDATER.weakCompareAndSet(next, head, null)) { COUNT_UPDATER.decrementAndGet(MutexQueue.this); T data = next.data; next.data = null; head = next; return data; } } } @Override public T peek() { Node<T> next = head.next; if (next == null) { return null; } return next.data; } @Override public int size() { return count; } @Override public Iterator<T> iterator() { return new Iterator<T>() { Node<T> current = head; int expectModCount = count; @Override public boolean hasNext() { checkModCount(); return current.next != null; } @Override public T next() { checkModCount(); return (current = current.next).data; } @Override public void remove() { Node<T> prev = current.prev; Node<T> next = current.next; prev.next = next; if (next != null) { next.prev = prev; } current.data = null; expectModCount = COUNT_UPDATER.decrementAndGet(MutexQueue.this); } private void checkModCount() { if (expectModCount != count) { throw new ConcurrentModificationException(); } } }; } }
package utilities.readers; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ExcelReader { static String filePath = "0"; static XSSFWorkbook wb; public static void setPath(String filePath) throws IOException { File InputsFile = new File(filePath); FileInputStream fip = new FileInputStream(InputsFile); wb = new XSSFWorkbook(fip); //HSSFWorkbook for xls format, XSSFWorkbook for xlsx format } public static String read(int RowNumber, int ColumnNumber) throws IOException { String CellData = "2"; Sheet sheet = wb.getSheetAt(0); Row row = sheet.getRow(RowNumber); //Iterator<Row> rowIt = sheet.rowIterator(); //while(rowIt.hasNext()) //{ //row = rowIt.next(); Cell cell = row.getCell(ColumnNumber); //Iterator<Cell> cellIt = row.cellIterator(); if (CellData != null && cell != null) //for NullPoiterException CellData = cell.getStringCellValue().toString(); //while(cellIt.hasNext()) //{ //cell = cellIt.next(); //} //} return CellData; } public static void main( String[] args ) throws IOException { String filePath = System.getProperty("user.dir")+"/src/test/resources/"+"data.xlsx"; setPath(filePath); ExcelReader ExcelObj = new ExcelReader(); String CellDataValue = "1"; for (int i = 1; i< 2; i++) { for (int j = 0; j< 2; j++) { CellDataValue = ExcelObj.read(i, j); System.out.println(CellDataValue); } } } }
package br.edu.ifg.sistemacomercial.logic; import br.edu.ifg.sistemacomercial.dao.ClienteDAO; import br.edu.ifg.sistemacomercial.entity.Cliente; import java.util.List; import javax.inject.Inject; public class ClienteLogic implements GenericLogic<Cliente, Integer> { @Inject private ClienteDAO dao; @Override public Cliente salvar(Cliente entity) throws Exception { if("".equals(entity.getNome().trim())){ throw new Exception("Nome é obrigatório. Insira um valor válido!"); } if("".equals(entity.getCpf().trim())){ throw new Exception("CPF é obrigatório. Insira um valor válido!"); } if("".equals(entity.getRg().trim())){ throw new Exception("RG é obrigatório. Insira um valor válido!"); } if("".equals(entity.getTelefone1().trim())){ throw new Exception("Telefone é obrigatório. Insira um valor válido!"); } if("".equals(entity.getEmail().trim())){ throw new Exception("Email é obrigatório. Insira um valor válido!"); } if("".equals(entity.getObservacao().trim())){ throw new Exception("Observação é obrigatório. Insira um valor válido!"); } dao.salvar(entity); return null; } @Override public void deletar(Cliente entity) throws Exception { dao.deletar(entity); } @Override public Cliente buscarPorId(Integer id) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public List<Cliente> buscar(Cliente entity) throws Exception { return dao.listar(); } }
package com.enesmumu.nba.platform.player.pojo; /** * 球员 * @author 作者:BoXuelin * @date 创建时间:2017年10月18日 * @version 1.0 */ public class Player { private Long id; private String name;//姓名 private String season;//赛季 private Double height;//身高 private Double weight;//体重 private Integer attr;//属性 public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSeason() { return season; } public void setSeason(String season) { this.season = season; } public Double getHeight() { return height; } public void setHeight(Double height) { this.height = height; } public Double getWeight() { return weight; } public void setWeight(Double weight) { this.weight = weight; } public Integer getAttr() { return attr; } public void setAttr(Integer attr) { this.attr = attr; } }
package socialnetwork.domain; import socialnetwork.repository.Status; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Request extends Entity<Tuple<Long, Long>> { Utilizator from; Utilizator to; Status status; private String fromName; private String fromLastName; private LocalDateTime data; private String toName; private String toLastName; public Request(Utilizator from, Utilizator to, Status status) { this.from = from; this.to = to; this.status = status; this.fromName = from.getFirstName(); this.fromLastName = from.getLastName(); this.toName = to.getFirstName(); this.toLastName = to.getLastName(); this.data = LocalDateTime.now(); } public Request(Status status, String fromName, String fromLastName, LocalDateTime data) { this.status = status; this.fromName = fromName; this.fromLastName = fromLastName; this.data = data; } public void setData(LocalDateTime data) { this.data = data; } public String getFromName() { return fromName; } public String getFromLastName() { return fromLastName; } public String getData() { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); return data.format(formatter); } public Utilizator getFrom() { return from; } public Utilizator getTo() { return to; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getToName() { return toName; } public String getToLastName() { return toLastName; } @Override public String toString() { return "Request{" + "from=" + from + ", to=" + to + ", status=" + status + '}'; } public void setTo(Utilizator to) { this.to = to; } }
package java0722; public class BookDTO { private String bookname; // 책이름 private String author; // 작가 private int booknumber; // 책 넘버 private boolean loans = true; // 대출여부 private String loansname; // 대출받은 사람? public BookDTO() { } @Override public String toString() { return "BookDTO [bookname=" + bookname + ", author=" + author + ", booknumber=" + booknumber + ", loans=" + loans + ", loansname=" + loansname + "]"; } public String getBookname() { return bookname; } public void setBookname(String bookname) { this.bookname = bookname; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getBooknumber() { return booknumber; } public void setBooknumber(int booknumber) { this.booknumber = booknumber; } public boolean isLoans() { return loans; } public void setLoans(boolean loans) { this.loans = loans; } public String getLoansname() { return loansname; } public void setLoansname(String loansname) { this.loansname = loansname; } }
package com.company; import java.sql.SQLOutput; import java.util.Scanner; public class Main { public static void main(String[] args) { BankAccount Barry = new BankAccount(); // Initiates a new Scanner for inputting data Scanner scanner = new Scanner(System.in); // Entering the customers name System.out.println("Enter your Name: "); Barry.setCustomerName(scanner.next()); System.out.println("Your Customer Name is: " + Barry.getCustomerName()); // Entering the customers phone number System.out.println("Enter your phone number: "); Barry.setPhoneNumber(scanner.next()); System.out.println("Your phone number is: " + Barry.getPhoneNumber()); // Entering the customers email address System.out.println("Enter your email address: "); Barry.setEmailAddress(scanner.next()); System.out.println("Your email address is: " + Barry.getEmailAddress()); // Entering the customers account number System.out.println("Enter your account number: "); Barry.setAccountNum(scanner.next()); System.out.println("Your account number is: " + Barry.getAccountNum()); // Entering the customers initial balance System.out.println("Enter your initial account balance: "); Barry.setBalance(Integer.parseInt(scanner.next())); System.out.println("Your initial balance is: " + Barry.getBalance()); } }
package com.fwo.hp.fwo.app.provider; import com.fwo.hp.fwo.app.model.TranslateResponseModel; import com.fwo.hp.fwo.app.model.YahooResponseModel; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; /** * Created by ajnen on 12/10/2017. */ public interface Endpoint { String YAHOO_URL = "https://query.yahooapis.com"; String TRANSLATE_URL = "https://google-translate-proxy.herokuapp.com"; //https://github.com/guyrotem/google-translate-server @GET("v1/public/yql") Call<YahooResponseModel> loadWeather(@Query("q") String query, @Query("format") String format); @GET("api/translate") Call<TranslateResponseModel> translate(@Query("query") String query, @Query("targetLang") String targetLang, @Query("sourceLang") String sourceLang); }
package sch.frog.calculator.util; public class OutObject<V> { public V value; }
package view; import java.io.IOException; /** * Represents the view of a multi-layer image processing application that is able to send * messages given to it. */ public class SimpleMultiLayerImageProcessingView implements ImageProcessingView { private final Appendable ap; /** * Constructor that initializes the given appendable to the object. * @param ap the given appendable to write to */ public SimpleMultiLayerImageProcessingView(Appendable ap) { this.ap = ap; } @Override public void renderMessage(String message) throws IOException { ap.append(message); } }
/** * Sencha GXT 1.0.0-SNAPSHOT - Sencha for GWT * Copyright (c) 2006-2018, Sencha Inc. * * licensing@sencha.com * http://www.sencha.com/products/gxt/license/ * * ================================================================================ * Commercial License * ================================================================================ * This version of Sencha GXT is licensed commercially and is the appropriate * option for the vast majority of use cases. * * Please see the Sencha GXT Licensing page at: * http://www.sencha.com/products/gxt/license/ * * For clarification or additional options, please contact: * licensing@sencha.com * ================================================================================ * * * * * * * * * ================================================================================ * Disclaimer * ================================================================================ * THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND * REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE * IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY, * FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND * THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING. * ================================================================================ */ package com.sencha.gxt.explorer.client.extjs_data; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.dom.client.Element; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.Widget; import com.sencha.gxt.explorer.client.extjs.Ext; import com.sencha.gxt.explorer.client.model.Example.Detail; import jsinterop.annotations.JsFunction; import jsinterop.annotations.JsProperty; import jsinterop.annotations.JsType; @Detail( name = "Models", category = "ExtJS", icon = "basicbinding", classes = { Ext.class }, minHeight = ModelDefinitionExtJs.MIN_HEIGHT, minWidth = ModelDefinitionExtJs.MIN_WIDTH) public class ModelDefinitionExtJs implements EntryPoint, IsWidget { protected static final int MIN_HEIGHT = 480; protected static final int MIN_WIDTH = 640; /** * Define the Ext Config properties of the object */ @JsType public static class PersonConfig { @JsProperty public String name; @JsProperty int age = 1; @JsProperty public String gender; } /** * Define the Ext class Constructor */ @JsFunction public static interface Constructor { Object onConstructor(Object config); } /** * Define the Ext class */ @JsType public static class PersonDefine { @JsProperty public Object config; @JsProperty public Constructor constructor; } /** * Define the a Ext Class as a Model with data */ @JsType(isNative = true, namespace = "com.example") public static class Person { @JsProperty public String name; @JsProperty public int age; } @Override public void onModuleLoad() { RootPanel.get().add(asWidget()); } @Override public Widget asWidget() { FlowPanel fp = new FlowPanel(); defineUsingJsInterop(fp); fp.add(new HTML("<br/>")); defineUsingJSNI(fp); return fp; } public void defineUsingJsInterop(FlowPanel fp) { PersonConfig config = new PersonConfig(); PersonDefine personDefine = new PersonDefine(); personDefine.config = config; // Define the model // Verify it exists in: // Browser Dev Tools: > Ext.data.schema.Schema.instances.default.entities Ext.define("com.example.Person", personDefine); // Instantiate the model Person person = new Person(); person.name = "Jacky"; person.age = 35; HTML htmlJsInterop = new HTML("JsInterop: name=" + person.name + " age=" + person.age); fp.add(htmlJsInterop); } private void defineUsingJSNI(FlowPanel fp) { HTML htmlJSNI = new HTML(); fp.add(htmlJSNI); defineUsingJsni(htmlJSNI.getElement()); } /** * JSNI Example */ public native void defineUsingJsni(Element htmlElement) /*-{ var person = new $wnd.com.example.Person(); person.name = "Angie"; person.age = 25; var s = "JSNI: name=" + person.name + " age=" + person.age; htmlElement.innerHTML = s; }-*/; }
package com.ytdsuda.management.service; import com.ytdsuda.management.entity.Authority; import java.util.List; public interface RoleAuthorityService { List<Authority> findRoleAuth(Integer roleId); Integer changeRoleAuth(Integer roleId, List<Integer> authIds); }
package com.dq.police.controller.actions.Task; import com.dq.police.controller.Action; import com.dq.police.helpers.ConstraintsUtil; import com.dq.police.model.PersistenceManager; import com.dq.police.model.entities.Related; import com.dq.police.model.entities.Task; import com.dq.police.view.View; import lombok.AllArgsConstructor; @AllArgsConstructor public class AddTaskAction extends Action { private PersistenceManager persistence; private View view; @Override public String execute() { Task task = new Task(); task.setName(view.getPropertyCancellable("name")); task.setDesc(view.getPropertyCancellable("desc")); task.setType(view.getPropertyCancellable("type")); task.setCop(view.getPropertyCancellable("cop")); task.setStatus("NOT STARTED"); persistence.create(task); return ConstraintsUtil.OPERATION_SUCCESS_MESSAGE; } @Override public String getName() { return "Add Task"; } }
package com.its.controllers; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.its.dto.DepartDto; import com.its.dto.RolDto; import com.its.dto.UserDto; import com.its.entities.Depart; import com.its.entities.Rol; import com.its.entities.User; import com.its.service.DepartService; import com.its.service.RolService; import com.its.service.UserService; @Controller @RequestMapping(value="hibernate") public class ContactosController { @Autowired private RolService rolService; @Autowired private DepartService departService; @Autowired private UserService userService; @RequestMapping(value="/contactos") public ModelAndView contactos() { ModelAndView model = new ModelAndView("contactos"); return model; } @RequestMapping(value="/listRol", method=RequestMethod.POST) public @ResponseBody Map<String,Object> getAllRol(Rol roles){ Map<String,Object> map = new HashMap<String,Object>(); List<RolDto> list = rolService.list(); if (list != null){ map.put("status","200"); map.put("message","Data found"); map.put("data", list); }else{ map.put("status","404"); map.put("message","Data not found "); } return map; } @RequestMapping(value="/listDept", method=RequestMethod.POST) public @ResponseBody Map<String,Object> getAllDept(Depart departs){ Map<String,Object> map = new HashMap<String,Object>(); List<DepartDto> list = departService.list(); if (list != null){ map.put("status","200"); map.put("message","Data found"); map.put("data", list); }else{ map.put("status","404"); map.put("message","Data not found"); } return map; } @RequestMapping(value="/listUser", method=RequestMethod.POST) public @ResponseBody Map<String,Object> getAllUsers(User users){ Map<String,Object> map = new HashMap<String,Object>(); List<UserDto> list = userService.list(); if (list != null){ map.put("status","200"); map.put("message","Data found"); map.put("data", list); }else{ map.put("status","404"); map.put("message","Data not found"); } return map; } }
package com.atlantiscoding; import java.util.Comparator; public class SuitAndRankSorter implements Comparator<Card> { public int compare(Card c1, Card c2) { return c1.getSuit() - c2.getSuit(); } }
package com.example.graci.myapplication; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class Levels extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyCanvas canvas = new MyCanvas(this); canvas.setBackgroundColor(Color.BLACK); setContentView(canvas); } }
import java.util.*; class sum_of_number { int sum=0; int add(int n) { sum=n%10; if(n==0) return 0; else return (sum+add(n/10)); } public static void main(String args[]) { int n; Scanner sc=new Scanner(System.in); System.out.println("Enter the no."); n=sc.nextInt(); sum_of_number obj=new sum_of_number(); int a =obj.add(n); System.out.println("SUM "+a); } }
package in.jaaga.thebachaoproject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import org.json.JSONException; import org.json.JSONObject; public class ReviewFragment extends Fragment { private OnFragmentInteractionListener mListener; JSONObject data; /*starts the new instance of this fragment. */ public static ReviewFragment newInstance(String data) { ReviewFragment fragment = new ReviewFragment(); Bundle args = new Bundle(); args.putString("data", data); return fragment; } public ReviewFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(getArguments()!=null){ try { data = new JSONObject(getArguments().getString("data")); } catch (JSONException e) { e.printStackTrace(); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View v=inflater.inflate(R.layout.fragment_review, container, false); TextView avg_rating = (TextView) v.findViewById(R.id.txt_avg_rating); Button write_review = (Button) v.findViewById(R.id.btn_write_review_fragment); avg_rating.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(getActivity(),DetailedReviewActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); write_review.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mListener.writeReview(); } }); if(data!=null){ try { ((TextView) v.findViewById(R.id.txt_avg_rating)).setText(data.getString("a")); ((TextView) v.findViewById(R.id.txt_location_review_frag)).setText(data.getString("a")); ((ProgressBar) v.findViewById(R.id.progressBar_five_stars)).setProgress(data.getInt("a")); ((ProgressBar) v.findViewById(R.id.progressBar_four_stars)).setProgress(data.getInt("a")); ((ProgressBar) v.findViewById(R.id.progressBar_three_stars)).setProgress(data.getInt("a")); ((ProgressBar) v.findViewById(R.id.progressBar_two_stars)).setProgress(data.getInt("a")); } catch (JSONException e) { e.printStackTrace(); } } return v; } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnFragmentInteractionListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. */ public interface OnFragmentInteractionListener { void writeReview(); } }
package com.test.base; import com.test.SolutionA; import junit.framework.TestCase; public class Example extends TestCase { private Solution solution; @Override protected void setUp() throws Exception { super.setUp(); } public void testSolutionA() { solution = new SolutionA(); assertSolution(); } private void assertSolution() { TreeLinkNode a1 = new TreeLinkNode(1); a1.left = new TreeLinkNode(2); a1.right = new TreeLinkNode(3); solution.connect(a1); assertEquals("1,#,2,3,#,", log(a1)); } private String log(TreeLinkNode root) { StringBuilder sBuilder = new StringBuilder(); TreeLinkNode node; while (null != root) { node = root; while (null != node) { sBuilder.append(node.val + ","); node = node.next; } sBuilder.append("#,"); root = root.left; } String result = sBuilder.toString(); System.out.println(result); return result; } @Override protected void tearDown() throws Exception { solution = null; super.tearDown(); } }
package com.web.common; public class StateDTO { protected String UserID; protected int InbundCnt; //수신건수 protected int OutboundCnt; //발신건수 protected int AssignmentCnt; //수신배정건수 protected int NonImageOpenCnt; //수신미확인건수 protected int NonCompleteCnt; //수신 미처리건수 protected String UpGroupName; //상위그룹 protected String GroupName; //소속팀 protected String DIDNo; //팩스번호 protected String OfficeTellNo; //개인전화 protected String AcceptAssignment; //배정여부 protected String DIDNoFromat; //팩스번호포멧 protected String SearchDateSrc; protected String SearchDateDest; public void SetSearchDateDest( String DateDest ) { SearchDateDest = DateDest; } public void SetSearchDateSrc( String DateSrc ) { SearchDateSrc = DateSrc; } public String GetSearchDateSrc() { return SearchDateSrc; } public String GetSearchDateDest() { return SearchDateDest; } public String getDIDNoFromat() { return DIDNoFromat; } public void setDIDNoFromat(String dIDNoFromat) { DIDNoFromat = dIDNoFromat; } public String getUpGroupName() { return UpGroupName; } public void setUpGroupName(String upGroupName) { UpGroupName = upGroupName; } public String getGroupName() { return GroupName; } public void setGroupName(String groupName) { GroupName = groupName; } public String getDIDNo() { return DIDNo; } public void setDIDNo(String dIDNo) { DIDNo = dIDNo; } public String getOfficeTellNo() { return OfficeTellNo; } public void setOfficeTellNo(String officeTellNo) { OfficeTellNo = officeTellNo; } public String getAcceptAssignment() { return AcceptAssignment; } public void setAcceptAssignment(String acceptAssignment) { AcceptAssignment = acceptAssignment; } protected String logid; public String getLogid() { return logid; } public void setLogid(String logid) { this.logid = logid; } public String getUserID() { return UserID; } public void setUserID(String userID) { UserID = userID; } public int getInbundCnt() { return InbundCnt; } public void setInbundCnt(int inbundCnt) { InbundCnt = inbundCnt; } public int getOutboundCnt() { return OutboundCnt; } public void setOutboundCnt(int outboundCnt) { OutboundCnt = outboundCnt; } public int getAssignmentCnt() { return AssignmentCnt; } public void setAssignmentCnt(int assignmentCnt) { AssignmentCnt = assignmentCnt; } public int getNonImageOpenCnt() { return NonImageOpenCnt; } public void setNonImageOpenCnt(int nonImageOpenCnt) { NonImageOpenCnt = nonImageOpenCnt; } public int getNonCompleteCnt() { return NonCompleteCnt; } public void setNonCompleteCnt(int nonCompleteCnt) { NonCompleteCnt = nonCompleteCnt; } }
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; class Tetramino implements Minos { public final int X; public final int Y; public final char TYPE; private final Mino[] minos; public static final char[] TYPES = {'I', 'J', 'L', 'O', 'S', 'T', 'Z'}; public Tetramino (int x, int y) { int r = new Random().nextInt(7); this.X = x; this.Y = y; this.TYPE = TYPES[r]; this.minos = shape(TYPE); } public Tetramino (int x, int y, char type) { this.X = x; this.Y = y; this.TYPE = type; this.minos = shape(TYPE); } public Tetramino (Mino[] minos, char type, int x, int y) { this.X = x; this.Y = y; this.TYPE = type; this.minos = minos; } public Tetramino (Tetramino old, Mino[] newMinos) { this.X = old.X; this.Y = old.Y; this.TYPE = old.TYPE; this.minos = newMinos; } public Tetramino rotate() { if (this.TYPE == 'O') { return this; } Mino[] newMinos = new Mino[4]; for (int i = 0; i < 4; i++) { Mino mino = minos[i]; int x = mino.X; int y = mino.Y; Mino newMino; if (this.TYPE == 'I') { newMino = new Mino(1-y, x, this.TYPE); } else { newMino = new Mino(-y, x, this.TYPE); } newMinos[i] = newMino; } return new Tetramino(this, newMinos); } public Tetramino moveDown() { return new Tetramino(minos, TYPE, X, Y+1); } @Override public Mino[] getMinos() { Mino[] relativeMinos = minos; Mino[] positionedMinos = new Mino[4]; for (int i = 0; i < 4; i++) { int posX = relativeMinos[i].X + X; int posY = relativeMinos[i].Y + Y; Mino absoluteMino = new Mino(posX, posY, TYPE); positionedMinos[i] = absoluteMino; } return positionedMinos; } private static Mino[] shape (char type) { Mino[] minos; switch (type) { case 'I': minos = new Mino[] { new Mino(-1, 0, type), new Mino( 0, 0, type), new Mino( 1, 0, type), new Mino( 2, 0, type) }; break; case 'J': minos = new Mino[] { new Mino(-1, -1, type), new Mino(-1, 0, type), new Mino( 0, 0, type), new Mino( 1, 0, type) }; break; case 'L': minos = new Mino[] { new Mino( 1, -1, type), new Mino(-1, 0, type), new Mino( 0, 0, type), new Mino( 1, 0, type) }; break; case 'O': minos = new Mino[] { new Mino( 0, -1, type), new Mino( 1, -1, type), new Mino( 0, 0, type), new Mino( 1, 0, type) }; break; case 'S': minos = new Mino[] { new Mino( 1, -1, type), new Mino( 0, -1, type), new Mino( 0, 0, type), new Mino(-1, 0, type) }; break; case 'Z': minos = new Mino[] { new Mino(-1, -1, type), new Mino( 0, -1, type), new Mino( 0, 0, type), new Mino( 1, 0, type) }; break; default: case 'T': minos = new Mino[] { new Mino( 0, -1, type), new Mino(-1, 0, type), new Mino( 0, 0, type), new Mino( 1, 0, type) }; break; } return minos; } }
package com.zjf.myself.codebase.activity.UILibrary; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.TextView; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.BaseAct; import com.zjf.myself.codebase.thirdparty.TransitionAnim.EasyTransition; import com.zjf.myself.codebase.thirdparty.TransitionAnim.EasyTransitionOptions; import java.util.ArrayList; /** * <pre> * author : ZouJianFeng * e-mail : 1434690833@qq.com * time : 2017/05/26 * desc : * version: 1.0 * </pre> */ public class TransitionAnimAct extends BaseAct{ private ArrayList<String> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.act_transition_anim); list = new ArrayList<>(); for (int i = 0; i < 20; i++) { list.add("name" + i); } ListView listView = (ListView) findViewById(R.id.lv); listView.setAdapter(new MyAdapter()); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // ready for intent Intent intent = new Intent(TransitionAnimAct.this, DetailActivity.class); intent.putExtra("name", list.get(position)); // ready for transition options EasyTransitionOptions options = EasyTransitionOptions.makeTransitionOptions( TransitionAnimAct.this, view.findViewById(R.id.iv_icon), view.findViewById(R.id.tv_name), findViewById(R.id.v_top_card)); // start transition EasyTransition.startActivity(intent, options); } }); } private class MyAdapter extends BaseAdapter { @Override public int getCount() { int count = 0; if (null != list) count = list.size(); return count; } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = null; if (null != convertView) { view = convertView; } else { view = LayoutInflater.from(TransitionAnimAct.this).inflate(R.layout.item_main_list, null, false); } TextView tvName = (TextView) view.findViewById(R.id.tv_name); tvName.setText(list.get(position)); return view; } } }
/*hard A group of two or more people wants to meet and minimize the total travel distance. You are given a 2D grid of values 0 or 1, where each 1 marks the home of someone in the group. The distance is calculated usingManhattan Distance, where distance(p1, p2) = |p2.x - p1.x| + |p2.y - p1.y|. For example, given three people living at (0,0), (0,4), and(2,2): 1 - 0 - 0 - 0 - 1 | | | | | 0 - 0 - 0 - 0 - 0 | | | | | 0 - 0 - 1 - 0 - 0 The point (0,2) is an ideal meeting point, as the total travel distance of 2+2+2=6 is minimal. So return 6. */ //Time O(MN) Space O(N) class Solution { public int minTotalDistance(int[][] grid){ List<Integer> rows = fillRows(grid); List<Integer> cols = fillCols(grid); int row = rows.get(rows.size()/2); int col = cols.get(cols.size()/2); return getDistance(row, rows) + getDistance(col, cols); } public List<Integer> fillRows(int[][] grid){ List<Integer> rows = new ArrayList<>(); for(int i = 0; i < grid.length; i++){ for(int j = 0; j < grid[0].length; j++){ if(grid[i][j] == 1) rows.add(i); } } return rows; } public List<Integer> fillCols(int[][] grid){ List<Integer> cols = new ArrayList<>(); for(int i = 0; i < grid[0].length; i++){ for(int j = 0; j < grid.length; j++){ if(grid[j][i] == 1) cols.add(i); } } return cols; } public int getDistance(int row, List<Integer> rows){ int res = 0; for(int n : rows){ res += Math.abs(n - row); } return res; } }
/** * 锁对象的改变 */ /** * @author Administrator * */ package mulitThread.chapter02.t2_2_16;
package dk.webbies.tscreate.analysis; import com.google.common.collect.Iterables; import dk.au.cs.casa.typescript.types.*; import dk.webbies.tscreate.analysis.unionFind.*; import dk.webbies.tscreate.declarationReader.DeclarationParser.NativeClassesMap; import dk.webbies.tscreate.util.Pair; import dk.webbies.tscreate.util.Util; import java.util.*; import java.util.stream.Collectors; /** * Created by Erik Krogh Kristensen on 18-09-2015. */ public class NativeTypeFactory { private final NativeClassesMap nativeClasses; private final Map<Signature, FunctionNode> signatureCache = new HashMap<>(); // Used to get around recursive types. private final PrimitiveNode.Factory primitiveFactory; private final UnionFindSolver solver; public NativeTypeFactory(PrimitiveNode.Factory primitiveFactory, UnionFindSolver solver, NativeClassesMap nativeClasses) { this.primitiveFactory = primitiveFactory; this.solver = solver; this.nativeClasses = nativeClasses; } public FunctionNode fromSignature(Signature signature) { if (signatureCache.containsKey(signature)) { return signatureCache.get(signature); } List<String> argumentNames = signature.getParameters().stream().map(Signature.Parameter::getName).collect(Collectors.toList()); FunctionNode functionNode = FunctionNode.create(argumentNames, solver); signatureCache.put(signature, functionNode); int normalParameterCount = signature.getParameters().size(); if (signature.isHasRestParameter()) { normalParameterCount--; Type restType = Iterables.getLast(signature.getParameters()).getType(); List<Type> typeArguments; if (restType instanceof ReferenceType) { ReferenceType ref = (ReferenceType) restType; typeArguments = ref.getTypeArguments(); } else if (restType instanceof GenericType) { GenericType generic = (GenericType) restType; typeArguments = generic.getTypeArguments(); } else { throw new RuntimeException(); } if (typeArguments.size() != 1) { throw new RuntimeException(); } } for (int i = 0; i < normalParameterCount; i++) { Type parameter = signature.getParameters().get(i).getType(); UnionNode argument = functionNode.arguments.get(i); solver.union(argument, fromType(parameter, true)); } solver.union(functionNode.returnNode, fromType(signature.getResolvedReturnType(), false)); functionNode.arguments.forEach(arg -> solver.union(arg, primitiveFactory.nonVoid())); return functionNode; } private Map<Type, UnionNode> typeCache = new HashMap<>(); private UnionNode fromType(Type type, boolean isArgument) { if (isArgument && type instanceof SimpleType && ((SimpleType) type).getKind() == SimpleTypeKind.Any) { return primitiveFactory.nonVoid(); } if (typeCache.containsKey(type)) { return new IncludeNode(solver, typeCache.get(type)); } else { EmptyNode node = new EmptyNode(solver); typeCache.put(type, node); List<UnionNode> result = type.accept(new UnionNativeTypeVisitor()); solver.union(node, result); return new IncludeNode(solver, node); } } private Map<Pair<GenericType, Boolean>, List<UnionNode>> genericTypeCache = new HashMap<>(); private Map<Pair<InterfaceType, Boolean>, List<UnionNode>> interfaceCache = new HashMap<>(); private class UnionNativeTypeVisitor implements TypeVisitor<List<UnionNode>> { private final boolean isBaseType; public UnionNativeTypeVisitor(boolean isBaseType) { this.isBaseType = isBaseType; } public UnionNativeTypeVisitor() { this(false); } private Map<InterfaceType, GenericType> convertedTypeMap = new HashMap<>(); private List<UnionNode> recurse(Type t) { return t.accept(this); } @Override public List<UnionNode> visit(AnonymousType t) { return Collections.EMPTY_LIST; } @Override public List<UnionNode> visit(ClassType t) { throw new UnsupportedOperationException(); } @Override public List<UnionNode> visit(GenericType t) { if (genericTypeCache.containsKey(new Pair<>(t, isBaseType))) { return genericTypeCache.get(new Pair<>(t, isBaseType)); } ArrayList<UnionNode> result = new ArrayList<>(); genericTypeCache.put(new Pair<>(t, isBaseType), result); InterfaceType interfaceType = t.toInterface(); convertedTypeMap.put(interfaceType, t); result.addAll(recurse(interfaceType)); return result; } @Override public List<UnionNode> visit(InterfaceType t) { if (interfaceCache.containsKey(new Pair<>(t, isBaseType))) { return interfaceCache.get(new Pair<>(t, isBaseType)); } List<UnionNode> result = new ArrayList<>(); interfaceCache.put(new Pair<>(t, isBaseType), result); ObjectNode obj = new ObjectNode(solver); if (convertedTypeMap.containsKey(t)) { GenericType type = convertedTypeMap.get(t); if (nativeClasses.nameFromType(type) != null) { if (isBaseType) { obj.setIsBaseType(true); } obj.setTypeName(nativeClasses.nameFromType(type)); } } else { if (nativeClasses.nameFromType(t) != null) { if (isBaseType) { obj.setIsBaseType(true); } obj.setTypeName(nativeClasses.nameFromType(t)); } } result.add(obj); for (Map.Entry<String, Type> entry : t.getDeclaredProperties().entrySet()) { String key = entry.getKey(); Type type = entry.getValue(); obj.addField(key, new IncludeNode(solver, recurse(type))); } if (!t.getDeclaredCallSignatures().isEmpty()) { List<FunctionNode> functionNodes = t.getDeclaredCallSignatures().stream().map(NativeTypeFactory.this::fromSignature).collect(Collectors.toList()); result.add(new IncludeNode(solver, functionNodes)); } if (!t.getDeclaredConstructSignatures().isEmpty()) { List<FunctionNode> functionNodes = t.getDeclaredConstructSignatures().stream().map(NativeTypeFactory.this::fromSignature).collect(Collectors.toList()); result.add(new IncludeNode(solver, functionNodes)); } if (t.getDeclaredStringIndexType() != null) { result.add(new DynamicAccessNode(solver, solver.union(recurse(t.getDeclaredStringIndexType())), primitiveFactory.string())); } if (t.getDeclaredNumberIndexType() != null) { result.add(new DynamicAccessNode(solver, solver.union(recurse(t.getDeclaredNumberIndexType())), primitiveFactory.number())); } t.getBaseTypes().forEach(type -> { result.add(new IncludeNode(solver, type.accept(new UnionNativeTypeVisitor(true)))); }); return result; } @Override public List<UnionNode> visit(ReferenceType t) { return recurse(t.getTarget()); } @Override public List<UnionNode> visit(SimpleType t) { switch (t.getKind()) { case Any: return Arrays.asList(primitiveFactory.any()); case Boolean: return Arrays.asList(primitiveFactory.bool()); case Enum: return Arrays.asList(primitiveFactory.number()); // TODO: Enums? case Number: return Arrays.asList(primitiveFactory.number()); case String: return Arrays.asList(primitiveFactory.string()); case Undefined: return Arrays.asList(primitiveFactory.undefined()); case Void: return Collections.EMPTY_LIST; default: throw new UnsupportedOperationException("Unhandled type: " + t.getKind()); } } @Override public List<UnionNode> visit(TupleType t) { List<UnionNode> returnTypes = t.getElementTypes().stream().map(this::recurse).reduce(new ArrayList<>(), Util::reduceList); UnionNode result = solver.union(primitiveFactory.array(), new DynamicAccessNode(solver, new IncludeNode(solver, returnTypes), primitiveFactory.number())); return Arrays.asList(result); } @Override public List<UnionNode> visit(UnionType t) { return t.getElements().stream().map(this::recurse).reduce(new ArrayList<>(), Util::reduceList); } @Override public List<UnionNode> visit(UnresolvedType t) { throw new UnsupportedOperationException(); } @Override public List<UnionNode> visit(TypeParameterType t) { // Generics, doesn't do this yet. return Collections.EMPTY_LIST; } @Override public List<UnionNode> visit(SymbolType t) { // Does't handle symbols yet. return Collections.EMPTY_LIST; } } }
package com.study.audio.ui; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.os.Parcelable; import android.support.annotation.NonNull; import android.support.v4.media.MediaMetadataCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.request.RequestOptions; import com.study.audio.MusicData; import com.study.audio.MusicUtil; import com.study.audio.R; import java.util.ArrayList; import java.util.List; class AlbumGalleryAdapter extends RecyclerView.Adapter<AlbumGalleryAdapter.ViewHolder>{ private Context mContext; private MediaMetadataCompat media; private List<String> mAlbumList, mAlbumArtList, mArtistList; private List<MusicData> mAlbumMusicList; public AlbumGalleryAdapter(List<MusicData> musicDataList) { // TODO: 2018/9/3 Constructor with Music Structure this.mAlbumArtList = MusicUtil.mAlbumArtList; this.mAlbumList = MusicUtil.mAlbumList; mArtistList = new ArrayList<>(); mAlbumMusicList = musicDataList; for (String album : mAlbumList) { // Log.d("mAlbumlist",album); String artist = null; String temp = null; int i = 0; for (MusicData mediaData : musicDataList) { temp = artist; if (mediaData.getAlbum().equals(album)) { artist = mediaData.getArtist(); // Log.d("debug",temp+" "+artist+i); if(temp!=null) { if (!temp.equals(artist)) { i++; } } } } if(i>0) artist = "Multiple Players"; if(artist!=null) mArtistList.add(artist); else mArtistList.add("unknown"); } } @NonNull @Override public AlbumGalleryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { mContext = parent.getContext(); LayoutInflater inflater = LayoutInflater.from(mContext); View albumView = inflater.inflate(R.layout.cardview_album, parent, false); return new AlbumGalleryAdapter.ViewHolder(albumView); } @Override public void onBindViewHolder(@NonNull AlbumGalleryAdapter.ViewHolder holder, int position) { // TODO: 2018/8/20 Load the Media Data String albumArt = mAlbumArtList.get(position); String album = mAlbumList.get(position); String artist = mArtistList.get(position); RequestOptions requestOptions = new RequestOptions().centerCrop() .placeholder(R.drawable.ic_album_black_24dp); Glide.with(mContext) .load(albumArt) .apply(requestOptions) .into(holder.albumImageView); holder.albumImageView.setBackgroundColor(Color.GRAY); holder.albumArtistTextView.setText(artist); holder.albumTextView.setText(album); holder.albumTextView.setTextColor(Color.BLACK); holder.albumTextView.setSingleLine(true); holder.albumTextView.setEllipsize(TextUtils.TruncateAt.END); } @Override public int getItemCount() { return mAlbumArtList.size(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ public CardView albumCardView; public TextView albumTextView; public TextView albumArtistTextView; public ImageView albumImageView; public ViewHolder(View itemView) { super(itemView); albumCardView = (CardView) itemView.findViewById(R.id.card_view); albumTextView = (TextView) itemView.findViewById(R.id.card_album_text); albumArtistTextView = (TextView) itemView.findViewById(R.id.card_album_artist); albumImageView = (ImageView) itemView.findViewById(R.id.card_album_img); albumCardView.setOnClickListener(this); } @Override public void onClick(View view) { // TODO: 2018/9/3 Pass the Music Content and Start the Activity String album = mAlbumList.get(getLayoutPosition()); List<MusicData> tempList = new ArrayList<>(); for (MusicData tempMusic : mAlbumMusicList){ if (tempMusic.getAlbum().equals(album)) { tempList.add(tempMusic); } } Intent i = new Intent(mContext, SongActivity.class); i.putParcelableArrayListExtra("tempList", (ArrayList<? extends Parcelable>) tempList); i.putExtra("currentPosition", getLayoutPosition()); mContext.startActivity(i); } } }
package com.reactnative.googlecast.types; import androidx.annotation.Nullable; import com.google.android.gms.cast.Cast; public class RNGCActiveInputState { public static @Nullable String toJson(final int value) { switch (value) { case Cast.ACTIVE_INPUT_STATE_YES: return "active"; case Cast.ACTIVE_INPUT_STATE_NO: return "inactive"; case Cast.ACTIVE_INPUT_STATE_UNKNOWN: return "unknown"; default: return null; } } }
package ocdhis2; import java.io.File; import java.io.StringWriter; import java.util.ArrayList; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * @author loic * * See DHIS2 documentation : https://www.dhis2.org/doc/snapshot/en/developer/html/ch01s11.html * See DHIS2 corresponding API : https://www.dhis2.org/download/apidocs/org/hisp/dhis/dxf2/datavalueset/DataValueSet.html * * Warning : DHIS2 API does not verify if the dataset really uses an attributeOptionCombo. As long as the * attributeOptionCombo uid exists in the system, even if assigned to another dataset, it will accept the data. * */ @XmlRootElement(name="dataValueSet") public class DataValueSet { private String orgUnit; // ex: "DiszpKrYNg8" (ex: corresponding to 'Hôpital ABC') private String period; // ex: "201201" (ex here: January 2012) private String completeDate; // ex: "2015-09-28" private String attributeOptionCombo; // ex: "D2CUIPUKpk3" (ex: corresponding to "médecine interne") private String dataSet; // ex: "DiszpKrYNg8" (ex: corresponding to 'notification des décès') private ArrayList<DataValue> dataValues = new ArrayList<>(); @XmlAttribute(name="orgUnit") public String getOrgUnit() { return orgUnit; } public void setOrgUnit(String orgUnit) { this.orgUnit = orgUnit; } @XmlAttribute(name="period") public String getPeriod() { return period; } public void setPeriod(String period) { this.period = period; } @XmlAttribute(name="completeDate") public String getCompleteDate() { return completeDate; } public void setCompleteDate(String completeDate) { this.completeDate = completeDate; } @XmlAttribute(name="attributeOptionCombo") public String getAttributeOptionCombo() { return attributeOptionCombo; } public void setAttributeOptionCombo(String attributeOptionCombo) { this.attributeOptionCombo = attributeOptionCombo; } @XmlAttribute(name="dataSet") public String getDataSet() { return dataSet; } public void setDataSet(String dataSet) { this.dataSet = dataSet; } @XmlElement(name="dataValue") public ArrayList<DataValue> getDataValues() { return dataValues; } public void setDataValues(ArrayList<DataValue> dataValues) { this.dataValues = dataValues; } // Produces a file with the XML data, useful for offline data transmission. // This file can for example be stored on a USB key transferred to the DSNIS, // where it can be uploaded into the database using the DHIS2 import interface. // TODO : fix it so that the data is attached to the hospital user // (ex 'Hopital_XYZ_OpenClinic' user) and not the admin user who uploads it. // TODO : add path for the file // TODO : add values in the file name (and in comments) about who made it // (so the SNIS doesn't have dozens of "simple.xml" files) // TODO : possibly put in its own object, with a name etc as members public void toXMLFile() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(DataValueSet.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.marshal(this, new File("simple.xml") ); jaxbMarshaller.marshal(this, System.out); } // Print the XML data to the console public void toXMLConsole() throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(DataValueSet.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.marshal(this, System.out); } // Produce a string with the XML content, by converting a stream to a string // see http://stackoverflow.com/questions/2472155/ public String toXMLString() throws JAXBException { java.io.StringWriter stringWriter = new StringWriter(); JAXBContext jaxbContext = JAXBContext.newInstance(DataValueSet.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); jaxbMarshaller.marshal(this,stringWriter); return stringWriter.toString(); } @Override public String toString() { return "DataValueSet(" + dataValues + ")"; } }
package com.androidsample.contentresolversample; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; /** * This activity displays how to perform search using content resolver on our com.androidsample.contentprovidersample content * provider and also bind the cursor with the list view to the list view to display results using SimpleCursorAdapter. */ public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { private static final int LOADER_ID = 1239; private EditText mEditText; private SimpleCursorAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //set the list view ListView listView = (ListView) findViewById(R.id.data_list); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) { Cursor cursor = (Cursor) mAdapter.getItem(pos); Intent intent = new Intent(MainActivity.this,DetailActivity.class); intent.putExtra(DetailActivity.ARG_NAME_ID,cursor.getLong(cursor.getColumnIndex("_id"))); startActivity(intent); } }); //Bind the cursor using SimpleCursorAdapter to the list view. mAdapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_expandable_list_item_1, null, new String[]{"name"}, new int[]{android.R.id.text1}); listView.setAdapter(mAdapter); mEditText = (EditText) findViewById(R.id.name_et); findViewById(R.id.btn_add).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mEditText.getText().length() <= 0) return; search(mEditText); } }); } private void search(EditText editText) { mEditText = editText; // Initialize the Loader with id '1239' and callbacks. // If the loader doesn't already exist, one is created. Otherwise, // the already created Loader is reused. In either case, the // LoaderManager will manage the Loader across the Activity/Fragment // lifecycle, will receive any new loads once they have completed, // and will report this new data back via callbacks. LoaderManager lm = getSupportLoaderManager(); //close any loader that is already running lm.destroyLoader(LOADER_ID); //init new loader lm.initLoader(LOADER_ID, null, this); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { //create the content resolver query. The syntax for the content uri should be content://authority/names/query. //This syntax represents the search operation in com.androidsample.contentprovidersample application. return new CursorLoader(this, Uri.parse("content://com.androidsample.contentprovidersample/names/" + mEditText.getText().toString().trim()), new String[]{"name", "_id"}, null, null, "name ASC"); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (loader.getId() == LOADER_ID) { // The asynchronous load is complete and the data // is now available for use. Only now can we associate // the queried Cursor with the SimpleCursorAdapter. if (mAdapter != null) mAdapter.swapCursor(data); } } @Override public void onLoaderReset(Loader<Cursor> loader) { // For whatever reason, the Loader's data is now unavailable. // Remove any references to the old data by replacing it with // a null Cursor. mAdapter.swapCursor(null); } }
package com.mlms.mobilelaundrymanagementsystemadmin.ui.home; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.mlms.mobilelaundrymanagementsystemadmin.OpenNewBillActivity; import com.mlms.mobilelaundrymanagementsystemadmin.R; import com.mlms.mobilelaundrymanagementsystemadmin.adapters.ActiveListAdapter_Admin; import com.mlms.mobilelaundrymanagementsystemadmin.databinding.FragmentHomeBinding; import com.mlms.mobilelaundrymanagementsystemadmin.models.CabangListModel; import com.mlms.mobilelaundrymanagementsystemadmin.models.LaundryModel; import com.mlms.mobilelaundrymanagementsystemadmin.models.adminNemployeeModel; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Objects; public class HomeFragment extends Fragment implements ActiveListAdapter_Admin.OnShowInfoListener{ private static final String TAG ="HomeFragment"; private FragmentHomeBinding binding; SwipeRefreshLayout pullToRefresh; FirebaseAuth auth; FirebaseFirestore fireStore; FirebaseDatabase database; RecyclerView recView; List<LaundryModel> laundryModelList; ActiveListAdapter_Admin activeListAdapter_admin; String name,role,cabang; Calendar calendar; Button OpenNewBill_btn; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); fireStore=FirebaseFirestore.getInstance(); database=FirebaseDatabase.getInstance(); auth=FirebaseAuth.getInstance(); calendar=Calendar.getInstance(); recView=root.findViewById(R.id.listOfActive); defineRole(); OpenNewBill_btn=root.findViewById(R.id.open_bill); OpenNewBill_btn.setOnClickListener(v -> { Intent intent=new Intent(getActivity(), OpenNewBillActivity.class); startActivity(intent); }); pullToRefresh=root.findViewById(R.id.RefreshHomePage); pullToRefresh.setOnRefreshListener(() -> { pullToRefresh.setRefreshing(false); Log.i(TAG,"onRefresh"); //listAllActiveStatus(); defineRole(); }); Log.i(TAG,"onCreate"); return root; } public void defineRole(){ database.getReference().child("loginAdminNEmployee").child(Objects.requireNonNull(auth.getCurrentUser()).getUid()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { adminNemployeeModel adminNemployeeModel=snapshot.getValue(adminNemployeeModel.class); assert adminNemployeeModel != null; role=adminNemployeeModel.getRole(); cabang=adminNemployeeModel.getCabang(); name=adminNemployeeModel.getName(); if(role.equals("Admin")){ listAllActiveStatus_admin(); OpenNewBill_btn.setVisibility(View.GONE); }else if(role.equals("Employee")){ listAllActiveStatus_employee(cabang); } } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } @SuppressLint("NotifyDataSetChanged") public void listAllActiveStatus_employee(String cabang){ // Initiate RecycleView recView.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false )); laundryModelList=new ArrayList<>(); activeListAdapter_admin= new ActiveListAdapter_Admin(getActivity(),laundryModelList,this ); recView.setAdapter(activeListAdapter_admin); fireStore.collection("Cabang Information") .document(cabang) .collection("Active List") .whereNotEqualTo("status","Sudah diambil") .get().addOnCompleteListener(task -> { if(task.isSuccessful()){ for(QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())){ LaundryModel laundryModel=document.toObject(LaundryModel.class); laundryModelList.add(laundryModel); activeListAdapter_admin.notifyDataSetChanged(); } }else{ Toast.makeText(getActivity(),"Error"+task.getException(),Toast.LENGTH_SHORT).show(); } }); } public void listAllActiveStatus_admin(){ List<CabangListModel> cabangListModelList=new ArrayList<>(); fireStore.collection("Cabang Information") .get() .addOnCompleteListener(task -> { if(task.isSuccessful()){ for(QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())){ CabangListModel cabangListModel=document.toObject(CabangListModel.class); cabangListModelList.add(cabangListModel); } for(CabangListModel list: cabangListModelList){ String cabangL=list.getCabangName(); listAllActiveStatus(cabangL); } }else{ Toast.makeText(getActivity(),"Error"+task.getException(),Toast.LENGTH_SHORT).show(); } }); } @SuppressLint("NotifyDataSetChanged") public void listAllActiveStatus(String cabangName){ // Initiate RecycleView recView.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false )); laundryModelList=new ArrayList<>(); activeListAdapter_admin= new ActiveListAdapter_Admin(getActivity(),laundryModelList,this ); recView.setAdapter(activeListAdapter_admin); fireStore.collection("Cabang Information") .document(cabangName) .collection("Active List") .whereNotEqualTo("status","Sudah diambil") .get().addOnCompleteListener(task -> { if(task.isSuccessful()){ for(QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())){ LaundryModel laundryModel=document.toObject(LaundryModel.class); laundryModelList.add(laundryModel); activeListAdapter_admin.notifyDataSetChanged(); } }else{ Toast.makeText(getActivity(),"Error"+task.getException(),Toast.LENGTH_SHORT).show(); } }); } @Override public void OnShowInfoClick(int position){ } @Override public void onStart() { super.onStart(); Log.i(TAG,"onStart"); } @Override public void onStop() { super.onStop(); Log.i(TAG,"onStop"); } @Override public void onPause() { super.onPause(); Log.i(TAG,"onPause"); } @Override public void onResume() { super.onResume(); Log.i(TAG,"onResume"); } @Override public void onDestroyView() { super.onDestroyView(); binding = null; Log.i(TAG,"onDestroy"); } }
package com.test.base; import java.util.Arrays; /** * .数据 -> 图 * .被坑了,应该用链表实现图的,用数组实现,麻烦又功能弱 * @author YLine * * 2019年2月22日 下午1:53:14 */ public class ArrayGraph { public static ArrayGraph createUndirectGraph(int capacity) { ArrayGraph graph = new ArrayGraph(UNDIRECTED_GRAPH, capacity); attachData(graph); return graph; } public static ArrayGraph createDirectGraph(int capacity) { ArrayGraph graph = new ArrayGraph(DIRECTED_GRAPH, capacity); attachData(graph); return graph; } private static void attachData(ArrayGraph graph) { graph.addVertex("0"); graph.addVertex("1"); graph.addVertex("2"); graph.addVertex("3"); graph.addVertex("4"); graph.addVertex("5"); graph.addEdge(0, 1); graph.addEdge(0, 2); graph.addEdge(1, 3); graph.addEdge(1, 4); graph.addEdge(2, 1); graph.addEdge(2, 4); graph.addEdge(3, 5); graph.addEdge(4, 5); } private static final boolean UNDIRECTED_GRAPH = false;// 无向图标志 private static final boolean DIRECTED_GRAPH = true;// 有向图标志 private int capacity; private boolean graphType; /** 实际向量大小 */ private int vertexSize; // 存储所有顶点信息的一维数组 private Object[] vertexesArray; // 存储图中顶点之间关联关系的二维数组,及边的关系 private boolean[][] edgesMatrix; // 记录第i个节点是否被访问过 private boolean[] visited; /** * @param graphType 图的类型:有向图/无向图 * @param size 图的 最大容量值 */ private ArrayGraph(boolean graphType, int capacity) { this.graphType = graphType; this.capacity = capacity; // 原始数据 this.vertexSize = 0; this.vertexesArray = new Object[capacity]; this.edgesMatrix = new boolean[capacity][capacity]; // 临时数据 this.visited = new boolean[capacity]; } /** * .获取指定点的值 * @param index 位置 * @return 值 */ public Object getValue(int index) { checkValid(index); visited[index] = true; return vertexesArray[index]; } /** * .获取指定点的所有下一个值 * @param index 当前位置 * @return 所有下一个位置 */ public int[] getNextArray(int index) { checkValid(index); int[] nextArray = new int[capacity]; int length = 0; for (int i = 0; i < edgesMatrix.length; i++) { if (edgesMatrix[index][i]) { nextArray[length] = i; length++; } } return Arrays.copyOf(nextArray, length); } public void resetState() { Arrays.fill(visited, false); } public void setVisitedEnable(int index) { checkValid(index); visited[index] = true; } public boolean isVisited(int index) { checkValid(index); return visited[index]; } public int getSize() { return vertexSize; } /** * .添加点 * @param val 点内容 * @return */ private void addVertex(Object val) { assert (null != val); // 如果为空,则终止程序运行 vertexesArray[vertexSize] = val; vertexSize++; } /** * .添加边[方向][第一个位置 指向 第二个位置,有则返回true] * @param vnum1 第一个点位置 * @param vnum2 第二个点位置 */ private void addEdge(int vnum1, int vnum2) { assert (vnum1 >= 0 && vnum1 < capacity); assert (vnum2 >= 0 && vnum2 < capacity); assert (vnum1 != vnum2); if (graphType) // 有向图 { edgesMatrix[vnum1][vnum2] = true; } else { edgesMatrix[vnum1][vnum2] = true; edgesMatrix[vnum2][vnum1] = true; } } private void checkValid(int index) { if (index < 0 || index >= capacity) { throw new IllegalArgumentException("index is error"); } } }
package no.bring.demo.logic; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Component public class Logic { // En Logic klasse som inneholder logikken til kalkulatoren // for utregning av en enkelsending public int singlePrice(int base, int packetp, int count , int weight,int weightp){ int total = (weight*count * weightp) + (packetp*count) + base; return total; } // For utregning av matrise public int[][] multiplePrice(int base, int packetp, int count , int weight,int weightp){ int[][] liste = new int[weight][count]; for(int i = 0; i < weight; i++){ for(int k = 0 ; k < count; k++){ liste[i][k] = ((i+1)*(k+1) * weightp) + (packetp*(k+1)) + base; } } return liste; } }
/* * Copyright (C) 2003-2013 eXo Platform SAS. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.exoplatform.social.common.embedder; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.exoplatform.container.xml.InitParams; import org.exoplatform.container.xml.ValueParam; import org.exoplatform.services.log.ExoLogger; import org.exoplatform.services.log.Log; import org.json.JSONException; import org.json.JSONObject; /** * @since 4.0.0-GA */ public class YoutubeEmbedder implements Embedder { private static final Log LOG = ExoLogger.getLogger(YoutubeEmbedder.class); private static final Pattern YOUTUBE_ID_PATTERN = Pattern .compile("(youtu\\.be\\/|youtube\\.com\\/(watch\\?(.*&)?v=|(embed|v)\\/))([^\\?&\"'>]+)"); private static final Pattern CONTENT_URL_PATTERN = Pattern .compile(".*youtube\\.com\\/v\\/([^\\&\\?\\/]+)"); private Map<Pattern,String> schemeEndpointMap; private Pattern youTubeURLPattern; private String url; /** * constructor * @param initParams */ public YoutubeEmbedder(InitParams initParams) { schemeEndpointMap = new HashMap<Pattern,String>(); Iterator<ValueParam> it = initParams.getValueParamIterator(); ValueParam valueParam = null; while(it.hasNext()) { valueParam = it.next(); String youTubeReg = valueParam.getName().replaceAll("&amp;", "&"); String youTubeFeedsURL = valueParam.getValue().replaceAll("&amp;", "&"); youTubeURLPattern = Pattern.compile(youTubeReg); schemeEndpointMap.put(youTubeURLPattern, youTubeFeedsURL); } } public Pattern getYouTubeURLPattern() { return youTubeURLPattern; } public void setUrl(String url) { this.url = url; } /** * Processes input link and returns data wrapped into a model called ExoSocialMedia. * * @return ExoSocialMedia object that corresponds to the link. */ public ExoSocialMedia getExoSocialMedia() { String feedsURL = null; for(Pattern pattern : schemeEndpointMap.keySet()) { Matcher matcher = pattern.matcher(url); if(matcher.find()) { feedsURL = schemeEndpointMap.get(pattern); } else { return null; } } // BufferedReader bufferedReader; JSONObject jsonObject = null; try { Matcher matcher = YOUTUBE_ID_PATTERN.matcher(url); String youtubeId = null; while (matcher.find()) { youtubeId = matcher.group(5); } String youTubeFeedURL = String.format(feedsURL, youtubeId); URL reqURL = new URL(youTubeFeedURL); bufferedReader = new BufferedReader(new InputStreamReader(reqURL.openStream())); StringBuffer stringBuffer = new StringBuffer(); String eachLine = null; while ((eachLine = bufferedReader.readLine()) != null) { stringBuffer.append(eachLine); } bufferedReader.close(); jsonObject = new JSONObject(stringBuffer.toString()); JSONObject entryObject = jsonObject.getJSONObject("entry"); // String html = buildHtmlInfo(entryObject.getJSONObject("content")); if (html == null) return null; ExoSocialMedia mediaObject = new ExoSocialMedia(); JSONObject mediaGroupObject = entryObject.getJSONObject("media$group"); mediaObject.setTitle(entryObject.getJSONObject("title").getString("$t")); mediaObject.setHtml(html); mediaObject.setDescription(mediaGroupObject.has("media$description") ? mediaGroupObject .getJSONObject("media$description").getString("$t") : ""); return mediaObject; } catch (JSONException e) { LOG.debug("Any syntax error cause to JSON exception.", e); return null; } catch (IOException e) { LOG.debug("Problem with IO when open url.", e); return null; } catch (Exception e) { LOG.debug("Problem occurred when get data from youtube link.", e); return null; } } private String buildHtmlInfo(JSONObject contentObject) throws JSONException { String videoContentURL = contentObject.getString("src"); // Matcher matcher = CONTENT_URL_PATTERN.matcher(videoContentURL); String contentSrc = null; while (matcher.find()) { contentSrc = matcher.group(0); } if (contentSrc == null) { LOG.info("Returned content url not match the pattern to get content source."); return null; } String videoPlayerType = contentObject.getString("type"); StringBuilder contentURL = new StringBuilder(); contentURL.append("<embed ") .append("width=\"420\" height=\"345\" ") .append("src=\"") .append(contentSrc) .append("\" type=\"") .append(videoPlayerType) .append("\">") .append("</embed>"); return contentURL.toString(); } }
package com.esum.framework.jdbc; import java.util.HashMap; /** * DB에서 Select한 정보를 Map<String, Object>을 담는다. */ public class RecordMap extends HashMap<String, Object>{ private static final long serialVersionUID = -8454065579596493854L; public Object getObject(String key) { return get(key); } public Object getObject(String key, Object defaultValue) { Object o = get(key); if(o==null) return defaultValue; return o; } public String getString(String key) { Object v = get(key); if(v==null) return null; return v.toString(); } public String getString(String key, String defaultValue) { Object v = get(key); if(v==null) return defaultValue; return v.toString(); } public String getStringWithTrim(String key, String defaultValue) { Object v = get(key); if (v == null || v.toString().length() == 0) return defaultValue; return v.toString(); } /** * key에 해당되는 값이 없는 경우 -1을 리턴한다. */ public int getInt(String key) { return getInt(key, -1); } public int getInt(String key, int defaultValue) { Object v = get(key); if(v==null) return defaultValue; return Integer.parseInt(v.toString()); } /** * key에 해당되는 값이 없는 경우 -1을 리턴한다. */ public long getLong(String key) { return getLong(key, -1); } public long getLong(String key, long defaultValue) { Object v = get(key); if(v==null) return defaultValue; return Long.parseLong(v.toString()); } }
/** * Copyright (c) 2012, Institute of Telematics, Institute of Information Systems (Dennis Pfisterer, Sven Groppe, Andreas Haller, Thomas Kiencke, Sebastian Walther, Mario David), University of Luebeck * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * - Neither the name of the University of Luebeck nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package console.commands; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import lupos.datastructures.items.Triple; import luposdate.evaluators.P2PIndexQueryEvaluator; import net.tomp2p.p2p.Peer; import net.tomp2p.peers.Number480; import net.tomp2p.peers.PeerAddress; import net.tomp2p.storage.Data; /** * Gibt den lokalen Speicher eines Peers aus. */ public class GetLocalStorage implements Command { /* * (non-Javadoc) * * @see console.commands.Command#execute(java.util.Scanner, * net.tomp2p.p2p.Peer, luposdate.evaluators.P2PIndexQueryEvaluator) */ public void execute(Scanner scanner, Peer peer, P2PIndexQueryEvaluator evaluator) { printHeader(scanner, peer, evaluator); printElements(peer); printFooter(peer); } private void printHeader(Scanner scanner, Peer peer, P2PIndexQueryEvaluator evaluator) { Command getMyIdCommand = new GetMyID(); getMyIdCommand.execute(scanner, peer, evaluator); System.out.println(); System.out.println("Key\t\t\t\t\t\tValue"); } private void printFooter(Peer peer) { System.out.println(); System.out.println("local storagesize: " + peer.getPeerBean().getStorage().map().size()); } private void printElements(Peer peer) { Map<Number480, Data> map = peer.getPeerBean().getStorage().map(); for (Entry<Number480, Data> result : map.entrySet()) { try { System.out.print(result.getKey().getLocationKey() + "\t"); if (result.getValue().getObject().getClass() == String.class) { System.out .println(result.getValue().getObject().toString()); } else if (result.getValue().getObject().getClass() == Triple.class) { System.out.println(((Triple) result.getValue().getObject()) .toN3String()); } else if (result.getValue().getObject().getClass() == PeerAddress.class) { System.out.println("PeerAdress von ID: " + ((PeerAddress) result.getValue().getObject()) .getID()); } else { System.out.println("Unbekanntes Format!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /* * (non-Javadoc) * * @see console.commands.Command#getDescription() */ public String getDescription() { return "returns all elements that are in the local peer storage"; } }
package com.atguigu.java; /* ��++ : �����㣨��ֵ��������1 ǰ++ ��������1 �����㣨��ֵ�� ��-- : �����㣨��ֵ�� ���Լ�1 ǰ-- �����Լ�1 �����㣨��ֵ�� */ public class test1{ public static void main(String[] args){ System.out.println("---hou++---"); int a = 5,b = 10; a++; System.out.println("a = " + a);//5 int num1 = a; System.out.println("num1 = " + num1); //6 System.out.println("---++qian---"); ++a; System.out.println("a = " + a);//6 int num2 = a; System.out.println("num2 = " + num2);//6 System.out.println("---hou-----"); b--; System.out.println("b = " + b);//10 int num3 = b; System.out.println("num3 = " + num3);//9 System.out.println("-----qian---"); --b; System.out.println("b = " + b);//9 int num4 = b; System.out.println("num4 = " + num4);//9 } }
open module modmain { // allow reflective access, currently used in the example_jerry-mouse requires modcallbackhandler; requires modcallee; }
package com.bnebit.sms.util.exception; //리팩토링 후 안 쓰는 Exception @Deprecated public class SessionCheckException extends RuntimeException{ private static final long serialVersionUID = 1L; private String message; private String url = "/error/errorPage"; public SessionCheckException() { this.message = "에러가 났네요~ 에러가 났어요~"; } public SessionCheckException(String message) { this.message = message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getUrl() { return url; } }
package in.rgukt.proxyserver.core; import java.util.HashMap; /** * HTTPRequest is used to store incoming HTTP requests from web clients like * browsers etc., This has all the methods to conveniently access individual * pieces of a HTTP request like HTTP method, resource, version, headers. * * @author Venkata Jaswanth * */ public final class HTTPRequest { private String[] initialRequestLineArray; private String initialRequestLine; /** * HashTable to store all headers and their values. */ private HashMap<String, String> headers = new HashMap<String, String>(); /** * Stores the complete HTTP request (just for speed) */ private StringBuilder completeHTTPRequest = new StringBuilder(); private boolean firstHeader = true; byte[] body = new byte[1]; public HTTPRequest() { } public final void setInitialRequestLine(String initialRequestLine) { assert (initialRequestLine != null); this.initialRequestLine = initialRequestLine; completeHTTPRequest.append(initialRequestLine); completeHTTPRequest.append('\n'); this.initialRequestLineArray = initialRequestLine.split(" "); } public final void setHeader(String header) { header = header.replaceAll("[\\r\\n]", ""); if (firstHeader) { setInitialRequestLine(header); firstHeader = false; return; } int pivot = header.indexOf(':'); headers.put(header.substring(0, pivot), header.substring(pivot + 2, header.length())); completeHTTPRequest.append(header); completeHTTPRequest.append('\n'); } public final String getInitialRequestLine() { return initialRequestLine; } public final String getMethod() { return initialRequestLineArray[0]; } public final String getResource() { return initialRequestLineArray[1]; } public final String getHTTPVersion() { return initialRequestLineArray[2]; } public final String getHeader(final String key) { return headers.get(key); } public final boolean hasHeader(final String key) { return headers.containsKey(key); } public final String getCompleteRequest() { return completeHTTPRequest.toString(); } /** * Add arbitary strings to the complete request. This gets added to the * completeHTTPRequest data structure. (for flexibility) * * @param request * The string to be added */ public final void addToRequest(String request) { completeHTTPRequest.append(request); } }
package com.sherry.epaydigital.bussiness.service; import com.sherry.epaydigital.bussiness.domain.PaymentRequestDomain; import com.sherry.epaydigital.data.model.PaymentRequest; import com.sherry.epaydigital.data.repository.PaymentRequestRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PaymentRequestService { private final PaymentRequestRepository paymentRequestRepository; @Autowired public PaymentRequestService(PaymentRequestRepository paymentRequestRepository) { this.paymentRequestRepository = paymentRequestRepository; } public void addPaymentRequestData(PaymentRequestDomain paymentRequestDomain) { PaymentRequest paymentRequest = new PaymentRequest(); paymentRequest.setBuyer_email(paymentRequestDomain.getBuyer_email()); paymentRequest.setCustomer_fk(paymentRequestDomain.getCustomer()); paymentRequestRepository.save(paymentRequest); } }
package com.dbs.portal.database.to.subscription; public interface ScheduledJobFieldConstants { // Dependent Services public static final String SECURITY_SVC = "securityService"; public static final String PREFERENCES_SVC = "preferencesService"; public static final String SUBSCRIPTION_SVC = "subscriptionService"; // Method Invocation Maps public static final String FUNC_ID_TARGET_OBJ_MAP = "functionIdTargetObjectMap"; public static final String FUNC_ID_TARGET_MTD_MAP = "functionIdTargetMethodMap"; // Preprocessor Map public static final String FUNC_ID_PREPROCESSOR_MAP = "functionIdPreprocessorMap"; // Subscription Information public static final String SUBSCRIPTION = "subscription"; // Distribution public static final String MAIL_SENDER = "mailSender"; public static final String SUBS_MAIL_MSG = "subscriptionMailMessages"; // Generation public static final String SUBS_REPORT_PATH = "reportPath"; // Result public static final String FILENAME = "filename"; public static final String STATUS = "status"; }
package com.culturaloffers.maps.model; import javax.persistence.*; import java.util.Objects; import java.util.Set; @Entity public class OfferType { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(nullable = false, unique = true) private String name; @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "offerType") private Set<Subtype> subtypes; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Subtype> getSubtypes() { return subtypes; } public void setSubtypes(Set<Subtype> subtypes) { this.subtypes = subtypes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } OfferType offerType = (OfferType) o; if (offerType.getId() == null || id == null) { if(offerType.getName().equals(getName())){ return true; } return false; } return Objects.equals(id, offerType.getId()); } }
/** * Copyright 2015 www.codereligion.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.codereligion.cherry.test.hamcrest.logback; import ch.qos.logback.classic.spi.ILoggingEvent; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import static com.google.common.base.Preconditions.checkArgument; /** * A matcher which expects at least one item of an iterable of {@link ch.qos.logback.classic.spi.ILoggingEvent ILoggingEvents} to match the given {@link * org.hamcrest.Matcher}. * * @author Sebastian Gr&ouml;bler * @since 23.03.2015 */ public class LoggingEventIterableHasItem extends TypeSafeDiagnosingMatcher<Iterable<ILoggingEvent>> { /** * Creates a new matcher for iterables of {@link ch.qos.logback.classic.spi.ILoggingEvent ILoggingEvents} that only matches when at least one event matches * the given {@link org.hamcrest.Matcher}. It is recommended to use this specific matcher instead of just combining the other matcher with {@link * org.hamcrest.CoreMatchers#hasItem(Object)} because of the improved error output and generics handling. * <p/> * Example usage: {@code assertThat(event, hasItem(withLevel(Level.ERROR)));} * <p/> * Example output: {@code Expected: an iterable containing an ILoggingEvent with level: ERROR but: was [ILoggingEvent{level=INFO, formattedMessage='some * Message', loggedBy=SomeLogger, throwable=null}]} * * @param itemMatcher the logging event {@link Matcher} to check the items with * @return a new matcher * @throws java.lang.IllegalArgumentException when the given parameter is {@code null} */ public static Matcher<Iterable<ILoggingEvent>> hasItem(final Matcher<ILoggingEvent> itemMatcher) { return new LoggingEventIterableHasItem(itemMatcher, false); } /** * Creates a new matcher for iterables of {@link ch.qos.logback.classic.spi.ILoggingEvent ILoggingEvents} that only matches when at no event matches the * given {@link org.hamcrest.Matcher}. This matcher is the negation of {@link LoggingEventIterableHasItem#hasItem(Matcher)}. It is recommended to use this * specific matcher instead of just combining the other matcher with {@link org.hamcrest.CoreMatchers#not(Matcher)} because of the improved error output. * <p/> * Example usage: {@code assertThat(event, hasNoItem(withLevel(Level.ERROR)));} * <p/> * Example output: {@code Expected: an iterable not containing an ILoggingEvent with level: ERROR but: was [ILoggingEvent{level=ERROR, * formattedMessage='some Message', loggedBy=SomeLogger, throwable=null}]} * * @param itemMatcher the logging event {@link Matcher} to check the items with * @return a new matcher * @throws java.lang.IllegalArgumentException when the given {@code itemMatcher} is {@code null} */ public static Matcher<Iterable<ILoggingEvent>> hasNoItem(final Matcher<ILoggingEvent> itemMatcher) { return new LoggingEventIterableHasItem(itemMatcher, true); } private final Matcher<ILoggingEvent> itemMatcher; private final boolean negated; private LoggingEventIterableHasItem(final Matcher<ILoggingEvent> itemMatcher, final boolean negated) { checkArgument(itemMatcher != null, "itemMatcher must not be null."); this.itemMatcher = itemMatcher; this.negated = negated; } @Override protected boolean matchesSafely(final Iterable<ILoggingEvent> collection, final Description mismatchDescription) { mismatchDescription.appendText("iterable contained "); if (negated) { return negativeMatches(collection, mismatchDescription); } else { return positiveMatches(collection, mismatchDescription); } } private boolean positiveMatches(final Iterable<ILoggingEvent> collection, final Description mismatchDescription) { mismatchDescription.appendText("["); boolean isPastFirst = false; for (final Object item : collection) { if (itemMatcher.matches(item)) { return true; } if (isPastFirst) { mismatchDescription.appendText(", "); } itemMatcher.describeMismatch(item, mismatchDescription); isPastFirst = true; } mismatchDescription.appendText("]"); return false; } private boolean negativeMatches(final Iterable<ILoggingEvent> collection, final Description mismatchDescription) { for (final Object item : collection) { if (itemMatcher.matches(item)) { itemMatcher.describeMismatch(item, mismatchDescription); return false; } } return true; } @Override public void describeTo(final Description description) { if (negated) { description.appendText("an iterable not containing "); } else { description.appendText("an iterable containing "); } description.appendDescriptionOf(itemMatcher); } }
package home_work_1.txt; public class Txt1_3 { public static void main (String[] args){ int num1 = -42; int num2 = -15; int a = ~num1; //было 11010100 System.out.println(a); //стало 00101011 a = ~num2; //было 11110111 System.out.println(a); //стало 00001000 a = num1 & num2; //было 11010100 System.out.println(a); // 11110111 //стало 11010100 //a = num1 &= num2; //System.out.println(a); a = num1 | num2; //было 11010100 // 11110111 System.out.println(a); //стало 11110111 //a = num1 |= num2; //System.out.println(a); a = num1 ^ num2; //было 11010100 // 11110111 System.out.println(a); //стало 00100011 //a = num1 ^= num2; //System.out.println(a); a = num1 >> 2; //было 11010100 System.out.println(a); // на 2 вправо // 00110101 a = num2 >> 2; //было 11110111 System.out.println(a); // на 2 вправо // 00111101 //a = num1 >>= num2; //System.out.println(a); a = num1 >>> 2; //было 11010100 System.out.println(a); // на 2 вправо // 0011010100 a = num2 >>> 2; //было 11110111 System.out.println(a); // на 2 вправо // 0011110111 a = num1 << 2; //было 11010100 System.out.println(a); // на 2 влево //a = num1 <<= num2; // 01010000 //System.out.println(a); //a = num1 >>>= num2; //System.out.println(a); a = num2 << 2; //было 11110111 System.out.println(a); // на 2 влево // 11011100 } }
package com.quixmart.sdk.support; public class QuixmartException extends RuntimeException { public QuixmartException() { super(); } public QuixmartException(String message) { super(message); } public QuixmartException(String message, Throwable cause) { super(message, cause); } public QuixmartException(Throwable cause) { super(cause); } }
package com.train.amm; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import com.train.amm.utils.Utils; public class ProviderSimulateActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_provider_simulate); } //通过provider进行增加操作 public void insertPro(View view) { //通过内容提供者,把数据插入数据库 //获取contentresolver对象 ContentResolver contentResolver = getContentResolver(); ContentValues contentValues = new ContentValues(); // //contentValues.put("phone", "66666"); //uri:内容提供者的主机名 //values要插入的数据 //为第一个表所用的 // contentResolver.insert(Uri.parse("content://com.train.pprovider"), contentValues); // // contentValues.put("name", "pdtest002"); // contentValues.put("phone", "2222"); // contentValues.put("salary", "22223"); // contentResolver.insert(Uri.parse("content://com.train.pprovider"), contentValues); // // contentValues.put("name", "pdtest003"); // contentValues.put("phone", "33333"); // contentValues.put("salary", "33333"); // contentResolver.insert(Uri.parse("content://com.train.pprovider"), contentValues); //第二个student表所用 contentValues.put("salary",2222); // contentValues.put("name","studentprovider"); contentValues.put("name","observer"); contentResolver.insert(Uri.parse("content://com.train.pprovider/student"), contentValues); } //通过provider进行删除操作 public void deletePro(View view) { //获取contentresolver对象 ContentResolver contentResolver = getContentResolver(); int delete = contentResolver.delete(Uri.parse("content://com.train.pprovider"), "name = ?", new String[]{"providertest"}); Utils.showShortToast(getApplicationContext(), delete + ""); } //通过provider进行修改操作 public void updatePro(View view) { //获取contentresolver对象 ContentResolver contentResolver = getContentResolver(); ContentValues contentValues = new ContentValues(); contentValues.put("name", "updateprovider"); int update = contentResolver.update(Uri.parse("content://com.train.pprovider"), contentValues, "name = ?", new String[]{"pdtest002"}); Utils.showShortToast(getApplicationContext(), update + ""); } //通过provider进行查询操作 public void searchPro(View view){ //获取contentresolver对象 ContentResolver contentResolver = getContentResolver(); Cursor cursor = contentResolver.query(Uri.parse("content://com.train.pprovider/person/4"), null, null, null, null); while(cursor.moveToNext()){ String name = cursor.getString(cursor.getColumnIndex("name")); String salary = cursor.getString(cursor.getColumnIndex("salary")); String phone = cursor.getString(cursor.getColumnIndex("phone")); Utils.showShortToast(getApplicationContext(),"name: "+ name +" "+"salary: "+ salary + " " + "phone: " + phone); } } }
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package com.neuron.mytelkom; import android.content.DialogInterface; import android.content.Intent; // Referenced classes of package com.neuron.mytelkom: // CreateNewConferenceAddParticipantActivity, CreateNewConferenceParticipantActivity class this._cls0 implements android.content.y._cls4 { final CreateNewConferenceAddParticipantActivity this$0; public void onClick(DialogInterface dialoginterface, int i) { Intent intent = new Intent(); intent.putExtra(CreateNewConferenceAddParticipantActivity.KEY_POSITION, position); setResult(CreateNewConferenceParticipantActivity.DELETE_PARTICIPANT_RESULT_CODE, intent); finish(); } () { this$0 = CreateNewConferenceAddParticipantActivity.this; super(); } }
package com.cqut.dao; import com.cqut.model.RateGroup; public interface RateGroupMapper { int deleteByPrimaryKey(String rategroupid); int insert(RateGroup record); int insertSelective(RateGroup record); RateGroup selectByPrimaryKey(String rategroupid); int updateByPrimaryKeySelective(RateGroup record); int updateByPrimaryKey(RateGroup record); }
package assignment2; import java.util.Scanner; public class assignment12 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print(" Enter your Name: "); String name = input.nextLine(); System.out.print("\n Enter your Nationality: "); String nationality = input.nextLine(); System.out.print("\n Enter your Roll Number: "); int roll = input.nextInt(); System.out.println("\n Name: " + name); System.out.println("\n Nationality: "+ nationality); System.out.println("\n Roll No: " + roll); input.close(); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package br.com.vebo.dados.swing.table; import br.com.vebo.dados.mapeamento.Calculo; import br.com.vebo.util.DoubleUtil; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; /** * * @author mohfus */ public class CalculoTableModel extends AbstractTableModel{ private String[] colunas = new String[]{"Código", "Nome", "Qtd Essência"}; private List<Calculo> calculos = new ArrayList<Calculo>(); public int getColumnCount() { return colunas.length; } public int getRowCount() { return calculos.size(); } public String getColumnName(int col) { return colunas[col]; } public Object getValueAt(int row, int col) { Calculo calculo = calculos.get(row); switch(col) { case 0: return calculo.getId(); case 1: return calculo.getNome(); case 2: return new DoubleUtil().doubleParaString(calculo.getUtilizacaoEssencia(), "#,##0.#######"); } return null; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public void setCalculos(List<Calculo> calculos) { this.calculos = calculos; } }
import com.sun.imageio.plugins.gif.GIFImageReader; import com.sun.imageio.plugins.gif.GIFImageReaderSpi; import com.sun.imageio.plugins.png.PNGImageWriter; import com.sun.imageio.plugins.png.PNGImageWriterSpi; import javax.imageio.spi.ImageReaderSpi; import javax.imageio.spi.ImageWriterSpi; import javax.imageio.stream.FileImageInputStream; import javax.imageio.stream.FileImageOutputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import javax.imageio.stream.MemoryCacheImageOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * @author Frode Fan * @version 1.0 * @since 2019/9/19 */ public class Gif { public static void main(String[] args) throws IOException { for (int i = 0; i < 4; i++) { getGifOneFrame("d:\\imgCode.gif", "d:\\" + i + ".png", i); } } public static void getGifOneFrame(String src, String target, int frame) throws IOException { FileImageInputStream in = null; FileImageOutputStream out = null; try { in = new FileImageInputStream(new File(src)); ImageReaderSpi readerSpi = new GIFImageReaderSpi(); GIFImageReader gifReader = (GIFImageReader) readerSpi.createReaderInstance(); gifReader.setInput(in); int num = gifReader.getNumImages(true); // 要取的帧数要小于总帧数 if (num > frame) { ImageWriterSpi writerSpi = new PNGImageWriterSpi(); PNGImageWriter writer = (PNGImageWriter) writerSpi.createWriterInstance(); for (int i = 0; i < num; i++) { if (i == frame) { File newfile = new File(target); out = new FileImageOutputStream(newfile); writer.setOutput(out); // 读取读取帧的图片 writer.write(gifReader.read(i)); return; } } } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } public static List<String> getGifOneFrame(String src) throws IOException { FileImageInputStream in = null; FileImageOutputStream out = null; try { in = new FileImageInputStream(new File(src)); ImageReaderSpi readerSpi = new GIFImageReaderSpi(); GIFImageReader gifReader = (GIFImageReader) readerSpi.createReaderInstance(); gifReader.setInput(in); int num = gifReader.getNumImages(true); // 要取的帧数要小于总帧数 ImageWriterSpi writerSpi = new PNGImageWriterSpi(); PNGImageWriter writer = (PNGImageWriter) writerSpi.createWriterInstance(); String prefix = src.substring(0, src.lastIndexOf(".")); List<String> paths = new ArrayList<>(); for (int i = 0; i < num; i++) { File newfile = new File(prefix + "\\" + num + "crop-" + i + ".png"); newfile.getParentFile().mkdir(); paths.add(newfile.getPath()); out = new FileImageOutputStream(newfile); writer.setOutput(out); // 读取读取帧的图片 writer.write(gifReader.read(i)); } return paths; } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } public static List<byte[]> getPngBytesListFromGif(byte[] gifBytes) throws IOException { ImageReaderSpi readerSpi = new GIFImageReaderSpi(); GIFImageReader gifReader = (GIFImageReader) readerSpi.createReaderInstance(); gifReader.setInput(new MemoryCacheImageInputStream(new ByteArrayInputStream(gifBytes))); int num = gifReader.getNumImages(true); // 要取的帧数要小于总帧数 ImageWriterSpi writerSpi = new PNGImageWriterSpi(); PNGImageWriter writer = (PNGImageWriter) writerSpi.createWriterInstance(); List<byte[]> jpgList = new ArrayList<>(num); for (int i = 0; i < num; i++) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); writer.setOutput(new MemoryCacheImageOutputStream(byteArrayOutputStream)); // 读取读取帧的图片 writer.write(gifReader.read(i)); jpgList.add(byteArrayOutputStream.toByteArray()); } return jpgList; } }
package walnoot.dodgegame; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.math.Interpolation; import com.badlogic.gdx.math.MathUtils; public class SoundManager{ // private static final String[] musicPaths = {"Comparsa.mp3", "CumbiaNoFrillsFaster.mp3", "No Frills Salsa.mp3", // "Notanico Merengue.mp3", "Peppy Pepe.mp3"}; private static final String MENU_SONG_NAME = "Slow Ska Game Loop.ogg"; private static final String GAME_SONG_NAME = "Funk Game Loop.ogg"; private static final String[] grabSoundPaths = {"register.mp3"}; public static final String PREF_SOUND_KEY = "SoundVolume", PREF_MUSIC_KEY = "musicVolume"; private static final float VOLUME_THRESHOLD = 0.05f; private Music menuSong, gameSong; // private int songIndex; private FileHandle musicFolder, soundFolder; // private boolean soundOn; private Sound[] grabSounds = new Sound[grabSoundPaths.length]; private Sound clickSound; private boolean loaded; private float soundVolume, musicVolume; private float transistion = 0f; // private boolean disposed; public void init(){ musicFolder = Gdx.files.internal("music/"); soundFolder = Gdx.files.internal("sounds/"); // songIndex = MathUtils.random(musicPaths.length - 1); // currentSong = Gdx.audio.newMusic(musicFolder.child(musicPaths[songIndex])); // menuSong = Gdx.audio.newMusic(musicFolder.child("Slow Ska Game Loop.ogg")); // currentSong = Gdx.audio.newMusic(musicFolder.child("Funk Game Loop.ogg")); soundVolume = DodgeGame.PREFERENCES.getFloat(PREF_SOUND_KEY, 1f); musicVolume = DodgeGame.PREFERENCES.getFloat(PREF_MUSIC_KEY, 1f); // if(musicVolume > VOLUME_THRESHOLD){ // menuSong.play(); // menuSong.setLooping(true); // menuSong.setVolume(soundVolume); // } for(int i = 0; i < grabSounds.length; i++){ grabSounds[i] = Gdx.audio.newSound(soundFolder.child(grabSoundPaths[i])); } clickSound = Gdx.audio.newSound(soundFolder.child("click.wav")); loaded = true; } public void update(){ if(musicVolume > VOLUME_THRESHOLD){ if(DodgeGame.state.playsGameMusic()){ if(gameSong == null){ gameSong = Gdx.audio.newMusic(musicFolder.child(GAME_SONG_NAME)); gameSong.setVolume(transistion * musicVolume); gameSong.setLooping(true); gameSong.play(); } transistion += DodgeGame.SECONDS_PER_UPDATE; if(transistion > 1f){ transistion = 1f; if(menuSong != null){ menuSong.dispose(); menuSong = null; } }else{ menuSong.setVolume(Interpolation.sine.apply(0f, musicVolume, 1f - transistion)); gameSong.setVolume(Interpolation.sine.apply(0f, musicVolume, transistion)); } }else{ if(menuSong == null){ menuSong = Gdx.audio.newMusic(musicFolder.child(MENU_SONG_NAME)); menuSong.setVolume((1f - transistion) * musicVolume); menuSong.setLooping(true); menuSong.play(); } transistion -= DodgeGame.SECONDS_PER_UPDATE; if(transistion < 0f){ transistion = 0f; if(gameSong != null){ gameSong.dispose(); gameSong = null; } }else{ menuSong.setVolume(Interpolation.sine.apply(0f, musicVolume, 1f - transistion)); gameSong.setVolume(Interpolation.sine.apply(0f, musicVolume, transistion)); } } } } public void playRandomGrabSound(){ if(soundVolume > VOLUME_THRESHOLD) grabSounds[MathUtils.random(0, grabSounds.length - 1)].play(soundVolume); } public void playClickSound(){ if(soundVolume > VOLUME_THRESHOLD) clickSound.play(soundVolume); } public void setSoundVolume(float volume){ this.soundVolume = volume; if(volume < VOLUME_THRESHOLD) this.soundVolume = 0f; DodgeGame.PREFERENCES.putFloat(PREF_SOUND_KEY, this.soundVolume); } public void setMusicVolume(float volume){ this.musicVolume = volume; if(volume < VOLUME_THRESHOLD){ this.musicVolume = 0f; if(menuSong != null){ menuSong.dispose(); menuSong = null; } }else{ if(menuSong == null){ menuSong = Gdx.audio.newMusic(musicFolder.child(MENU_SONG_NAME)); menuSong.setLooping(true); menuSong.play(); } menuSong.setVolume(musicVolume); } DodgeGame.PREFERENCES.putFloat(PREF_MUSIC_KEY, this.musicVolume); } public float getSoundVolume(){ return soundVolume; } public float getMusicVolume(){ return musicVolume; } public boolean isLoaded(){ return loaded; } public void dispose(){ if(menuSong != null) menuSong.dispose(); if(gameSong != null) gameSong.dispose(); } }
package dev.nowalk.services; import java.util.List; import dev.nowalk.models.Account; import dev.nowalk.models.User; public interface UserServices { //the services associated with users //we have our basic CRUD operations here as a good practice so each layer can communicate directly above or below it //we dont want any skipping of layers public User getUser(int id); public List<User> getAllUsers(); public User addUser(User u); public User updateUser(User change); public User deleteUser(int id); //Here we can create and delete accounts from each user //I don't want to be able to make a random account that could possibly not be linked to a user, so the user services will have //add account/delete account/ money transfer methods that will call the Account services layer //public Account addAccountToUser(Account a); public Account deleteAccountFromUser(int id, int userId); public Account withdrawFunds(int id, int userId, double amount); public Account addFunds(int id, int userId, double amount); public Account transferFunds(int takeId, int putId, int userId, double amount); public List<Account> getAllAccounts(); public Account getAccountById(int id); public Account getAccountFromUser(int id ,int userId); public List<Account> getAllAccountsByUserId(int userId); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package hdfcraft.minecraft; import java.awt.Point; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import org.jnbt.CompoundTag; import org.jnbt.Tag; import static hdfcraft.minecraft.Constants.*; /** * An "MCRegion" chunk. * * @author pepijn */ public final class ChunkImpl extends AbstractNBTItem implements Chunk { public ChunkImpl(int xPos, int zPos, int maxHeight) { super(new CompoundTag(TAG_LEVEL, new HashMap<String, Tag>())); this.xPos = xPos; this.zPos = zPos; this.maxHeight = maxHeight; blocks = new byte[256 * maxHeight]; data = new byte[128 * maxHeight]; skyLight = new byte[128 * maxHeight]; blockLight = new byte[128 * maxHeight]; heightMap = new byte[256]; entities = new ArrayList<Entity>(); tileEntities = new ArrayList<TileEntity>(); readOnly = false; } public ChunkImpl(CompoundTag tag, int maxHeight) { this(tag, maxHeight, false); } public ChunkImpl(CompoundTag tag, int maxHeight, boolean readOnly) { super((CompoundTag) tag.getTag(TAG_LEVEL)); this.maxHeight = maxHeight; this.readOnly = readOnly; blocks = getByteArray(TAG_BLOCKS); data = getByteArray(TAG_DATA); skyLight = getByteArray(TAG_SKY_LIGHT); blockLight = getByteArray(TAG_BLOCK_LIGHT); heightMap = getByteArray(TAG_HEIGHT_MAP); List<Tag> entityTags = getList(TAG_ENTITIES); entities = new ArrayList<Entity>(entityTags.size()); for (Tag entityTag: entityTags) { entities.add(Entity.fromNBT(entityTag)); } List<Tag> tileEntityTags = getList(TAG_TILE_ENTITIES); tileEntities = new ArrayList<TileEntity>(tileEntityTags.size()); for (Tag tileEntityTag: tileEntityTags) { tileEntities.add(TileEntity.fromNBT(tileEntityTag)); } // TODO: last update is ignored, is that correct? xPos = getInt(TAG_X_POS); zPos = getInt(TAG_Z_POS); terrainPopulated = getBoolean(TAG_TERRAIN_POPULATED); } @Override public Tag toNBT() { setByteArray(TAG_BLOCKS, blocks); setByteArray(TAG_DATA, data); setByteArray(TAG_SKY_LIGHT, skyLight); setByteArray(TAG_BLOCK_LIGHT, blockLight); setByteArray(TAG_HEIGHT_MAP, heightMap); List<Tag> entityTags = new ArrayList<Tag>(entities.size()); for (Entity entity: entities) { entityTags.add(entity.toNBT()); } setList(TAG_ENTITIES, CompoundTag.class, entityTags); List<Tag> tileEntityTags = new ArrayList<Tag>(entities.size()); for (TileEntity tileEntity: tileEntities) { tileEntityTags.add(tileEntity.toNBT()); } setList(TAG_TILE_ENTITIES, CompoundTag.class, tileEntityTags); setLong(TAG_LAST_UPDATE, System.currentTimeMillis()); setInt(TAG_X_POS, xPos); setInt(TAG_Z_POS, zPos); setBoolean(TAG_TERRAIN_POPULATED, terrainPopulated); return new CompoundTag("", Collections.singletonMap("", super.toNBT())); } @Override public int getMaxHeight() { return maxHeight; } @Override public int getxPos() { return xPos; } @Override public int getzPos() { return zPos; } @Override public Point getCoords() { return new Point(xPos, zPos); } @Override public int getBlockType(int x, int y, int z) { return blocks[blockOffset(x, y, z)] & 0xFF; } @Override public void setBlockType(int x, int y, int z, int blockType) { if (readOnly) { return; } blocks[blockOffset(x, y, z)] = (byte) blockType; } @Override public int getDataValue(int x, int y, int z) { return getDataByte(data, x, y, z); } @Override public void setDataValue(int x, int y, int z, int dataValue) { if (readOnly) { return; } setDataByte(data, x, y, z, dataValue); } @Override public int getSkyLightLevel(int x, int y, int z) { return getDataByte(skyLight, x, y, z); } @Override public void setSkyLightLevel(int x, int y, int z, int skyLightLevel) { if (readOnly) { return; } setDataByte(skyLight, x, y, z, skyLightLevel); } @Override public int getBlockLightLevel(int x, int y, int z) { return getDataByte(blockLight, x, y, z); } @Override public void setBlockLightLevel(int x, int y, int z, int blockLightLevel) { if (readOnly) { return; } setDataByte(blockLight, x, y, z, blockLightLevel); } @Override public boolean isBiomesAvailable() { throw new UnsupportedOperationException("Not supported"); } @Override public int getBiome(int x, int z) { throw new UnsupportedOperationException("Not supported"); } @Override public void setBiome(int x, int z, int biome) { throw new UnsupportedOperationException("Not supported"); } @Override public int getHeight(int x, int z) { return heightMap[x + z * 16] & 0xFF; } @Override public void setHeight(int x, int z, int height) { if (readOnly) { return; } heightMap[x + z * 16] = (byte) (Math.min(height, 255)); } @Override public boolean isTerrainPopulated() { return terrainPopulated; } @Override public void setTerrainPopulated(boolean terrainPopulated) { if (readOnly) { return; } this.terrainPopulated = terrainPopulated; } @Override public List<Entity> getEntities() { return entities; } @Override public List<TileEntity> getTileEntities() { return tileEntities; } @Override public Material getMaterial(int x, int y, int z) { return Material.get(getBlockType(x, y, z), getDataValue(x, y, z)); } @Override public void setMaterial(int x, int y, int z, Material material) { setBlockType(x, y, z, material.getBlockType()); setDataValue(x, y, z, material.getData()); } @Override public boolean isReadOnly() { return readOnly; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ChunkImpl other = (ChunkImpl) obj; if (this.xPos != other.xPos) { return false; } if (this.zPos != other.zPos) { return false; } return true; } @Override public int hashCode() { int hash = 7; hash = 67 * hash + this.xPos; hash = 67 * hash + this.zPos; return hash; } /** * @throws UnsupportedOperationException */ @Override public ChunkImpl clone() { throw new UnsupportedOperationException("ChunkImlp.clone() not supported"); } private int getDataByte(byte[] array, int x, int y, int z) { byte dataByte = array[blockOffset(x, y, z) / 2]; if (blockOffset(x, y, z) % 2 == 0) { // Even byte -> least significant bits return dataByte & 0x0F; } else { // Odd byte -> most significant bits return (dataByte & 0xF0) >> 4; } } private void setDataByte(byte[] array, int x, int y, int z, int dataValue) { int blockOffset = blockOffset(x, y, z); int offset = blockOffset / 2; byte dataByte = array[offset]; if (blockOffset % 2 == 0) { // Even byte -> least significant bits dataByte &= 0xF0; dataByte |= (dataValue & 0x0F); } else { // Odd byte -> most significant bits dataByte &= 0x0F; dataByte |= ((dataValue & 0x0F) << 4); } array[offset] = dataByte; } private int blockOffset(int x, int y, int z) { return y + (z + x * 16) * maxHeight; } public final boolean readOnly; final byte[] blocks; final byte[] data; final byte[] skyLight; final byte[] blockLight; final byte[] heightMap; final int xPos, zPos; boolean terrainPopulated; final List<Entity> entities; final List<TileEntity> tileEntities; final int maxHeight; private static final long serialVersionUID = 1L; }
package Pro04.ReConstructBinaryTree; import java.util.Arrays; public class Solution { // 递归,先序的第一个数字是根节点,由此在中序中区分出左右子树,再在左右子树中重复该步骤 public TreeNodes reConstructBinaryTree(int[] pre, int[] in) { if (pre.length == 0 || in.length == 0) { return null; } TreeNodes root = new TreeNodes(pre[0]); for (int i = 0; i < in.length; i++) { if (pre[0] == in[i]) { root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i)); root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length)); } } return root; } public TreeNodes reConstructBinaryTree1(int[] pre, int[] in) { TreeNodes root = new TreeNodes(pre[0]); int inRootIndex = 0; for (int i = 0; i < in.length; i++) { if (in[i] == root.val) { inRootIndex = i; break; } } int[] leftin=Arrays.copyOfRange(in,0,inRootIndex); //取的是index为0到inRootIndex-1的数组 int[] rightin=Arrays.copyOfRange(in,inRootIndex+1,in.length); int[] leftpre=Arrays.copyOfRange(pre,1,1+inRootIndex); int[] rightpre=Arrays.copyOfRange(pre,inRootIndex+1,pre.length); root.left=reConstructBinaryTree(leftpre,leftin); root.right=reConstructBinaryTree(rightpre,rightin); return root; } // 中序打印 public void print(TreeNodes treeNodes) { if (treeNodes != null) { print(treeNodes.left); System.out.println(treeNodes.val); print(treeNodes.right); } } public static void main(String[] args) { int[] pre = {1, 2, 4, 7, 3, 5, 6, 8}; int[] in = {4, 7, 2, 1, 5, 3, 8, 6}; Solution solution = new Solution(); TreeNodes root = new TreeNodes(0); root = solution.reConstructBinaryTree1(pre, in); //root保存重建的二叉树 solution.print(root); } }