text
stringlengths
10
2.72M
package com.lagou.edu; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; // 声明本项⽬是⼀个Eureka服务 @EnableEurekaServer @SpringBootApplication public class Lagou02CloudEurekaServer8761Application { public static void main(String[] args) { SpringApplication.run(Lagou02CloudEurekaServer8761Application.class, args); } }
package com.lasform.core.business.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.lasform.core.business.service.implementation.ThirdPartyLocationServiceImp; import com.lasform.core.model.dto.DirectionRequest; @RestController @RequestMapping("/api/thirdParty") // @EnableWebSecurity // @CrossOrigin(origins = "${lasform.application.web-face-url}") public class ThirdPartyController { @Autowired ThirdPartyLocationServiceImp thirdPartyService; @GetMapping(value = "/script", produces = "text/javascript; charset=utf-8") private String script() { return thirdPartyService.getBaseApi(); } @PostMapping(value = "/direction", produces = "application/json") private String direction(@RequestBody DirectionRequest directionRequest) { return thirdPartyService.getDirection(directionRequest); } }
package model_practicaltest02.eim.systems.cs.pub.ro.model_practicaltest02; public interface Constants { public final static boolean DEBUG = true; public final static String TAG = "MODEL_PracticalTest02"; public final static String API_SERVER = "http://api.wunderground.com/api/bdfed6464b1c8ba1/conditions/q/"; }
import java.util.Scanner; //못푼문제 ★ public class Q11729 { public static StringBuffer br; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); br = new StringBuffer(); int n = sc.nextInt(); System.out.println((int)(Math.pow(2, n)-1)); hanoi(n,1,3,2); System.out.println(br.toString()); } public static void hanoi(int n,int from, int to, int via) { if(n==1) { move(1,from,to); return; } hanoi(n-1,from,via,to); move(n-1,from,to); hanoi(n-1,via,to,from); } public static void move(int n,int from,int to) { br.append(from+" "+to); br.append("\n"); } }
package com.github.dockerjava.api.model.metric; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class CpuStats { @JsonProperty("cpu_usage") private CpuUsage cpuUsage; @JsonProperty("throlling_data") private ThrottlingData throttlingData; public CpuUsage getCpuUsage() { return cpuUsage; } public ThrottlingData getThrottlingData() { return throttlingData; } @Override public String toString() { return "CpuStats [cpuUsage=" + cpuUsage + ", throttlingData=" + throttlingData + "]"; } }
package com.javawebtutor.Entities; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.Table; import javax.persistence.TableGenerator; @TableGenerator(name = "racunmal", table = "idgen", pkColumnName = "genname", valueColumnName = "genval", allocationSize = 100) @Entity @Table(name="racunmaloprodaja") public class RacunMaloprodaja { @Id @GeneratedValue(strategy =GenerationType.TABLE, generator = "racunmal") @Column(name="idracunmaloprodaja") private int id; @Column(name="iznos") private double iznos; @Column(name="nacinplacanja") private String nacinPlacanja; @Column(name="dostava") private String dostava; @Column(name="datum") private Date datum; @OneToOne(cascade=CascadeType.ALL) private Dostava iddostava; public RacunMaloprodaja(){ } public RacunMaloprodaja(double iznos, String nacinpl, String dost, Date d) { this.setIznos(iznos); this.setNacinPlacanja(nacinpl); this.setDostava(dost); this.setDatum(d); } public int getId() { return this.id; } public void setId(int idd) { this.id=idd; } public double getIznos() { return this.iznos; } public void setIznos(double iznos) { this.iznos=iznos; } public String getNacinPlacanja() { return this.nacinPlacanja; } public void setNacinPlacanja(String nacin) { this.nacinPlacanja=nacin; } public void setDostava(String dost) { this.dostava=dost; } public String getDostava() { return this.dostava; } public Date getDatum() { return this.datum; } public void setDatum(Date d) { this.datum=d; } public Dostava getIdDostava() { return this.iddostava; } public void setIdDostava(Dostava dd) { this.iddostava=dd; } }
package edu.nmsu.Home.LocalSolver; import edu.nmsu.problem.Parameters; import org.jacop.constraints.XltC; import org.jacop.core.IntVar; import org.jacop.core.Store; import org.jacop.core.Var; import org.jacop.floats.core.FloatVar; import org.jacop.search.*; /** * Created by nandofioretto on 11/1/16. */ public abstract class CPSolver implements Solver { /** Contains all decision variables used within a specific instance. */ protected IntVar[] vars; /** It specifies the cost function, null if no cost is used. */ protected IntVar costFunction; protected int bestCost = Integer.MAX_VALUE; /** It specifies the constraint store. */ public Store store; /** It specifies the search procedure used by a given instance. */ protected Search<IntVar> search; protected long timeoutMs = 300000; /** The solving time horizon */ protected final int HORIZON = Parameters.getHorizon(); // 15 minute intervals over 24 hours /** It specifies the scale factors to round double numbers to integers. */ protected final int kiloWattToWatt = 10; // used for power protected final int centsToDollars = 100; // used for price protected final int deltaScale = 10; // used for deltas protected double scaleFactor = kiloWattToWatt*centsToDollars; protected int scaleAndRoundPower(double n) { return (int)(n * kiloWattToWatt); } protected int scaleAndRoundPrice(double n) { return (int)(n * centsToDollars); } protected int scaleAndRoundDelta(double n) { return (int)(n * deltaScale); } protected int getKiloWattToWatt() { return kiloWattToWatt; } protected int getCentsToDollars() { return centsToDollars; } public void setTimeoutMs(long timeoutMs) { this.timeoutMs = timeoutMs; } /** * It creates an array of int variables * @param array The array of variables * @param store The constraint store * @param min min value of the domain * @param max max value of the domain */ protected void createIntVarArray(IntVar[] array, Store store, int min, int max) { for (int i = 0; i < array.length; i++) array[i] = new IntVar(store, min, max); } /** * It creates an array of int variables * @param array The array of variables * @param store The constraint store * @param name The variable name prefix (will be followed by "_i" for i=0...array.length-1 * @param min min value of the domain * @param max max value of the domain */ protected void createIntVarArray(IntVar[] array, Store store, String name, int min, int max) { for (int i = 0; i < array.length; i++) array[i] = new IntVar(store, name + "_[" + i + "]", min, max); } protected void createFloatVarArray(FloatVar[] array, Store store, String name, double min, double max) { for (int i = 0; i < array.length; i++) array[i] = new FloatVar(store, name + "_[" + i + "]", min, max); } /** * It creates a 2D array of int variables * @param array The array of variables * @param store The constraint store * @param min min value of the domain * @param max max value of the domain */ protected void createIntVar2DArray(IntVar[][] array, Store store, int min, int max) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = new IntVar(store, min, max); } } } protected void createFloatVar2DArray(FloatVar[][] array, Store store, float min, float max) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = new FloatVar(store, min, max); } } } /** * It creates a 2D array of int variables * @param array The array of variables * @param store The constraint store * @param name The variable name prefix (will be followed by "_i" for i=0...array.length-1 * @param min min value of the domain * @param max max value of the domain */ protected void createIntVar2DArray(IntVar[][] array, Store store, String name, int min, int max) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = new IntVar(store, name + "_[" + i + "," + j + "]", min, max); } } } protected void createFloatVar2DArray(FloatVar[][] array, Store store, String name, double min, double max) { for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { array[i][j] = new FloatVar(store, name + "_[" + i + "," + j + "]", min, max); } } } /** * It specifies simple search method based on input order and lexigraphical * ordering of values. It optimizes the solution by minimizing the cost function. * * @return true if there is a solution, false otherwise. */ protected boolean searchOptimal() { long T1, T2; T1 = System.currentTimeMillis(); SelectChoicePoint<IntVar> select = new SimpleSelect<>(vars, null, new IndomainMin<>()); search.setTimeOut(timeoutMs / 1000); boolean result = search.labeling(store, select, costFunction); T2 = System.currentTimeMillis(); System.out.println("\n\t*** Execution time = " + (T2 - T1) + " ms"); return result; } protected boolean searchSatisfaction() { SelectChoicePoint<IntVar> select = new SimpleSelect<>(vars, null, new IndomainMax<>()); search = new DepthFirstSearch<>(); //search.setTimeOut(timeoutMs / 1000); boolean result = search.labeling(store, select); return result; } /** * It specifies simple search method based on smallest domain variable order * and lexigraphical ordering of values. * @return true if there is a solution, false otherwise. */ protected boolean searchSmallestDomain() { SelectChoicePoint<IntVar> select = new SimpleSelect<>(vars, new SmallestDomain<>(), new IndomainMin<>()); search = new DepthFirstSearch<>(); search.setTimeOut(timeoutMs / 1000); boolean result = search.labeling(store, select, costFunction); return result; } /** * It specifies simple search method based on weighted degree variable order * and lexigraphical ordering of values. This search method is rather general * any problem good fit. It can be a good first trial to see if the model is * correct. * * @return true if there is a solution, false otherwise. */ protected boolean searchWeightedDegree() { long T1, T2; T1 = System.currentTimeMillis(); SelectChoicePoint<IntVar> select = new SimpleSelect<>(vars, new WeightedDegree<>(), new SmallestDomain<>(), new IndomainMin<>()); search = new DepthFirstSearch<>(); search.setTimeOut(timeoutMs / 1000); boolean result = search.labeling(store, select, costFunction); T2 = System.currentTimeMillis(); System.out.println("\n\t*** Execution time = " + (T2 - T1) + " ms"); return result; } /** * It specifies simple search method based variable order which * takes into account the number of constraints attached to a variable * and lexicographical ordering of values. * * @return true if there is a solution, false otherwise. */ protected boolean searchMostConstrainedStatic() { search = new DepthFirstSearch<>(); search.setTimeOut(timeoutMs / 1000); SelectChoicePoint<IntVar> select = new SimpleSelect<>(vars, new MostConstrainedStatic<>(), new IndomainMin<>()); boolean result = search.labeling(store, select, costFunction); return result; } /** * It searches for solution using Limited Discrepancy Search. * @param noDiscrepancy maximal number of discrepancies * @return true if the solution was found, false otherwise. */ protected boolean searchLDS(int noDiscrepancy) { search = new DepthFirstSearch<>(); search.setTimeOut(timeoutMs / 1000); boolean result; // false by default SelectChoicePoint<IntVar> select = new SimpleSelect<>(vars, new SmallestDomain<>(), new IndomainMiddle<>()); LDS<IntVar> lds = new LDS<>(noDiscrepancy); if (search.getExitChildListener() == null) search.setExitChildListener(lds); else search.getExitChildListener().setChildrenListeners(lds); // Execution time measurement long begin = System.currentTimeMillis(); result = search.labeling(store, select, costFunction); // Execution time measurement long end = System.currentTimeMillis(); System.out.println("Number of milliseconds " + (end - begin)); return result; } /** * It conducts the search with restarts from which the no-goods are derived. * Every search contributes with new no-goods which are kept so eventually * the search is complete (although can be very expensive to maintain explicitly * all no-goods found during search). * @return true if there is a solution, false otherwise. */ protected boolean searchWithRestarts(int nodesOut) { // Input Order tie breaking boolean result = false; boolean timeout = true; int nodes = 0; int decisions = 0; int backtracks = 0; int wrongDecisions = 0; search = new DepthFirstSearch<>(); //TODO: fix superfast timeout from this search type. (we want a better solution if we can manage it) //look into possibly using this: (was already here commented when I started refactoring stuff) //uncommenting it does nothing.. will have to try something else. //search.setTimeOut(LPP.getSchedulerTimeoutMs() / 1000); NoGoodsCollector<IntVar> collector = new NoGoodsCollector<>(); search.setExitChildListener(collector); search.setTimeOutListener(collector); search.setExitListener(collector); SelectChoicePoint<IntVar> select = new SimpleSelect<>(vars, new SmallestDomain<>(), new IndomainSimpleRandom<>()); //System.out.println("***********************************\n\n\nLPP.getSchedulerTimeoutMs():"+LPP.getSchedulerTimeoutMs()+"\n\n\n***********************"); //it appears that the timeout is being set to the "NoGoodsCollecter<IntVar> collector" variable. //gets set to false if collector timeOut is hit..? kinda strange, will have to investigate further //ALWAYS gets set to false... while (timeout) { // search.setPrintInfo(false); search.setNodesOut(nodesOut); result = search.labeling(store, select, costFunction); timeout &= collector.timeOut; nodes += search.getNodes(); decisions += search.getDecisions(); wrongDecisions += search.getWrongDecisions(); backtracks += search.getBacktracks(); search = new DepthFirstSearch<>(); collector = new NoGoodsCollector<>(); search.setExitChildListener(collector); search.setTimeOutListener(collector); search.setExitListener(collector); //System.out.println("++++++" + timeout); } return result; } protected boolean BranchAndBound() { search = new DepthFirstSearch<>(); search.setSolutionListener(new CostListener<>()); store.setLevel(store.level + 1); //search.setTimeOut(LPP.getSchedulerTimeoutMs() / 1000); SelectChoicePoint<IntVar> select = new SimpleSelect<>(vars, new SmallestDomain<>(), new IndomainSimpleRandom<>()); //search.labeling(store, select, costFunction); boolean result = true; boolean optimalResult = false; while (result) { result = search.labeling(store, select); store.impose(new XltC(costFunction, bestCost)); optimalResult = optimalResult || result; } store.removeLevel(store.level); store.setLevel(store.level-1); return result; } public class CostListener<T extends Var> extends SimpleSolutionListener<T> { public boolean executeAfterSolution(Search<T> search, SelectChoicePoint<T> select) { boolean returnCode = super.executeAfterSolution(search, select); bestCost = costFunction.value(); return returnCode; } } }
package net.tecgurus.controller.dto; import javax.validation.constraints.Email; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.Positive; public class UsuarioDto { @NotEmpty(message = "Nombre no pude ser vacio") private String name; @Email(message = "Correo no valido") private String email; private String direccion; @Positive(message = "Debe ser un numero positivo") private Integer edad; public UsuarioDto() { super(); } public UsuarioDto(String name, String email, String direccion, Integer edad) { super(); this.name = name; this.email = email; this.direccion = direccion; this.edad = edad; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } public Integer getEdad() { return edad; } public void setEdad(Integer edad) { this.edad = edad; } }
package com.mtl.demo.serviceA.feign; import com.mtl.hulk.annotation.MTLDTBroker; import com.mtl.hulk.context.BusinessActivityContext; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @FeignClient("hulkServiceB") public interface HulkClientB { @MTLDTBroker @RequestMapping("/hulkServiceB") String getHulkServiceB(@RequestParam("a") int a, @RequestParam("b") int b); @RequestMapping(value = "/hulkServiceBConfirm", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) boolean confirmMysqlSaveAssetBCard(@RequestBody BusinessActivityContext ctx); @RequestMapping(value = "/hulkServiceBCancel", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) boolean cancelMysqlSaveAssetBCard(@RequestBody BusinessActivityContext ctx); }
package BotServer.server.service; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.TypeReference; import org.apache.commons.lang3.StringUtils; import java.io.FileInputStream; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; /** * ************************************************************** * <p> * Desc: * User: jianguangluo * Date: 2018-12-27 * Time: 16:50 * <p> * ************************************************************** */ public class BotSettingsService { private static volatile JSONObject config = null; private static volatile List<JSONObject> webUsers = null; public static JSONObject getBotSetting() { return getSystemConfig(); } /** * WebUser配置文件 * @return */ public static List<JSONObject> getWebUsers() { if (webUsers == null) { synchronized (BotSettingsService.class) { if (webUsers == null) { try { webUsers = new ArrayList<>(); String fileName ="./web_users.json";//获取文件路径 FileInputStream input = new FileInputStream(fileName); int len = input.available(); byte[] bytes = new byte[len]; input.read(bytes, 0, len); String s = new String(bytes); if (StringUtils.isNotEmpty(s)) { JSONObject res = JSONObject.parseObject(s); if (res != null) { List<JSONObject> array = res.getObject("list",new TypeReference<List<JSONObject>>(){}); if (array != null) { array.forEach(o -> { webUsers.add(o); }); } } System.out.println("WebUserConfig:" + webUsers == null ? "" : webUsers); } } catch (Exception ex) { ex.printStackTrace(); } } } } return webUsers; } /** * 读WebUser配置文中的用户红金额 * @param openId * @param amount * @return */ public static BigDecimal getRedPackAmount(String openId, BigDecimal amount) { for (JSONObject user : getWebUsers()) { if (user.getString("openId").equals(openId)) { return user.getBigDecimal("amount"); } } return amount; } private static JSONObject getSystemConfig() { if (config == null) { synchronized (BotSettingsService.class) { if (config == null) { try { String fileName ="./setting.json";//获取文件路径 FileInputStream input = new FileInputStream(fileName); int len = input.available(); byte[] bytes = new byte[len]; input.read(bytes, 0, len); String s = new String(bytes); if (StringUtils.isNotEmpty(s)) { config = JSONObject.parseObject(s); System.out.println("Config:" + config == null ? "" : config.toJSONString()); } } catch (Exception ex) { ex.printStackTrace(); } } } } return config; } }
package application.portfolios; import application.orders.Order; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.List; @Entity public class Portfolio { @Id @GeneratedValue private long id; @NotNull private String name; private String description; @OneToMany(mappedBy = "portfolio", cascade = CascadeType.REMOVE) private List<Order> orders; private Portfolio() { } public Portfolio(String name, String description) { this.name = name; this.description = description; } public long getId() { return id; } public String getName() { return name; } public String getDescription() { return description; } public void update(Portfolio portfolio) { if (portfolio.getName() != null) this.name = portfolio.name; if (portfolio.getDescription() != null) this.description = portfolio.description; } }
package application; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import model.dao.DaoFactory; import model.dao.DepartmentDao; import model.entities.Department; public class Program2 { public static void main(String[] args) { Scanner sc = new Scanner (System.in); DepartmentDao departmentDao = DaoFactory.createDepartmentDao(); System.out.println("---Teste 1 : FindById---"); Department department = departmentDao.findById(3); System.out.println(department); /* System.out.println("---Teste 2 : Insert---"); Department newDepartment = new Department(null, "Drinks"); departmentDao.insert(newDepartment); System.out.println("New Department Inserted! \n"+"New ID: " + newDepartment.getId() + "\n" + "New Name: " + newDepartment.getName()); */ System.out.println("---Teste 3 : Update---"); department = departmentDao.findById(6); department.setName("Stellar Ships"); departmentDao.update(department); System.out.println("Updated"); System.out.println("---Teste 4 DeleteById---"); // department = departmentDao.findById(7); departmentDao.deleteById(7); System.out.println("Deleted"); System.out.println("---Teste 5 findAll---"); List<Department> depList = new ArrayList<>(); depList = departmentDao.findAll(); depList.forEach(System.out::println); sc.close(); } }
public class charu { public static void main (String args[]) { int a [] = {28, 12, 89, 73, 65, 18, 96, 50, 8, 36}; int i,j; for(i=1;i<a.length;i++) { int temp=a[i]; for(j=i-1;j>=0;j--) { if (temp > a[j]) { break; }else{ a[j+1] = a[j]; } } a[j+1]=temp; } for (int c=0;c<a.length;c++) { System.out.print(a[c]+","); } } }
package controller; import dao.NEXEntityDAO; import model.Students; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @WebServlet("/EditDB") public class EditDB extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { NEXEntityDAO<Students> nexEntityDAO2 = new NEXEntityDAO<>(Students.class); String date = req.getParameter("birthdayDate"); Date date1 = null; try { date1 = new SimpleDateFormat("yyyy-MM-dd").parse(date); } catch (ParseException e) { e.printStackTrace(); } String age = req.getParameter("age"); int age1 = Integer.parseInt(age); Students editing = new Students(req.getParameter("firstName"), req.getParameter("lastName"), age1 , date1, req.getParameter("faculty")); nexEntityDAO2.update(editing); resp.sendRedirect("/testMain.html"); } }
/** * */ package com.DB.dao.SQLServer; import java.sql.PreparedStatement; import java.sql.SQLException; import com.DB.dao.LoginDao; import com.DB.model.Login; /** * @author Bruce GONG * */ public class LoginDaoImpl implements LoginDao { private DBHelper dbhelper = null; public LoginDaoImpl(Login login) { super(); // TODO Auto-generated constructor stub try { dbhelper = new DBHelper(login); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* (non-Javadoc) * @see com.DB.dao.LoginDao#createLogin(com.DB.model.Login) */ @Override public boolean createLogin(Login login) { // TODO Auto-generated method stub String sql = "CREATE LOGIN "+login.getLoginName()+" WITH PASSWORD = '"+login.getLoginPwd()+"', " + "DEFAULT_DATABASE = M2_DB , DEFAULT_LANGUAGE = us_english, CHECK_POLICY= OFF; \n"; try { dbhelper.execSQL(sql); return true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } /* (non-Javadoc) * @see com.DB.dao.LoginDao#removeLogin(com.DB.model.Login) */ @Override public boolean removeLogin(String username) { // TODO Auto-generated method stub String sql = "DROP LOGIN " + username; try { dbhelper.execSQL(sql); return true; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } } }
package pl.coderslab.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import pl.coderslab.entity.Tweet; import pl.coderslab.entity.User; import pl.coderslab.service.TweetService; import pl.coderslab.service.UserService; import pl.coderslab.validationGroups.ValidationMessage; import pl.coderslab.validationGroups.ValidationUser; import javax.servlet.http.HttpSession; import javax.validation.Valid; import javax.validation.Validator; import java.time.LocalDateTime; import java.util.List; @Controller public class HomeController { @Autowired UserService userService; @Autowired TweetService tweetService; @GetMapping("/") public String home (HttpSession httpSession) { if (httpSession.getAttribute("id") == null) { return "login"; } else { return "redirect:/home"; } } @GetMapping("/home") public String index (Model model, HttpSession httpSession) { if (httpSession.getAttribute("id") == null) { return "login"; } else { model.addAttribute("tweet", new Tweet()); Long userId = tweetService.castObjectToLong(httpSession.getAttribute("id")); User userLogged = userService.findById(userId); model.addAttribute("userLog", userLogged); return "home"; } } @PostMapping("/home") public String index(@Validated(ValidationMessage.class) @ModelAttribute Tweet tweet, BindingResult result, HttpSession httpSession) { Long userId = tweetService.castObjectToLong(httpSession.getAttribute("id")); User user = userService.findById(userId); tweet.setCreated(LocalDateTime.now()); tweet.setUser(user); if (result.hasErrors()) { return "redirect:/home"; } tweetService.save(tweet); return "redirect:/user/"+userId+"/all"; } @GetMapping("/logout") public String logout(HttpSession httpSession) { httpSession.setAttribute("id", null); return "redirect:/login"; } /////////////// MODEL //////////////////// @ModelAttribute("users") public List<User> users() { return userService.findAll(); } @ModelAttribute("alltweets") public List<Tweet> tweets() {return tweetService.findAllSorted();} }
package com.detroitlabs.comicview.model; import com.fasterxml.jackson.annotation.JsonProperty; public class firstApperedInIssue { private String apiDetailsUrl; private String id; private String name; private String issueNumber; @JsonProperty("api_detail_url") public String getApiDetailsUrl() { return apiDetailsUrl; } @JsonProperty("api_detail_url") public void setApiDetailsUrl(String apiDetailsUrl) { this.apiDetailsUrl = apiDetailsUrl; } @JsonProperty("id") public String getId() { return id; } @JsonProperty("id") public void setId(String id) { this.id = id; } @JsonProperty("name") public String getName() { return name; } @JsonProperty("name") public void setName(String name) { this.name = name; } @JsonProperty("issueNumber") public String getIssueNumber() { return issueNumber; } @JsonProperty("issueNumber") public void setIssueNumber(String issueNumber) { this.issueNumber = issueNumber; } @Override public String toString() { return "firstApperedInIssue{" + "apiDetailsUrl='" + apiDetailsUrl + '\'' + ", id='" + id + '\'' + ", name='" + name + '\'' + ", issueNumber='" + issueNumber + '\'' + '}'; } }
package my.blog.controllers; import io.micronaut.context.annotation.Property; import io.micronaut.core.type.Argument; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.HttpStatus; import io.micronaut.http.MediaType; import io.micronaut.http.client.RxStreamingHttpClient; import io.micronaut.http.client.annotation.Client; import io.micronaut.http.client.exceptions.HttpClientResponseException; import io.micronaut.security.authentication.UsernamePasswordCredentials; import io.micronaut.security.token.jwt.render.BearerAccessRefreshToken; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import my.blog.errors.CustomHttpResponseError; import my.blog.models.Post; import my.blog.repositories.MemoryStorage; import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestMethodOrder; import javax.inject.Inject; import java.util.List; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; @MicronautTest @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class PostControllerMemoryTest { private final long UNSUPPORTED_ID = 4L; @Inject @Client("/") RxStreamingHttpClient client; @Inject MemoryStorage memoryStorage; @Test @Order(1) void returnsListOfPosts() { var response = client.toBlocking().exchange(HttpRequest.GET("/posts"), Argument.listOf(Post.class)); assertEquals(HttpStatus.OK, response.getStatus()); assertNotNull(response.body()); List<Post> posts = response.body(); assertThat(posts).containsExactlyInAnyOrderElementsOf(memoryStorage.getPosts()); } @Test @Order(2) void findPostById() { var response = client.toBlocking().exchange(HttpRequest.GET("/posts/1"), Post.class); assertEquals(HttpStatus.OK, response.getStatus()); assertNotNull(response.body()); assertEquals(memoryStorage.getPosts().get(0), response.body()); } @Test @Order(3) void notFoundPostById() { try { client.toBlocking().exchange(HttpRequest.GET("/posts/" + UNSUPPORTED_ID), Argument.of(Post.class), Argument.of(CustomHttpResponseError.class)); } catch (HttpClientResponseException ex) { Optional<CustomHttpResponseError> error = ex.getResponse().getBody(CustomHttpResponseError.class); assertTrue(error.isPresent()); assertEquals(HttpStatus.NOT_FOUND.getCode(), error.get().getStatus()); assertEquals(HttpStatus.NOT_FOUND.name(), error.get().getError()); assertEquals("Not found post with id: " + UNSUPPORTED_ID, error.get().getMessage()); } } @Test @Order(4) void canUpdatePost() { var token = givenTestUserIsLoggedIn(); var changedTitle = "New title"; var changedText = "New text"; Post post1 = Post.builder().title(changedTitle).text(changedText).build(); post1.setId(1L); var updateRqst = HttpRequest.PUT("/posts/update", post1) .accept(MediaType.APPLICATION_JSON) .bearerAuth(token.getAccessToken()); HttpResponse<Post> response = client.toBlocking().exchange(updateRqst, Post.class); assertEquals(HttpStatus.OK, response.getStatus()); var updatedPost = response.body(); assertNotNull(updatedPost); assertEquals(changedTitle, updatedPost.getTitle()); assertEquals(changedText, updatedPost.getText()); } @Test @Order(5) void failureUpdatePost() { var token = givenTestUserIsLoggedIn(); try { Post unknownPost = Post.builder().build(); unknownPost.setId(UNSUPPORTED_ID); var rqst = HttpRequest.PUT("/posts/update", unknownPost) .accept(MediaType.APPLICATION_JSON) .bearerAuth(token.getAccessToken()); client.toBlocking().exchange(rqst, Argument.of(Post.class), Argument.of(CustomHttpResponseError.class)); } catch (HttpClientResponseException ex) { Optional<CustomHttpResponseError> error = ex.getResponse().getBody(CustomHttpResponseError.class); assertTrue(error.isPresent()); assertEquals(HttpStatus.NOT_ACCEPTABLE.getCode(), error.get().getStatus()); assertEquals(HttpStatus.NOT_ACCEPTABLE.name(), error.get().getError()); assertEquals("Failure update post with id: " + UNSUPPORTED_ID, error.get().getMessage()); } } @Test @Order(6) void canRemovePostById() { var token = givenTestUserIsLoggedIn(); var rqst = HttpRequest.DELETE("/posts/1") .accept(MediaType.APPLICATION_JSON) .bearerAuth(token.getAccessToken()); var responseOfDel = client.toBlocking().exchange(rqst); assertEquals(HttpStatus.OK, responseOfDel.getStatus()); var responseOfGetAll = client.toBlocking().exchange(HttpRequest.GET("/posts"), Argument.listOf(Post.class)); List<Post> posts = responseOfGetAll.body(); assertNotNull(posts); assertEquals(2, posts.size()); } @Test @Order(7) void failureRemovePost() { var token = givenTestUserIsLoggedIn(); try { var rqst = HttpRequest.DELETE("/posts/" + UNSUPPORTED_ID) .accept(MediaType.APPLICATION_JSON) .bearerAuth(token.getAccessToken()); client.toBlocking().exchange(rqst, String.class); } catch (HttpClientResponseException ex) { HttpResponse<?> response = ex.getResponse(); assertEquals(HttpStatus.NOT_ACCEPTABLE, response.getStatus()); Optional<String> message = response.getBody(String.class); assertTrue(message.isPresent()); assertEquals("Failure update post with id: " + UNSUPPORTED_ID, message.get()); } } @Test @Order(8) void canCreatePost() { var token = givenTestUserIsLoggedIn(); String createdTitle = "New title"; String createdText = "New text"; String postAuthor = "Brandon"; var newPost = Post.builder().title(createdTitle).text(createdText).author(postAuthor).build(); var rqst = HttpRequest.PUT("/posts/create", newPost) .accept(MediaType.APPLICATION_JSON) .bearerAuth(token.getAccessToken()); var response = client.toBlocking().exchange(rqst, Post.class); assertEquals(HttpStatus.OK, response.getStatus()); var createdPost = response.body(); assertNotNull(createdPost); assertEquals(createdTitle, createdPost.getTitle()); assertEquals(createdText, createdPost.getText()); assertEquals(postAuthor, createdPost.getAuthor()); } @Test @Order(9) void failCreateIfPostHasId() { var token = givenTestUserIsLoggedIn(); try { Post newFailedPost = Post.builder().build(); newFailedPost.setId(UNSUPPORTED_ID); var rqst = HttpRequest.PUT("/posts/create", newFailedPost) .accept(MediaType.APPLICATION_JSON) .bearerAuth(token.getAccessToken()); client.toBlocking().exchange(rqst, Argument.of(Post.class), Argument.of(CustomHttpResponseError.class)); } catch (HttpClientResponseException ex) { Optional<CustomHttpResponseError> error = ex.getResponse().getBody(CustomHttpResponseError.class); assertTrue(error.isPresent()); assertEquals(HttpStatus.NOT_ACCEPTABLE.getCode(), error.get().getStatus()); assertEquals(HttpStatus.NOT_ACCEPTABLE.name(), error.get().getError()); assertEquals("Identifier of new post must be 0 or null!", error.get().getMessage()); } } private BearerAccessRefreshToken givenTestUserIsLoggedIn() { var username = "blog@gmail.net"; UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, "123456"); var request = HttpRequest.POST("/login", credentials); var loginRsp = client.toBlocking().exchange(request, BearerAccessRefreshToken.class); assertEquals(HttpStatus.OK, loginRsp.getStatus()); BearerAccessRefreshToken token = loginRsp.body(); assertNotNull(token); assertEquals(username, token.getUsername()); return token; } }
package neighbourhood; import alg.np.similarity.SimilarityMap; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * An abstract base class to compute neighbourhood formations in UBCF recommenders */ public abstract class Neighbourhood { private Map<Integer,Set<Integer>> neighbourhoodMap; // stores the neighbourhood users for each user in a set /** Constructor */ public Neighbourhood() { neighbourhoodMap = new HashMap<Integer,Set<Integer>>(); } /** * Gets the neighbours for a given user * @param id - the user's ID * @returns the neighbours for id */ public Set<Integer> getNeighbours(final Integer id) { return neighbourhoodMap.get(id); } /** * Checks if two users are neighbours * @param id1 - a user's ID * @param id2 - a user's ID * @returns true if id2 is a neighbour of id1 */ public boolean isNeighbour(final Integer id1, final Integer id2) { if (neighbourhoodMap.containsKey(id1)) return neighbourhoodMap.get(id1).contains(id2); else return false; } /** * Add a user to another user's neighbourhood * @param id1 - a user's ID * @param id2 - a new neighbour's ID */ public void add(final Integer id1, final Integer id2) { Set<Integer> set = neighbourhoodMap.containsKey(id1) ? neighbourhoodMap.get(id1) : new HashSet<Integer>(); set.add(id2); neighbourhoodMap.put(id1, set); } /** * Computes neighbourhoods for all users and stores them in neighbourhood map - must be called before isNeighbour(Integer,Integer). * @param simMap - a map containing user-user similarities */ public abstract void computeNeighbourhoods(final SimilarityMap simMap); }
package com.javarush.task.task07.task0718; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Scanner; /* Проверка на упорядоченность */ public class Solution { public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(System.in); ArrayList<String> arrayList = new ArrayList<>(); for (int i = 0; i < 10; i++) { arrayList.add(scanner.nextLine()); } for (int i = 1; i < arrayList.size(); i++) { if(arrayList.get(i).length() < arrayList.get(i - 1).length()){ System.out.println(i); return; } } } }
package pkga3; public class A3 { public String doIt() { return "from A3"; } }
package gov.nih.mipav.view.renderer.J3D.surfaceview.plotterview; import gov.nih.mipav.view.*; import gov.nih.mipav.view.renderer.J3D.*; import gov.nih.mipav.view.renderer.J3D.surfaceview.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Dialog to turn bounding box of surface renderer on and off, and to change the color of the frame. */ public class JPanelSurfaceBox extends JPanelRendererJ3D { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -1435246141584042105L; //~ Instance fields ------------------------------------------------------------------------------------------------ /** Check box for turning box on and off. */ protected JCheckBox boundingCheck; /** Color button for changing color. */ protected JButton colorButton; /** Color button for changing z color. */ protected JButton colorButtonBackground; /** Color chooser dialog. */ protected ViewJColorChooser colorChooser; /** Panel for the rotation cube. */ protected JPanel cubePanel; /** Check box for cubic control. */ protected JCheckBox cubicCheck; /** Button group for projections. */ protected ButtonGroup radioButtonGroupProjections; /** Radio Button for Orthographic rendering. */ protected JRadioButton radioButtonOrthographic; /** Radio Button for Perspective rendering. */ protected JRadioButton radioButtonPerspective; /** Radio Button for Perspective rendering. */ protected JRadioButton viewAlignedButton; /** Radio Button for Orthographic rendering. */ protected JRadioButton viewButton; /** Button group for projections. */ protected ButtonGroup viewTextureButtonGroup; /** DOCUMENT ME! */ private JPanel buttonPanel; /** DOCUMENT ME! */ private float coarseValue, fineValue; /** DOCUMENT ME! */ private JTextField fine, coarse; /** DOCUMENT ME! */ private JLabel fineLabel, coarseLabel; /** Flag indicating if box is on or off. */ private boolean flag = false; //~ Constructors --------------------------------------------------------------------------------------------------- /** * Creates new dialog for turning bounding box frame on and off. * * @param parent Should be of type ViewJFrameSurfaceRenderer */ public JPanelSurfaceBox(RenderViewBase parent) { super(parent); init(); cubicCheck.setVisible(false); cubePanel.setVisible(false); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * Changes color of box frame and button if color button was pressed; turns bounding box on and off if checkbox was * pressed; and closes dialog if "Close" button was pressed. * * @param event Event that triggered function. */ public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if ((source instanceof JButton) && (source != cancelButton)) { colorChooser = new ViewJColorChooser(new Frame(), "Pick color", new OkColorListener((JButton) source), new CancelListener()); } else if (source == boundingCheck) { if (boundingCheck.isSelected() != flag) { flag = boundingCheck.isSelected(); if (flag == true) { ((SurfacePlotter) renderBase).showBoxFrame(); colorButton.setEnabled(true); } else { ((SurfacePlotter) renderBase).hideBoxFrame(); colorButton.setEnabled(false); } } } else if (source == radioButtonOrthographic) { if (renderBase instanceof SurfaceRender) { ((SurfaceRender) renderBase).setRenderPerspective(false); } else if (renderBase instanceof SurfacePlotter) { ((SurfacePlotter) renderBase).setRenderPerspective(false); } } else if (source == radioButtonPerspective) { if (renderBase instanceof SurfaceRender) { ((SurfaceRender) renderBase).setRenderPerspective(true); } else if (renderBase instanceof SurfacePlotter) { ((SurfacePlotter) renderBase).setRenderPerspective(true); } } else if (source == viewButton) { ((SurfaceRender) renderBase).setViewTextureAligned(false); setTextEnabled(false); } else if (source == viewAlignedButton) { coarse.setText(Float.toString(((SurfaceRender) renderBase).getSliceSpacingCoarse())); ((SurfaceRender) renderBase).setViewTextureAligned(true); setTextEnabled(true); } else if (source == cubicCheck) { if (cubicCheck.isSelected()) { ((SurfaceRender) renderBase).addCubicControl(); } else { ((SurfaceRender) renderBase).removeCubicControl(); } } else if (source == cancelButton) { this.setVisible(false); } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public float getCoarseVal() { return Float.parseFloat(coarse.getText()); } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public JPanel getMainPanel() { buttonPanel.setVisible(false); return mainPanel; } /** * DOCUMENT ME! * * @param evt DOCUMENT ME! */ public void keyTyped(KeyEvent evt) { Object source = evt.getSource(); char ch = evt.getKeyChar(); if (ch == KeyEvent.VK_ENTER) { fineValue = Float.parseFloat(fine.getText()); coarseValue = Float.parseFloat(coarse.getText()); ((SurfaceRender) renderBase).setSliceSpacingFine(fineValue); ((SurfaceRender) renderBase).setSliceSpacingCoarse(coarseValue); if (source.equals(fine)) { ((SurfaceRender) renderBase).useSliceSpacingFine(); } else { ((SurfaceRender) renderBase).useSliceSpacingCoarse(); } } } /** * DOCUMENT ME! * * @param _color DOCUMENT ME! */ public void setColorButton(Color _color) { colorButtonBackground.setBackground(_color); } /** * DOCUMENT ME! * * @param flag DOCUMENT ME! */ public void setEnable(boolean flag) { viewButton.setEnabled(flag); viewAlignedButton.setEnabled(flag); } /** * DOCUMENT ME! * * @param flag DOCUMENT ME! */ public void setTextEnabled(boolean flag) { fineLabel.setEnabled(false); coarseLabel.setEnabled(flag); fine.setEnabled(false); coarse.setEnabled(flag); } /** * /** Takes a text field and forces the text field to accept numbers, backspace and delete-key entries. * * @param status Text field to modify. */ /** * protected void makeNumericsOnly(JTextField txt, boolean allowFloatingPoint) { if (allowFloatingPoint) { * txt.addKeyListener(new KeyAdapter() { // make the field public void keyTyped(KeyEvent evt) { // not accept * letters JTextField t = (JTextField) evt.getComponent(); char ch = evt.getKeyChar(); if (ch == KeyEvent.VK_ENTER) * { // make sure the enter key acts as clicking OK t.getNextFocusableComponent(); } else if (ch == '.') { if * (t.getSelectedText() != null) { if (t.getText().length() == t.getSelectedText().length()) { t.setText("0"); } * else if ( (t.getText().indexOf('.') != -1) // there is a '.', but no && (t.getSelectedText().indexOf('.') == -1)) * { // in the selected text evt.consume(); // ignore } } else if (t.getText().indexOf('.') != -1) { evt.consume(); * } else if (t.getText().length() == 0) { t.setText("0"); } } //negative signs are not allowed else if ( ( (ch < * '0') || (ch > '9')) && ( (ch != KeyEvent.VK_DELETE) && (ch != KeyEvent.VK_BACK_SPACE))) { // if is the case that * ch is outside the bounds of a number AND it is the case that ch is neither a BS or a DE, then... // key is not a * digit or a deletion char evt.consume(); } } }); } else { txt.addKeyListener(new KeyAdapter() { // make the field * public void keyTyped(KeyEvent evt) { // not accept letters JTextField t = (JTextField) evt.getComponent(); char * ch = evt.getKeyChar(); if (ch == KeyEvent.VK_ENTER) { // make sure the enter key acts as clicking OK * t.getNextFocusableComponent(); } else if ( ( (ch < '0') || (ch > '9')) && ( (ch != KeyEvent.VK_DELETE) && (ch != * KeyEvent.VK_BACK_SPACE))) { // if is the case that ch is outside the bounds of a number AND it is the case that * ch is neither a BS or a DE, then... // key is not a digit or a deletion char evt.consume(); } } }); } } * * @param status DOCUMENT ME! */ /** * Makes the dialog visible next to the parent frame. If this makes it go off the screen, puts the dialog in the * center of the screen. * * @param status Flag indicating if the dialog should be visible. */ public void setVisible(boolean status) { Point location = new Point(); location.x = renderBase.getLocation().x - getWidth(); location.y = renderBase.getLocation().y + renderBase.getHeight(); if (((location.x + getWidth()) < Toolkit.getDefaultToolkit().getScreenSize().width) && ((location.y + getHeight()) < Toolkit.getDefaultToolkit().getScreenSize().height)) { setLocation(location); } else { Rectangle dialogBounds = getBounds(); setLocation((Toolkit.getDefaultToolkit().getScreenSize().width / 2) - (dialogBounds.width / 2), (Toolkit.getDefaultToolkit().getScreenSize().height / 2) - (dialogBounds.height / 2)); } super.setVisibleStandard(status); } /** * Calls the appropriate method in the parent frame. * * @param button DOCUMENT ME! * @param color Color to set box frame to. */ protected void setBoxColor(JButton button, Color color) { if (button == colorButton) { renderBase.setBoxColor(color); } else if (button == colorButtonBackground) { renderBase.setBackgroundColor(color); } } /** * Initializes GUI components. */ private void init() { // setTitle("Bounding box"); mainPanel = new JPanel(); boundingCheck = new JCheckBox("Show bounding frame"); boundingCheck.setFont(serif12); boundingCheck.addActionListener(this); colorButton = new JButton(); colorButton.setPreferredSize(new Dimension(25, 25)); colorButton.setToolTipText("Change box frame color"); colorButton.addActionListener(this); colorButton.setBackground(Color.red); colorButton.setEnabled(false); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(5, 5, 5, 5); panel.add(colorButton, gbc); gbc.gridx = 1; panel.add(boundingCheck, gbc); panel.setBorder(buildTitledBorder("Bounding box options")); colorButtonBackground = new JButton(); colorButtonBackground.setPreferredSize(new Dimension(25, 25)); colorButtonBackground.setToolTipText("Change background color"); colorButtonBackground.addActionListener(this); colorButtonBackground.setBackground(Color.darkGray); JLabel backgroundLabel = new JLabel("Background color"); backgroundLabel.setFont(serif12); backgroundLabel.setForeground(Color.black); JPanel panel2 = new JPanel(new GridBagLayout()); gbc.gridx = 0; gbc.gridy = 0; panel2.add(colorButtonBackground, gbc); gbc.gridx = 1; panel2.add(backgroundLabel, gbc); panel2.setBorder(buildTitledBorder("Background")); JPanel projectionTypePanel = new JPanel(); projectionTypePanel.setBorder(buildTitledBorder("Projection Type")); Box projectionTypeBox = new Box(BoxLayout.X_AXIS); radioButtonPerspective = new JRadioButton(); radioButtonPerspective.addActionListener(this); radioButtonOrthographic = new JRadioButton(); radioButtonOrthographic.addActionListener(this); radioButtonGroupProjections = new ButtonGroup(); radioButtonPerspective.setSelected(true); radioButtonPerspective.setText("Perspective View "); radioButtonOrthographic.setText("Orthographic View"); radioButtonGroupProjections.add(radioButtonPerspective); radioButtonGroupProjections.add(radioButtonOrthographic); projectionTypeBox.add(radioButtonPerspective); projectionTypeBox.add(radioButtonOrthographic); projectionTypePanel.add(projectionTypeBox); cubicCheck = new JCheckBox("Show orientation cube"); cubicCheck.setFont(serif12); cubicCheck.addActionListener(this); cubePanel = new JPanel(new GridBagLayout()); gbc.weightx = 1; gbc.anchor = GridBagConstraints.WEST; gbc.insets = new Insets(5, 5, 5, 5); cubePanel.add(cubicCheck, gbc); cubePanel.setBorder(buildTitledBorder("Orientation")); JPanel viewTexturePanel = new JPanel(); viewTexturePanel.setBorder(buildTitledBorder("Texture Type")); Box viewTextureBox = new Box(BoxLayout.Y_AXIS); viewButton = new JRadioButton(); viewButton.addActionListener(this); viewAlignedButton = new JRadioButton(); viewAlignedButton.addActionListener(this); viewTextureButtonGroup = new ButtonGroup(); viewButton.setSelected(true); viewButton.setText("View volume texture "); viewAlignedButton.setText("View aligned volume texture"); viewTextureButtonGroup.add(viewButton); viewTextureButtonGroup.add(viewAlignedButton); JPanel inputPanel = new JPanel(new GridBagLayout()); fineLabel = new JLabel("Fine"); fineLabel.setFont(serif12); fineLabel.setForeground(Color.black); fineLabel.setRequestFocusEnabled(false); gbc.weightx = 0.5; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(1, 1, 1, 1); gbc.gridx = 0; gbc.gridy = 0; inputPanel.add(fineLabel, gbc); fine = new JTextField(3); if (renderBase instanceof SurfaceRender) { fine.setText(Float.toString(((SurfaceRender) renderBase).getSliceSpacingFine())); } fine.addKeyListener(this); MipavUtil.makeNumericsOnly(fine, true); // makeNumericsOnly(fine, true); gbc.gridx = 1; inputPanel.add(fine, gbc); coarseLabel = new JLabel("Coarse"); coarseLabel.setFont(serif12); coarseLabel.setForeground(Color.black); coarseLabel.setRequestFocusEnabled(false); gbc.gridx = 0; gbc.gridy = 1; inputPanel.add(coarseLabel, gbc); coarse = new JTextField(3); if (renderBase instanceof SurfaceRender) { coarse.setText(Float.toString(((SurfaceRender) renderBase).getSliceSpacingCoarse())); } coarse.addKeyListener(this); MipavUtil.makeNumericsOnly(coarse, true); // makeNumericsOnly(coarse, true); gbc.gridx = 1; inputPanel.add(coarse, gbc); viewTextureBox.add(viewButton); viewTextureBox.add(viewAlignedButton); viewTextureBox.add(inputPanel); viewTexturePanel.add(viewTextureBox); Box contentBox = new Box(BoxLayout.Y_AXIS); contentBox.add(panel); contentBox.add(panel2); contentBox.add(cubePanel); contentBox.add(projectionTypePanel); contentBox.add(viewTexturePanel); buttonPanel = new JPanel(); buildCancelButton(); cancelButton.setText("Close"); buttonPanel.add(cancelButton); contentBox.add(buttonPanel); // getContentPane().add(contentBox); mainPanel.add(contentBox); setEnable(false); setTextEnabled(false); // pack(); // setVisible(true); } //~ Inner Classes -------------------------------------------------------------------------------------------------- /** * Does nothing. */ class CancelListener implements ActionListener { /** * Does nothing. * * @param e DOCUMENT ME! */ public void actionPerformed(ActionEvent e) { } } /** * Pick up the selected color and call method to change the VOI color. */ class OkColorListener implements ActionListener { /** DOCUMENT ME! */ JButton button; /** * Creates a new OkColorListener object. * * @param _button DOCUMENT ME! */ OkColorListener(JButton _button) { super(); button = _button; } /** * Get color from chooser and set button and VOI color. * * @param e Event that triggered function. */ public void actionPerformed(ActionEvent e) { Color color = colorChooser.getColor(); button.setBackground(color); setBoxColor(button, color); } } }
package com.alex.pets; import com.alex.exceptions.PetIsDeadException; import com.alex.plants.Dyplo; public class Squirrel extends Pet implements Alive { private String name; private String breed; public Squirrel(String someName, String breed) { super(); this.name = someName; this.breed = breed; } public void eat(Object nut) { if (!isAlive) { throw new PetIsDeadException(this); } else { System.out.println("Squirrel " + name + " eat " + nut); } } public void jump() { if (!isAlive) { throw new PetIsDeadException(this); } else { System.out.println("Squirrel " + name + " is jumping"); } } public void store(Object object) { if (!isAlive) { System.out.println("Squirrel distress"); throw new PetIsDeadException(this); } else { if (object instanceof Dyplo) { Dyplo dyplo = (Dyplo) object; dyplo.store(this); System.out.println("The squirrel " + name + " stores nuts in a hollow"); } } } public String getName() { return name; } public String toString() { return "Squirrel " + name; } public String getBreed() { return breed; } }
package behavioral.iterator.my; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { SocialNetwork socialNetwork = new Facebook(getTestProfiles()); Spammer spammer = new Spammer(socialNetwork); spammer.sendSpamToFriends("aaa@123.com", "buy a iphone?"); spammer.sendSpamToCoworkers("aaa@123.com", "get a good job?"); } public static List<Profile> getTestProfiles() { List<Profile> data = new ArrayList<>(); data.add(new Profile("aaa@123.com", "Anna Smith", "friends:mad_max@ya.com", "friends:catwoman@yahoo.com", "coworkers:sam@amazon.com")); data.add(new Profile("mad_max@ya.com", "Maximilian", "friends:anna.smith@bing.com", "coworkers:sam@amazon.com")); data.add(new Profile("bill@microsoft.eu", "Billie", "coworkers:avanger@ukr.net")); data.add(new Profile("avanger@ukr.net", "John Day", "coworkers:bill@microsoft.eu")); data.add(new Profile("sam@amazon.com", "Sam Kitting", "coworkers:anna.smith@bing.com", "coworkers:mad_max@ya.com", "friends:catwoman@yahoo.com")); data.add(new Profile("catwoman@yahoo.com", "Liza", "friends:anna.smith@bing.com", "friends:sam@amazon.com")); return data; } }
//package org.zerhusen.config; // //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.Configuration; //import org.springframework.context.annotation.Import; //import org.springframework.context.annotation.PropertySource; //import org.springframework.core.env.Environment; //import org.springframework.data.jpa.repository.config.EnableJpaRepositories; //import org.springframework.orm.jpa.JpaTransactionManager; //import org.springframework.orm.jpa.JpaVendorAdapter; //import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; //import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; //import org.springframework.transaction.PlatformTransactionManager; //import org.springframework.transaction.annotation.EnableTransactionManagement; // //import javax.sql.DataSource; //import java.util.Properties; // //@Configuration ////@EnableJpaRepositories(basePackages = {"com.wanban.fileservice.database.repository", "com.yuyan.database.repository"}) //////@EnableTransactionManagement //////@PropertySource(value = { ////// "classpath:datasource.properties", ////// "classpath:datasource_override.properties" //////}, ignoreResourceNotFound = true) ////@Import(ServiceConfig.class) //public class DataSourceConfig { // // @Bean() // public DataSource dataSource() { // org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource(); // //com.alibaba.druid.pool.DruidDataSource dataSource = new com.alibaba.druid.pool.DruidDataSource(); //// dataSource.setDriverClassName(env.getProperty("db.driverClassName")); //// //// String url = env.getProperty("db.url"); //// String ip = rootEnv.getDatabaseIp(); //// String realUrl = url.replaceAll("\\d{1,3}(\\.\\d{1,3}){3}", ip);//replace the ip in the data source properties with ip in service properties //// // dataSource.setUrl("jdbc:postgresql://127.0.0.1/file_db"); // dataSource.setUsername("file_user"); // dataSource.setPassword("123456"); //// dataSource.setMaxActive(env.getProperty("db.maxActive", Integer.class)); //// dataSource.setInitialSize(env.getProperty("db.initialSize", Integer.class)); //// dataSource.setMaxIdle(env.getProperty("db.maxIdle", Integer.class)); //// dataSource.setMinIdle(env.getProperty("db.minIdle", Integer.class)); //// dataSource.setValidationQuery(env.getProperty("db.validationQuery")); //// dataSource.setTestOnBorrow(env.getProperty("db.testOnBorrow", Boolean.class)); //// dataSource.setTestOnReturn(env.getProperty("db.testOnReturn", Boolean.class)); //// dataSource.setTestWhileIdle(env.getProperty("db.testWhileIdle", Boolean.class)); //// dataSource.setTimeBetweenEvictionRunsMillis(env.getProperty("db.timeBetweenEvictionRunsMillis", Integer.class)); //// dataSource.setMinEvictableIdleTimeMillis(env.getProperty("db.minEvictableIdleTimeMillis", Integer.class)); //// //// dataSource.setRemoveAbandoned(env.getProperty("db.removeAbandoned", Boolean.class)); //// dataSource.setRemoveAbandonedTimeout(env.getProperty("db.removeAbandonedTimeout", Integer.class)); //// dataSource.setMaxWait(env.getProperty("db.maxWait", Integer.class)); //// dataSource.setLogAbandoned(env.getProperty("db.logAbandoned", Boolean.class)); // // return dataSource; // } // // @Bean // public LocalContainerEntityManagerFactoryBean entityManagerFactory() { // JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // // LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); // factory.setJpaVendorAdapter(vendorAdapter); // factory.setDataSource(dataSource()); // factory.setPackagesToScan("com.wanban.fileservice.database.entity", "com.yuyan.database.entity"); // factory.setJpaProperties(additionalProperties()); // // return factory; // } // // @Bean // public PlatformTransactionManager transactionManager() { // JpaTransactionManager transactionManager = new JpaTransactionManager(); // transactionManager.setEntityManagerFactory(entityManagerFactory().getObject()); // return transactionManager; // } // // Properties additionalProperties() { // return new Properties() { // { // setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect"); //// setProperty("hibernate.show_sql", env.getProperty("db.hibernate.show_sql")); //// setProperty("hibernate.jdbc.batch_size", env.getProperty("db.hibernate.jdbc.batch_size")); //// //// // hbm2ddl should be used for development, omitted for production //// String hbm2ddl = env.getProperty("db.hibernate.hbm2ddl.auto"); //// if (hbm2ddl != null) { //// //setProperty("hibernate.hbm2ddl.auto", hbm2ddl); //// } // } // }; // } // //}
package com.saasxx.core.config; public class Constants { /** * 以下是包扫描路径常量 **/ final static String BACKAGE_SCHEMA = "com.saasxx.**.schema"; final static String BACKAGE_DAO = "com.saasxx.**.dao"; final static String BACKAGE_SERVICE = "com.saasxx.**.service"; final static String BACKAGE_STARTUP = "com.saasxx.**.startup"; final static String BACKAGE_WEB = "com.saasxx.**.web"; /* * 验证码 */ public static final long VERIFICATION_CODE_EXPIRES = 30 * 60 * 1000; // 验证码超时时间(30m) public static final long SEND_VERIFICATION_CODE_INTERVAL = 60 * 1000; // 发送验证码时间间隔(60s) }
/** * Project Name:market * File Name:Bill.java * Package Name:com.market.entity * Date:2020年4月29日下午5:09:26 * Copyright (c) 2020, 277809183@qq.com All Rights Reserved. * */ /** * Project Name:market * File Name:Bill.java * Package Name:com.market.entity * Date:2020年4月29日下午5:09:26 * Copyright (c) 2020, 837806955@qq.com All Rights Reserved. * */ package com.market.entity; /** * ClassName:Bill <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2020年4月29日 下午5:09:26 <br/> * @author Future * @version * @since JDK 1.8 * @see */ /** * ClassName: Bill <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON(可选). <br/> * date: 2020年4月29日 下午5:09:26 <br/> * * @author Li Zhengyu * @version * @since JDK 1.8 */ public class Bill { private String bid; private String bname; private double bprice; private double bamount; private double btotal; private String bprovider; private String binfo; private String bdate; public Bill() { super(); // TODO Auto-generated constructor stub } public Bill(String bid, String bname, double bprice, double bamount, double btotal,String bprovider, String binfo,String bdate) { super(); this.bid = bid; this.bname = bname; this.bprice = bprice; this.bamount = bamount; this.btotal=btotal; this.bprovider=bprovider; this.binfo=binfo; this.bdate=bdate; } public String getBid() { return bid; } public void setBid(String bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public double getBprice() { return bprice; } public void setBprice(double bprice) { this.bprice = bprice; } public double getBamount() { return bamount; } public void setBamount(double bamount) { this.bamount = bamount; } public double getBtotal() { return btotal; } public void setBtotal(double btotal) { this.btotal = btotal; } public String getBprovider() { return bprovider; } public void setBprovider(String bprovider) { this.bprovider = bprovider; } public String getBinfo() { return binfo; } public void setBinfo(String binfo) { this.binfo = binfo; } public String getBdate() { return bdate; } public void setBdate(String bdate) { this.bdate = bdate; } }
import java.util.Scanner; import java.util.Arrays; /* * Class: Game * Description: The class represents a single Game item for * any type of item that can be hired. * It is also contains functions that are needed to modify the hiring record * and build a string containing the information contained in the game class. * Author: [Danny le] - [s3722067] */ public class Game extends Item { private final static double RENTAL_SURCHARGE = 7.00; private final static double EXTENDED_MULITIPLIER = 0.50; private final static double NOT_EXTENDED_MULITIPLIER = 1.00; private final int RENTAL_PERIOD = 7; private String[] platforms = new String[100]; private boolean extended; Scanner scanner = new Scanner(System.in); public Game(String id, String title, String genre, String description, String[] platforms) throws IdException { super("G_" + id, title, genre, description, RENTAL_SURCHARGE); this.platforms = platforms; } /* * borrow ALGORITHM * BEGIN * IF input of Extended is Y * SET extended to true * ELSE input of Extended is N * SET extended to false * CALL the super borrow method * IF an exception is thrown and caught, throw the same exception * RETURN borrowingFee * END */ public double borrow(String memberid, String inputExtended, int daysinadvance) throws BorrowException, IdException { //Sets the borrowing fee by prompting the user to enter whether the hire is extended //then calling the item borrow method and returns the borrowing fee //If a borrow exception was thrown and caught, it will throw the exception again to the //movie master class to handle if (inputExtended.equals("Y")) { this.extended = true; } else if (inputExtended.equals("N")) { this.extended = false; } double borrowingFee; try { borrowingFee = super.borrow(memberid, new DateTime(daysinadvance)); } catch (BorrowException e) { throw new BorrowException(e.getMessage()); } return borrowingFee; } /* * returnItem ALGORITHM * BEGIN * COMPUTE the difference in days * IF difference in days is greater or equal to 0 * COMPUTE the borrowDays * COMPUTE number of late days * IF number of late days is greater than 0 * COMPUTE extended multiplier * COMPUTE the late fee * CALL the super method returnItem * ELSE * SET late fee to 0 * CALL the super method returnItem * ELSE * PRINT an error message as the item cannot be return before the borrow date * RETURN total fee * END */ public double returnItem(DateTime returnDate) { int borrowDays; double lateFee; double extendedMultiplier; double totalFee = 0; // Finds the difference in days based on the return date and the borrow date if it // greater than or equal to zero than the rest of the code is ran, however if the difference is days is //it is not valid as the user is try to return the item before the borrow date and an error message is printed to the console int differenceInDays = DateTime.diffDays(returnDate, getCurrentlyBorrowed().getborrowDate()); // Calculates extended multiplier to then calculate the late fee which is then sent to the //return item method of the item class to calculate the total fee which is then returned if (differenceInDays >= 0) { borrowDays = RENTAL_PERIOD; int noOfLateDays = DateTime.diffDays(returnDate, new DateTime((getCurrentlyBorrowed().getborrowDate()), borrowDays)); if (noOfLateDays > 0) { if (extended) { extendedMultiplier = EXTENDED_MULITIPLIER; } else { extendedMultiplier = NOT_EXTENDED_MULITIPLIER ; } lateFee = (((1 * noOfLateDays) + (5 * (noOfLateDays / 7))) * extendedMultiplier); totalFee = super.returnItem(returnDate, lateFee); } else { lateFee = 0; totalFee = super.returnItem(returnDate, lateFee); } } else { System.out.println("Error -Can not be returned before the borrow date"); totalFee = Double.NaN; } return totalFee; } /* * getDetails ALGORITHM * BEGIN * CREATE new string builder * APPEAD details passed by the getDeatils method in the items class * IF Game is currently borrowed and is on extended hire * SET string that represents the loan status to "Extended" * ELSE IF the game is only currently borrowed * SET string that represents the loan status to "True" * ELSE IF the game in not on loan * SET string that represents the loan status to "False" * APPEND details to the string builder * APPEND details passed by the getDeatils2 method in the items class * RETURN string builder to string * END */ public String getDetails() { String onloan = null; StringBuilder Details = new StringBuilder(1000); Details.append(super.getDetails()); if (getCurrentlyBorrowed() != null && extended) { onloan = "Extended"; } else if (getCurrentlyBorrowed() != null) { onloan = "True"; } else if (getCurrentlyBorrowed() == null) { onloan = "False"; } Details.append(String.format("%-25s %s\n", "Platforms:", Arrays.toString(platforms))); Details.append(String.format("%-25s %s\n", "Rental Period:", RENTAL_PERIOD + " days")); Details.append(String.format("%-25s %s\n", "On loan:", onloan)); Details.append(String.format("%25s %-25s\n", "", "Borrowing Record")); Details.append(super.getDetails2()); return Details.toString(); } /* * toString ALGORITHM * BEGIN * FOR the number of platforms in the platforms array * APPEND the platform name to a string * IF the game has a currently borrowed record and is extended * SET hire type to "E" * ELSE the game has a currently borrowed record * SET hire type to "T" *ELSE IF currently borrowed is empty * SET loan status to "F" * SET string to the formatted with the string given by the super class, the string of platforms and loan status * RETURN the formatted string * END */ public String toString() { String platform = ""; for (int i = 0; i < platforms.length; i++) { platform = platform + platforms[i] + ","; } String loanStatus = null; if (getCurrentlyBorrowed() != null && extended) { loanStatus = "E"; } else if (getCurrentlyBorrowed() != null) { loanStatus = "T"; } else if (getCurrentlyBorrowed() == null) { loanStatus = "F"; } String toString = String.format("%s:%s:%s\n", super.toString(), platform, loanStatus); return toString; } public void setExtened(boolean extended) { this.extended = extended; } }
package com.example.testingswapi; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.List; public class PeopleAdapter extends ArrayAdapter<Person> { List<Person> personList; Context context; private LayoutInflater inflater; public PeopleAdapter(Context context, List<Person> objectList) { super(context, 0, objectList); this.inflater = LayoutInflater.from(context); this.context = context; personList = objectList; } @Override public Person getItem(int position) { return personList.get(position); } @Override public View getView(int position, View convertView, ViewGroup parent) { final ViewHolder viewHolder; if (convertView == null) { View view = inflater.inflate(R.layout.search_listview, parent, false); viewHolder = ViewHolder.create((RelativeLayout) view); view.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } Person item = getItem(position); viewHolder.dataTextView.setText(item.getName()); return viewHolder.personView; } private static class ViewHolder { public final RelativeLayout personView; public final TextView dataTextView; private ViewHolder(RelativeLayout personView, TextView dataTextView) { this.personView = personView; this.dataTextView = dataTextView; } public static ViewHolder create (RelativeLayout personView) { TextView dataTextView = (TextView) personView.findViewById(R.id.textView); return new ViewHolder(personView, dataTextView); } } }
package com.jgw.supercodeplatform.trace.vo; import java.util.List; import com.jgw.supercodeplatform.trace.dto.blockchain.NodeInsertBlockChainStruct; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(value = "区块链返回前端节点数据详情model") public class NodeBlockChainInfoVO { @ApiModelProperty(value = "主键id") private Long blockChainId; @ApiModelProperty(value = "功能节点id") private String functionId; @ApiModelProperty(value = "功能节点名称") private String functionName; // 上链节点信息 @ApiModelProperty(value = "当前业务系统节点对象数据",hidden=true) private List<NodeInsertBlockChainStruct> currentNodeInfoList; // 上链节点信息 @ApiModelProperty(value = "上链业务系统节点对象数据",hidden=true) private List<NodeInsertBlockChainStruct> lastNodeInfoList; @ApiModelProperty(value = "当前业务系统节点数据") private String localDataJson; @ApiModelProperty(value = "上链节点数据") private String blockchainDataJson; // 区块号 @ApiModelProperty(value = "区块号") private Long blockNo; @ApiModelProperty(value = "区块hash--所在区块链位置") private String blockHash; @ApiModelProperty(value = "交易hash--全球唯一区块链hash编号") private String transactionHash; @ApiModelProperty(value = "交易时间") private String transactionTime; /** * 1上链 2 疑视串改 3未上链 */ @ApiModelProperty(value = "上链状态 ,1:验证通过,2 校验不通过") private boolean check; public boolean getCheck() { return check; } public void setCheck(boolean check) { this.check = check; } public Long getBlockChainId() { return blockChainId; } public void setBlockChainId(Long blockChainId) { this.blockChainId = blockChainId; } public String getLocalDataJson() { return localDataJson; } public void setLocalDataJson(String localDataJson) { this.localDataJson = localDataJson; } public String getBlockchainDataJson() { return blockchainDataJson; } public void setBlockchainDataJson(String blockchainDataJson) { this.blockchainDataJson = blockchainDataJson; } public String getFunctionId() { return functionId; } public void setFunctionId(String functionId) { this.functionId = functionId; } public String getFunctionName() { return functionName; } public void setFunctionName(String functionName) { this.functionName = functionName; } public List<NodeInsertBlockChainStruct> getCurrentNodeInfoList() { return currentNodeInfoList; } public void setCurrentNodeInfoList(List<NodeInsertBlockChainStruct> currentNodeInfoList) { this.currentNodeInfoList = currentNodeInfoList; } public List<NodeInsertBlockChainStruct> getLastNodeInfoList() { return lastNodeInfoList; } public void setLastNodeInfoList(List<NodeInsertBlockChainStruct> lastNodeInfoList) { this.lastNodeInfoList = lastNodeInfoList; } public Long getBlockNo() { return blockNo; } public void setBlockNo(Long blockNo) { this.blockNo = blockNo; } public String getBlockHash() { return blockHash; } public void setBlockHash(String blockHash) { this.blockHash = blockHash; } public String getTransactionHash() { return transactionHash; } public void setTransactionHash(String transactionHash) { this.transactionHash = transactionHash; } public String getTransactionTime() { return transactionTime; } public void setTransactionTime(String transactionTime) { this.transactionTime = transactionTime; } }
package com.lyl.core.dao.domain; import java.util.ArrayList; import java.util.List; public class GalaxyExample { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table galaxy * * @mbg.generated */ protected String orderByClause; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table galaxy * * @mbg.generated */ protected boolean distinct; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table galaxy * * @mbg.generated */ protected List<Criteria> oredCriteria; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public GalaxyExample() { oredCriteria = new ArrayList<Criteria>(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public String getOrderByClause() { return orderByClause; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public void setDistinct(boolean distinct) { this.distinct = distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public boolean isDistinct() { return distinct; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public List<Criteria> getOredCriteria() { return oredCriteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public void or(Criteria criteria) { oredCriteria.add(criteria); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table galaxy * * @mbg.generated */ public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table galaxy * * @mbg.generated */ protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andIdIsNull() { addCriterion("id is null"); return (Criteria) this; } public Criteria andIdIsNotNull() { addCriterion("id is not null"); return (Criteria) this; } public Criteria andIdEqualTo(Integer value) { addCriterion("id =", value, "id"); return (Criteria) this; } public Criteria andIdNotEqualTo(Integer value) { addCriterion("id <>", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThan(Integer value) { addCriterion("id >", value, "id"); return (Criteria) this; } public Criteria andIdGreaterThanOrEqualTo(Integer value) { addCriterion("id >=", value, "id"); return (Criteria) this; } public Criteria andIdLessThan(Integer value) { addCriterion("id <", value, "id"); return (Criteria) this; } public Criteria andIdLessThanOrEqualTo(Integer value) { addCriterion("id <=", value, "id"); return (Criteria) this; } public Criteria andIdIn(List<Integer> values) { addCriterion("id in", values, "id"); return (Criteria) this; } public Criteria andIdNotIn(List<Integer> values) { addCriterion("id not in", values, "id"); return (Criteria) this; } public Criteria andIdBetween(Integer value1, Integer value2) { addCriterion("id between", value1, value2, "id"); return (Criteria) this; } public Criteria andIdNotBetween(Integer value1, Integer value2) { addCriterion("id not between", value1, value2, "id"); return (Criteria) this; } public Criteria andUidIsNull() { addCriterion("uid is null"); return (Criteria) this; } public Criteria andUidIsNotNull() { addCriterion("uid is not null"); return (Criteria) this; } public Criteria andUidEqualTo(String value) { addCriterion("uid =", value, "uid"); return (Criteria) this; } public Criteria andUidNotEqualTo(String value) { addCriterion("uid <>", value, "uid"); return (Criteria) this; } public Criteria andUidGreaterThan(String value) { addCriterion("uid >", value, "uid"); return (Criteria) this; } public Criteria andUidGreaterThanOrEqualTo(String value) { addCriterion("uid >=", value, "uid"); return (Criteria) this; } public Criteria andUidLessThan(String value) { addCriterion("uid <", value, "uid"); return (Criteria) this; } public Criteria andUidLessThanOrEqualTo(String value) { addCriterion("uid <=", value, "uid"); return (Criteria) this; } public Criteria andUidLike(String value) { addCriterion("uid like", value, "uid"); return (Criteria) this; } public Criteria andUidNotLike(String value) { addCriterion("uid not like", value, "uid"); return (Criteria) this; } public Criteria andUidIn(List<String> values) { addCriterion("uid in", values, "uid"); return (Criteria) this; } public Criteria andUidNotIn(List<String> values) { addCriterion("uid not in", values, "uid"); return (Criteria) this; } public Criteria andUidBetween(String value1, String value2) { addCriterion("uid between", value1, value2, "uid"); return (Criteria) this; } public Criteria andUidNotBetween(String value1, String value2) { addCriterion("uid not between", value1, value2, "uid"); return (Criteria) this; } public Criteria andNameIsNull() { addCriterion("name is null"); return (Criteria) this; } public Criteria andNameIsNotNull() { addCriterion("name is not null"); return (Criteria) this; } public Criteria andNameEqualTo(String value) { addCriterion("name =", value, "name"); return (Criteria) this; } public Criteria andNameNotEqualTo(String value) { addCriterion("name <>", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThan(String value) { addCriterion("name >", value, "name"); return (Criteria) this; } public Criteria andNameGreaterThanOrEqualTo(String value) { addCriterion("name >=", value, "name"); return (Criteria) this; } public Criteria andNameLessThan(String value) { addCriterion("name <", value, "name"); return (Criteria) this; } public Criteria andNameLessThanOrEqualTo(String value) { addCriterion("name <=", value, "name"); return (Criteria) this; } public Criteria andNameLike(String value) { addCriterion("name like", value, "name"); return (Criteria) this; } public Criteria andNameNotLike(String value) { addCriterion("name not like", value, "name"); return (Criteria) this; } public Criteria andNameIn(List<String> values) { addCriterion("name in", values, "name"); return (Criteria) this; } public Criteria andNameNotIn(List<String> values) { addCriterion("name not in", values, "name"); return (Criteria) this; } public Criteria andNameBetween(String value1, String value2) { addCriterion("name between", value1, value2, "name"); return (Criteria) this; } public Criteria andNameNotBetween(String value1, String value2) { addCriterion("name not between", value1, value2, "name"); return (Criteria) this; } public Criteria andAgeIsNull() { addCriterion("age is null"); return (Criteria) this; } public Criteria andAgeIsNotNull() { addCriterion("age is not null"); return (Criteria) this; } public Criteria andAgeEqualTo(Integer value) { addCriterion("age =", value, "age"); return (Criteria) this; } public Criteria andAgeNotEqualTo(Integer value) { addCriterion("age <>", value, "age"); return (Criteria) this; } public Criteria andAgeGreaterThan(Integer value) { addCriterion("age >", value, "age"); return (Criteria) this; } public Criteria andAgeGreaterThanOrEqualTo(Integer value) { addCriterion("age >=", value, "age"); return (Criteria) this; } public Criteria andAgeLessThan(Integer value) { addCriterion("age <", value, "age"); return (Criteria) this; } public Criteria andAgeLessThanOrEqualTo(Integer value) { addCriterion("age <=", value, "age"); return (Criteria) this; } public Criteria andAgeIn(List<Integer> values) { addCriterion("age in", values, "age"); return (Criteria) this; } public Criteria andAgeNotIn(List<Integer> values) { addCriterion("age not in", values, "age"); return (Criteria) this; } public Criteria andAgeBetween(Integer value1, Integer value2) { addCriterion("age between", value1, value2, "age"); return (Criteria) this; } public Criteria andAgeNotBetween(Integer value1, Integer value2) { addCriterion("age not between", value1, value2, "age"); return (Criteria) this; } public Criteria andAddressIsNull() { addCriterion("address is null"); return (Criteria) this; } public Criteria andAddressIsNotNull() { addCriterion("address is not null"); return (Criteria) this; } public Criteria andAddressEqualTo(String value) { addCriterion("address =", value, "address"); return (Criteria) this; } public Criteria andAddressNotEqualTo(String value) { addCriterion("address <>", value, "address"); return (Criteria) this; } public Criteria andAddressGreaterThan(String value) { addCriterion("address >", value, "address"); return (Criteria) this; } public Criteria andAddressGreaterThanOrEqualTo(String value) { addCriterion("address >=", value, "address"); return (Criteria) this; } public Criteria andAddressLessThan(String value) { addCriterion("address <", value, "address"); return (Criteria) this; } public Criteria andAddressLessThanOrEqualTo(String value) { addCriterion("address <=", value, "address"); return (Criteria) this; } public Criteria andAddressLike(String value) { addCriterion("address like", value, "address"); return (Criteria) this; } public Criteria andAddressNotLike(String value) { addCriterion("address not like", value, "address"); return (Criteria) this; } public Criteria andAddressIn(List<String> values) { addCriterion("address in", values, "address"); return (Criteria) this; } public Criteria andAddressNotIn(List<String> values) { addCriterion("address not in", values, "address"); return (Criteria) this; } public Criteria andAddressBetween(String value1, String value2) { addCriterion("address between", value1, value2, "address"); return (Criteria) this; } public Criteria andAddressNotBetween(String value1, String value2) { addCriterion("address not between", value1, value2, "address"); return (Criteria) this; } public Criteria andPhoneIsNull() { addCriterion("phone is null"); return (Criteria) this; } public Criteria andPhoneIsNotNull() { addCriterion("phone is not null"); return (Criteria) this; } public Criteria andPhoneEqualTo(String value) { addCriterion("phone =", value, "phone"); return (Criteria) this; } public Criteria andPhoneNotEqualTo(String value) { addCriterion("phone <>", value, "phone"); return (Criteria) this; } public Criteria andPhoneGreaterThan(String value) { addCriterion("phone >", value, "phone"); return (Criteria) this; } public Criteria andPhoneGreaterThanOrEqualTo(String value) { addCriterion("phone >=", value, "phone"); return (Criteria) this; } public Criteria andPhoneLessThan(String value) { addCriterion("phone <", value, "phone"); return (Criteria) this; } public Criteria andPhoneLessThanOrEqualTo(String value) { addCriterion("phone <=", value, "phone"); return (Criteria) this; } public Criteria andPhoneLike(String value) { addCriterion("phone like", value, "phone"); return (Criteria) this; } public Criteria andPhoneNotLike(String value) { addCriterion("phone not like", value, "phone"); return (Criteria) this; } public Criteria andPhoneIn(List<String> values) { addCriterion("phone in", values, "phone"); return (Criteria) this; } public Criteria andPhoneNotIn(List<String> values) { addCriterion("phone not in", values, "phone"); return (Criteria) this; } public Criteria andPhoneBetween(String value1, String value2) { addCriterion("phone between", value1, value2, "phone"); return (Criteria) this; } public Criteria andPhoneNotBetween(String value1, String value2) { addCriterion("phone not between", value1, value2, "phone"); return (Criteria) this; } public Criteria andExtInfoIsNull() { addCriterion("ext_info is null"); return (Criteria) this; } public Criteria andExtInfoIsNotNull() { addCriterion("ext_info is not null"); return (Criteria) this; } public Criteria andExtInfoEqualTo(String value) { addCriterion("ext_info =", value, "extInfo"); return (Criteria) this; } public Criteria andExtInfoNotEqualTo(String value) { addCriterion("ext_info <>", value, "extInfo"); return (Criteria) this; } public Criteria andExtInfoGreaterThan(String value) { addCriterion("ext_info >", value, "extInfo"); return (Criteria) this; } public Criteria andExtInfoGreaterThanOrEqualTo(String value) { addCriterion("ext_info >=", value, "extInfo"); return (Criteria) this; } public Criteria andExtInfoLessThan(String value) { addCriterion("ext_info <", value, "extInfo"); return (Criteria) this; } public Criteria andExtInfoLessThanOrEqualTo(String value) { addCriterion("ext_info <=", value, "extInfo"); return (Criteria) this; } public Criteria andExtInfoLike(String value) { addCriterion("ext_info like", value, "extInfo"); return (Criteria) this; } public Criteria andExtInfoNotLike(String value) { addCriterion("ext_info not like", value, "extInfo"); return (Criteria) this; } public Criteria andExtInfoIn(List<String> values) { addCriterion("ext_info in", values, "extInfo"); return (Criteria) this; } public Criteria andExtInfoNotIn(List<String> values) { addCriterion("ext_info not in", values, "extInfo"); return (Criteria) this; } public Criteria andExtInfoBetween(String value1, String value2) { addCriterion("ext_info between", value1, value2, "extInfo"); return (Criteria) this; } public Criteria andExtInfoNotBetween(String value1, String value2) { addCriterion("ext_info not between", value1, value2, "extInfo"); return (Criteria) this; } public Criteria andRemarkIsNull() { addCriterion("remark is null"); return (Criteria) this; } public Criteria andRemarkIsNotNull() { addCriterion("remark is not null"); return (Criteria) this; } public Criteria andRemarkEqualTo(String value) { addCriterion("remark =", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotEqualTo(String value) { addCriterion("remark <>", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThan(String value) { addCriterion("remark >", value, "remark"); return (Criteria) this; } public Criteria andRemarkGreaterThanOrEqualTo(String value) { addCriterion("remark >=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThan(String value) { addCriterion("remark <", value, "remark"); return (Criteria) this; } public Criteria andRemarkLessThanOrEqualTo(String value) { addCriterion("remark <=", value, "remark"); return (Criteria) this; } public Criteria andRemarkLike(String value) { addCriterion("remark like", value, "remark"); return (Criteria) this; } public Criteria andRemarkNotLike(String value) { addCriterion("remark not like", value, "remark"); return (Criteria) this; } public Criteria andRemarkIn(List<String> values) { addCriterion("remark in", values, "remark"); return (Criteria) this; } public Criteria andRemarkNotIn(List<String> values) { addCriterion("remark not in", values, "remark"); return (Criteria) this; } public Criteria andRemarkBetween(String value1, String value2) { addCriterion("remark between", value1, value2, "remark"); return (Criteria) this; } public Criteria andRemarkNotBetween(String value1, String value2) { addCriterion("remark not between", value1, value2, "remark"); return (Criteria) this; } public Criteria andCallerIsNull() { addCriterion("caller is null"); return (Criteria) this; } public Criteria andCallerIsNotNull() { addCriterion("caller is not null"); return (Criteria) this; } public Criteria andCallerEqualTo(String value) { addCriterion("caller =", value, "caller"); return (Criteria) this; } public Criteria andCallerNotEqualTo(String value) { addCriterion("caller <>", value, "caller"); return (Criteria) this; } public Criteria andCallerGreaterThan(String value) { addCriterion("caller >", value, "caller"); return (Criteria) this; } public Criteria andCallerGreaterThanOrEqualTo(String value) { addCriterion("caller >=", value, "caller"); return (Criteria) this; } public Criteria andCallerLessThan(String value) { addCriterion("caller <", value, "caller"); return (Criteria) this; } public Criteria andCallerLessThanOrEqualTo(String value) { addCriterion("caller <=", value, "caller"); return (Criteria) this; } public Criteria andCallerLike(String value) { addCriterion("caller like", value, "caller"); return (Criteria) this; } public Criteria andCallerNotLike(String value) { addCriterion("caller not like", value, "caller"); return (Criteria) this; } public Criteria andCallerIn(List<String> values) { addCriterion("caller in", values, "caller"); return (Criteria) this; } public Criteria andCallerNotIn(List<String> values) { addCriterion("caller not in", values, "caller"); return (Criteria) this; } public Criteria andCallerBetween(String value1, String value2) { addCriterion("caller between", value1, value2, "caller"); return (Criteria) this; } public Criteria andCallerNotBetween(String value1, String value2) { addCriterion("caller not between", value1, value2, "caller"); return (Criteria) this; } public Criteria andInvalidIsNull() { addCriterion("invalid is null"); return (Criteria) this; } public Criteria andInvalidIsNotNull() { addCriterion("invalid is not null"); return (Criteria) this; } public Criteria andInvalidEqualTo(Integer value) { addCriterion("invalid =", value, "invalid"); return (Criteria) this; } public Criteria andInvalidNotEqualTo(Integer value) { addCriterion("invalid <>", value, "invalid"); return (Criteria) this; } public Criteria andInvalidGreaterThan(Integer value) { addCriterion("invalid >", value, "invalid"); return (Criteria) this; } public Criteria andInvalidGreaterThanOrEqualTo(Integer value) { addCriterion("invalid >=", value, "invalid"); return (Criteria) this; } public Criteria andInvalidLessThan(Integer value) { addCriterion("invalid <", value, "invalid"); return (Criteria) this; } public Criteria andInvalidLessThanOrEqualTo(Integer value) { addCriterion("invalid <=", value, "invalid"); return (Criteria) this; } public Criteria andInvalidIn(List<Integer> values) { addCriterion("invalid in", values, "invalid"); return (Criteria) this; } public Criteria andInvalidNotIn(List<Integer> values) { addCriterion("invalid not in", values, "invalid"); return (Criteria) this; } public Criteria andInvalidBetween(Integer value1, Integer value2) { addCriterion("invalid between", value1, value2, "invalid"); return (Criteria) this; } public Criteria andInvalidNotBetween(Integer value1, Integer value2) { addCriterion("invalid not between", value1, value2, "invalid"); return (Criteria) this; } public Criteria andUidLikeInsensitive(String value) { addCriterion("upper(uid) like", value.toUpperCase(), "uid"); return (Criteria) this; } public Criteria andNameLikeInsensitive(String value) { addCriterion("upper(name) like", value.toUpperCase(), "name"); return (Criteria) this; } public Criteria andAddressLikeInsensitive(String value) { addCriterion("upper(address) like", value.toUpperCase(), "address"); return (Criteria) this; } public Criteria andPhoneLikeInsensitive(String value) { addCriterion("upper(phone) like", value.toUpperCase(), "phone"); return (Criteria) this; } public Criteria andExtInfoLikeInsensitive(String value) { addCriterion("upper(ext_info) like", value.toUpperCase(), "extInfo"); return (Criteria) this; } public Criteria andRemarkLikeInsensitive(String value) { addCriterion("upper(remark) like", value.toUpperCase(), "remark"); return (Criteria) this; } public Criteria andCallerLikeInsensitive(String value) { addCriterion("upper(caller) like", value.toUpperCase(), "caller"); return (Criteria) this; } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table galaxy * * @mbg.generated do_not_delete_during_merge */ public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } /** * This class was generated by MyBatis Generator. * This class corresponds to the database table galaxy * * @mbg.generated */ public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
package com.gaoshin.business; import com.gaoshin.beans.NotificationList; import com.gaoshin.beans.User; public interface NotificationService { NotificationList after(User user, Long after, int size, boolean markRead, boolean unreadOnly); NotificationList before(User user, Long before, int size); }
/** * 最大子序和 https://leetcode-cn.com/problems/maximum-subarray/ */ public class 最大子序和 { public int maxSubArray3(int[] nums) {//正数的增益性,sum如果小于0,那加上num[i]肯定更小,这时候sum应该为nums[i] int sum=nums[0],max=nums[0]; for(int i=1;i<nums.length;i++){ sum=sum>=0?sum+nums[i]:nums[i]; max=Math.max(max,sum); } return max; } public int maxSubArray2(int[] nums) {//空间优化 int pre=0,max=nums[0]; for(int i=0;i<nums.length;i++){ pre=Math.max(pre+nums[i],nums[i]); max=Math.max(max,pre); } return max; } public int maxSubArray(int[] nums) { int[] dp=new int[nums.length]; dp[0]=nums[0]; int max=dp[0]; for(int i=1;i<dp.length;i++){ dp[i]=Math.max(dp[i-1]+nums[i],nums[i]); max=Math.max(max,dp[i]);//这个最大就确保了连续性 } return max; } }
package f.star.iota.milk.ui.www52guzhuang.www; import android.os.Bundle; import f.star.iota.milk.base.ScrollImageFragment; public class WWWFragment extends ScrollImageFragment<WWWPresenter, WWWAdapter> { public static WWWFragment newInstance(String url) { WWWFragment fragment = new WWWFragment(); Bundle bundle = new Bundle(); bundle.putString("base_url", url.replace("1-1.html", "")); bundle.putString("page_suffix", "-1.html"); fragment.setArguments(bundle); return fragment; } @Override protected WWWPresenter getPresenter() { return new WWWPresenter(this); } @Override protected WWWAdapter getAdapter() { return new WWWAdapter(); } @Override protected boolean isHideFab() { return false; } }
package com.qst.chapter08; import android.app.DownloadManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.ServiceConnection; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.IBinder; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button startButton; private Button stopButton; private Button bindButton; private Button operateButton; private Button unbindButton; private Button start4Button; private Button stop4Button; private Button bind4Button; private Button unbind4Button; private Button start5Button; private Button stop5Button; private Button bind5Button; private Button progress5Button; private Button start6Button; private Button stop6Button; private Button start7Button; private Button notificationManagerButton; private Button downloadManagerButton; private MyService3 myService3; private ServiceConnection myService3Connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Log.i("MainActivity", "myService3Connection.onServiceDisconnected():name=" + name); myService3 = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("MainActivity", "myService3Connection.onServiceConnected():name=" + name); myService3 = ((MyService3.MyBinder) service).getService(); } }; private ServiceConnection myService4Connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Log.i("MainActivity", "myService4Connection.onServiceDisconnected()"); } @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.i("MainActivity", "myService4Connection.onServiceConnected()"); } }; private MyService5 myService5; private ServiceConnection myService5Connection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { myService5 = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { myService5 = ((MyService5.MyBinder) service).getService(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startButton = (Button) findViewById(R.id.startButton); stopButton = (Button) findViewById(R.id.stopButton); bindButton = (Button) findViewById(R.id.bindButton); operateButton = (Button) findViewById(R.id.operateButton); unbindButton = (Button) findViewById(R.id.unbindButton); start4Button = (Button) findViewById(R.id.start4Button); stop4Button = (Button) findViewById(R.id.stop4Button); bind4Button = (Button) findViewById(R.id.bind4Button); unbind4Button = (Button) findViewById(R.id.unbind4Button); start5Button = (Button) findViewById(R.id.start5Button); stop5Button = (Button) findViewById(R.id.stop5Button); bind5Button = (Button) findViewById(R.id.bind5Button); progress5Button = (Button) findViewById(R.id.progress5Button); start6Button = (Button) findViewById(R.id.start6Button); stop6Button = (Button) findViewById(R.id.stop6Button); start7Button = (Button) findViewById(R.id.start7Button); // notificationManagerButton = (Button) findViewById(R.id.notificationManagerButton); downloadManagerButton = (Button) findViewById(R.id.downloadManagerButton); startButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService2.class); intent.putExtra("message", "hello!"); startService(intent); } }); stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService2.class); stopService(intent); } }); bindButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService3.class); intent.putExtra("message", "hello!"); bindService(intent, myService3Connection, Context.BIND_AUTO_CREATE); } }); operateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (myService3 == null) return; String returnValue = myService3.doSomeOperation("test"); Log.i("MainActivity", "myService3.doSomeOperation:" + returnValue); } }); unbindButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { unbindService(myService3Connection); } }); start4Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService4.class); startService(intent); } }); stop4Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService4.class); stopService(intent); } }); bind4Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService4.class); bindService(intent, myService4Connection, Context.BIND_AUTO_CREATE); } }); unbind4Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { unbindService(myService4Connection); } }); start5Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService5.class); intent.putExtra("notice title", "MyService5通知"); intent.putExtra("notice text", "MyService5成为前台服务了。"); startService(intent); } }); stop5Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService5.class); stopService(intent); } }); bind5Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService5.class); bindService(intent, myService5Connection, Context.BIND_AUTO_CREATE); } }); progress5Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Thread() { public void run() { for (int i = 0; i <= 100; i++) { final int p = i; runOnUiThread(new Runnable() { public void run() { myService5.setProgress(p); } }); try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } }); start6Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService6.class); startService(intent); } }); stop6Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService6.class); stopService(intent); } }); start7Button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, MyService7.class); startService(intent); } }); notificationManagerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { notification(); } }); downloadManagerButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { download(); } }); } private void notification() { Intent intent = new Intent(Settings.ACTION_SETTINGS); PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification notification = new Notification.Builder(this) .setSmallIcon(R.mipmap.ic_launcher) .setLargeIcon( BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) .setContentTitle("通知标题").setContentText("通知内容。") .setContentIntent(pendingIntent).setNumber(1).build(); notification.flags |= Notification.FLAG_AUTO_CANCEL; NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(1, notification); } private void download() { Uri uri = Uri.parse( "http://dl.ops.baidu.com/baidusearch_AndroidPhone_757p.apk"); DownloadManager.Request request = new DownloadManager.Request(uri); request.setTitle("下载示例"); request.setDescription("下载说明"); request.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "temp.apk"); request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); final DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); final long downloadId = downloadManager.enqueue(request); IntentFilter filter = new IntentFilter(); filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE); filter.addAction(DownloadManager.ACTION_NOTIFICATION_CLICKED); final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); long id = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) { if (id == downloadId) { Uri uri = downloadManager .getUriForDownloadedFile(downloadId); Log.i("MainActivity", "下载完毕:" + uri.toString()); } } else if (DownloadManager.ACTION_NOTIFICATION_CLICKED .equals(action)) { Log.i("MainActivity", "取消下载"); downloadManager.remove(id); } } }; registerReceiver(receiver, filter); } }
package Server; import util.BoundedBuffer; import util.LoggingPacket; import util.Snake; import java.util.concurrent.CopyOnWriteArrayList; /** * The worker class of the entire project. We expect to load this file first then * fire all relevant threads to start the snake game, the goal of the Server is to allow a Thread to be stuck in the * Game's while(true) and have threads interact with it within that while(true) * @author Mitchell & Kieran */ public class Server implements Runnable{ BoundedBuffer bb; BoundedBuffer logger; CopyOnWriteArrayList<Snake> players; /** * Constructor for Server; */ public Server(CopyOnWriteArrayList<Snake> playerList, BoundedBuffer<LoggingPacket> logger) { this.logger = logger; bb = new BoundedBuffer(50000); this.players = playerList; } @Override public void run() { Game theGame = new Game(bb, logger, players); theGame.init(); theGame.mainLoop(); } }
package uk.co.monkeypower.openchurch.portlet; import javax.portlet.PortalContext; import org.apache.pluto.container.CCPPProfileService; import org.apache.pluto.container.EventCoordinationService; import org.apache.pluto.container.FilterManagerService; import org.apache.pluto.container.NamespaceMapper; import org.apache.pluto.container.PortletEnvironmentService; import org.apache.pluto.container.PortletInvokerService; import org.apache.pluto.container.PortletPreferencesService; import org.apache.pluto.container.PortletRequestContextService; import org.apache.pluto.container.PortletURLListenerService; import org.apache.pluto.container.RequestDispatcherService; import org.apache.pluto.container.UserInfoService; import org.apache.pluto.container.driver.PortalAdministrationService; import org.apache.pluto.container.driver.PortalDriverServices; import org.apache.pluto.container.driver.PortletContextService; import org.apache.pluto.container.driver.PortletRegistryService; public class OpenChurchPortletDriverServices implements PortalDriverServices { private PortalContext portalContext; public void setPortalContext(PortalContext portalContext) { this.portalContext = portalContext; } public PortalContext getPortalContext() { return portalContext; } public EventCoordinationService getEventCoordinationService() { // TODO Auto-generated method stub return null; } public PortletRequestContextService getPortletRequestContextService() { // TODO Auto-generated method stub return null; } public FilterManagerService getFilterManagerService() { // TODO Auto-generated method stub return null; } public PortletURLListenerService getPortletURLListenerService() { // TODO Auto-generated method stub return null; } public PortletPreferencesService getPortletPreferencesService() { // TODO Auto-generated method stub return null; } public PortletEnvironmentService getPortletEnvironmentService() { // TODO Auto-generated method stub return null; } public PortletInvokerService getPortletInvokerService() { // TODO Auto-generated method stub return null; } public UserInfoService getUserInfoService() { // TODO Auto-generated method stub return null; } public NamespaceMapper getNamespaceMapper() { // TODO Auto-generated method stub return null; } public CCPPProfileService getCCPPProfileService() { // TODO Auto-generated method stub return null; } public RequestDispatcherService getRequestDispatcherService() { // TODO Auto-generated method stub return null; } public PortletContextService getPortletContextService() { // TODO Auto-generated method stub return null; } public PortletRegistryService getPortletRegistryService() { // TODO Auto-generated method stub return null; } public PortalAdministrationService getPortalAdministrationService() { // TODO Auto-generated method stub return null; } }
package com.citibank.ods.common.taglib; import javax.servlet.jsp.JspException; import org.apache.struts.taglib.TagUtils; import org.apache.struts.util.MessageResources; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.dataset.DataSetRow; /** * * Custom Tag utilizada para interação para as linhas de um DataSet. * * @version: 1.00 * @author Luciano Marubayashi, Dec 21, 2006 */ public class DataSetRowsTag extends BaseBodyTag { /** * C_DATA_SET_ROW_NAME_DEFAULT - Nome padrão utilizado para publicar uma linha * de um DataSet caso um nome não seja definido. */ private static final String C_DATA_SET_ROW_NAME_DEFAULT = "dataSetRow"; /** * C_LOCAL_STRINGS_NAME - nome do MessageResources utilizado por esta custom */ private static final String C_LOCAL_STRINGS_NAME = "com.citibank.ods.common.taglib"; /** * C_MESSAGE_DATASETROWS_INSTANCE - Código da mensagem que indica erro quando * o bean referenciado por m_name / m_property não for uma instância de * DataSet. */ private static final String C_MESSAGE_DATASETROWS_INSTANCE = "datasetrows.instance"; /** * C_MESSAGE_DATASETROWS_STEPINDEXNAME_EMPTY - Código da mensagem que indica * erro quando o m_stepIndexName for informado como "". */ private static final String C_MESSAGE_DATASETROWS_STEPINDEXNAME_EMPTY = "datasetrows.stepIndexName.empty"; /** * C_MESSAGE_DATASETROWS_STEPINDEXNAME_SEQUENCERESTARTSTEP_COMBO_INVALID - * Código da mensagem que indica erro quando o m_stepIndexName e * m_sequenceRestartStep estiverem preenchidos de maneira inconsistente. */ private static final String C_MESSAGE_DATASETROWS_STEPINDEXNAME_SEQUENCERESTARTSTEP_COMBO_INVALID = "datasetrows.stepIndexName.sequenceRestartStep.combo.invalid"; /** * m_dataSet - DataSet utilzzado para as interações. */ private DataSet m_dataSet; /** * m_rowIndex - Índice da linha do DataSet que está sendo avaliada. */ private int m_rowIndex = 0; /** * ms_messages - MessageResources utilizado pela custom tag para tratamento de * mensagens de exceção. */ protected static MessageResources ms_messages = MessageResources.getMessageResources( C_LOCAL_STRINGS_NAME ); /** * m_name - Nome do bean que é o DataSet que será percorrido (se m_property * não for especificada) ou do bean que possui uma propriedade que é o DataSet * que será percorrido (se m_property for especificado). */ private String m_name = null; /** * m_property - Propriedade do bean especificado por m_name que é o DataSet * que será percorrido. */ private String m_property = null; /** * Nome que será utilizado para publicar uma linha do DataSet. */ private String m_dataSetRowName = null; /** * m_counterScope - escopo de pesquisa do bean especificado pelo * m_counterName. Se não for especificado, serão aplicadas as regras padrão * definidas pelo PageContext.findAttribute(). */ private String m_scope = null; /** * m_sequenceRestartStep - indica o número de reinício de contagem de passo. * Sempre que o número da linha do DataSet que está sendo percorrida atingir * uma valor que é múltiplo deste valor (M_sequenceRestartIndex) a contagem de * pessao será reiniciada. */ private int m_sequenceRestartStep = 0; /** * m_stepIndexName - nome de publicação do Bean que representará o valor do * passo atual. */ private String m_stepIndexName = null; /** * * Getter da Propriedade < <propriedade>>. * * @return valor da Propriedade < <propriedade>>. */ public String getDataSetRowName() { return m_dataSetRowName; } /** * * Setter da propriedade < <propriedade>>. * * @param dataSetRowName_ - Valor da propriedade m_dataSetRowName. */ public void setDataSetRowName( String dataSetRowName_ ) { m_dataSetRowName = dataSetRowName_; } /** * * Getter da Propriedade m_name. * * @return valor da Propriedade m_name. */ public String getName() { return m_name; } /** * * Setter da propriedade m_name. * * @param dataSetRowName_ - Valor da propriedade m_name. */ public void setName( String name_ ) { m_name = name_; } /** * * Getter da Propriedade m_property. * * @return valor da Propriedade m_property. */ public String getProperty() { return m_property; } /** * * Setter da propriedade m_property. * * @param dataSetRowName_ - Valor da propriedade m_property. */ public void setProperty( String property_ ) { m_property = property_; } /** * * Getter da Propriedade m_scope. * * @return valor da Propriedade m_scope. */ public String getScope() { return m_scope; } /** * * Setter da propriedade m_scope. * * @param dataSetRowName_ - Valor da propriedade m_scope. */ public void setScope( String scope_ ) { m_scope = scope_; } /** * * Getter da Propriedade m_sequenceRestartStep. * * @return valor da Propriedade m_sequenceRestartStep. */ public int getSequenceRestartStep() { return m_sequenceRestartStep; } /** * * Setter da propriedade m_sequenceRestartStep. * * @param dataSetRowName_ - Valor da propriedade m_sequenceRestartStep. */ public void setSequenceRestartStep( int sequenceRestartStep_ ) { m_sequenceRestartStep = sequenceRestartStep_; } /** * * Getter da Propriedade m_stepIndexName. * * @return valor da Propriedade m_stepIndexName. */ public String getStepIndexName() { return m_stepIndexName; } /** * * Setter da propriedade m_stepIndexName. * * @param dataSetRowName_ - Valor da propriedade m_stepIndexName. */ public void setStepIndexName( String stepIndexName_ ) { m_stepIndexName = stepIndexName_; } /* * Pesquisa pelo DataSet e, caso exista e possua pelo menos uma linha, publica * a primeira linha. * @see javax.servlet.jsp.tagext.Tag#doStartTag() */ public int doStartTag() throws JspException { int tagAction = SKIP_BODY; Object dataSet = null; //procura pelo bean indicado dataSet = TagUtils.getInstance().lookup( pageContext, m_name, m_property, m_scope ); if ( dataSet != null ) { // Verifica se o bean obtido é um data set if ( !( dataSet instanceof DataSet ) ) { JspException e = new JspException( ms_messages.getMessage( C_MESSAGE_DATASETROWS_INSTANCE, m_name, m_property ) ); TagUtils.getInstance().saveException( pageContext, e ); throw e; } } //Verifica se o stepIndexName e o sequenceRestartStep estão consistentes if ( m_stepIndexName != null && "".equals( m_stepIndexName ) ) { JspException e = new JspException( ms_messages.getMessage( C_MESSAGE_DATASETROWS_STEPINDEXNAME_EMPTY ) ); TagUtils.getInstance().saveException( pageContext, e ); throw e; } if ( ( m_sequenceRestartStep == 0 && m_stepIndexName != null ) || ( m_sequenceRestartStep > 0 && m_stepIndexName == null ) ) { JspException e = new JspException( ms_messages.getMessage( C_MESSAGE_DATASETROWS_STEPINDEXNAME_SEQUENCERESTARTSTEP_COMBO_INVALID ) ); TagUtils.getInstance().saveException( pageContext, e ); throw e; } m_dataSet = ( DataSet ) dataSet; if ( m_dataSet != null && m_dataSet.size() > 0 ) { if ( m_dataSetRowName == null || "".equals( m_dataSetRowName ) ) { m_dataSetRowName = C_DATA_SET_ROW_NAME_DEFAULT; } publishData(); tagAction = EVAL_BODY_BUFFERED; } return tagAction; } /* * @see javax.servlet.jsp.tagext.IterationTag#doAfterBody() */ public int doAfterBody() throws JspException { int tagAction = SKIP_BODY; if ( bodyContent != null ) { TagUtils.getInstance().writePrevious( pageContext, bodyContent.getString() ); bodyContent.clearBody(); } if ( m_rowIndex < m_dataSet.size() - 1 ) { m_rowIndex = m_rowIndex + 1; publishData(); tagAction = EVAL_BODY_BUFFERED; } else { pageContext.removeAttribute( m_dataSetRowName ); if ( m_stepIndexName != null ) { pageContext.removeAttribute( m_stepIndexName ); } } return tagAction; } /** * * Publica a linha corrente do DataSet e, caso esteja especificado, o número * do passo determinado pelo número da linha corrente do DataSet. * */ private void publishData() { DataSetRow dataSetRow = m_dataSet.getRow( m_rowIndex ); pageContext.setAttribute( m_dataSetRowName, dataSetRow ); if ( m_stepIndexName != null ) { pageContext.setAttribute( m_stepIndexName, new Integer( m_rowIndex % m_sequenceRestartStep ) ); } } /* * @see javax.servlet.jsp.tagext.Tag#doEndTag() */ public int doEndTag() throws JspException { return ( EVAL_PAGE ); } /** * Libera os recursos utilizados pela custom tag. */ public void release() { super.release(); m_dataSet = null; m_dataSetRowName = null; m_name = null; m_property = null; m_rowIndex = 0; m_scope = null; } }
package controller; import algorithms.maze.Maze3d; import model.Model; import view.View; /** * This class is about displaying the board of the maze * According to one cross in a certain index * @author Tuval Lifshitz * */ public class DisplayCrossCommand implements Command { View v; Model m; Maze3d myMaze; String section; int index; public DisplayCrossCommand(View v, Model m){ this.v = v; this.m = m; myMaze = null; section = null; } @Override public void doCommand(){ int[][] toPrnt; if(myMaze == null || section == null){ v.printLineOnScreen("The requested maze was not found - please try again later with correct name."); } else if(index == -1){ v.printLineOnScreen("could not convert your index, please try again"); } else{ if(section.toLowerCase() == "x"){ toPrnt = myMaze.getCrossSectionByX(index); } else if( section.toLowerCase() == "y"){ toPrnt = myMaze.getCrossSectionByY(index); } else if(section.toLowerCase() == "z"){ toPrnt = myMaze.getCrossSectionByZ(index); }else{ v.printLineOnScreen("Please eneter a valid dimention(X/Y/Z) or index next time."); toPrnt = null; } //just making sure if(toPrnt != null){ v.PrintMazeCross(toPrnt); } } myMaze = null; section = null; } @Override public void setParams(String[] params) { myMaze = m.getMazeByName(params[3]); section = params[1]; try{ index = Integer.parseInt(params[2]); }catch(NumberFormatException nfe){ index = -1; } } }
package org.openmrs.module.jsslab.rest.v1_0.resource; import java.util.List; import org.openmrs.annotation.Handler; import org.openmrs.api.context.Context; import org.openmrs.logic.rule.definition.RuleDefinition; import org.openmrs.logic.rule.definition.RuleDefinitionService; //import org.openmrs.module.jsslab.impl.ExternalObjectsServiceImpl; import org.openmrs.module.webservices.rest.web.RequestContext; import org.openmrs.module.webservices.rest.web.RestConstants; import org.openmrs.module.webservices.rest.web.annotation.Resource; import org.openmrs.module.webservices.rest.web.representation.DefaultRepresentation; import org.openmrs.module.webservices.rest.web.representation.FullRepresentation; import org.openmrs.module.webservices.rest.web.representation.Representation; import org.openmrs.module.webservices.rest.web.resource.impl.DelegatingResourceDescription; import org.openmrs.module.webservices.rest.web.resource.impl.MetadataDelegatingCrudResource; import org.openmrs.module.webservices.rest.web.response.ResponseException; @Resource("ruledefinition") @Handler(supports = RuleDefinition.class, order = 0) public class RuleDefinitionResource extends MetadataDelegatingCrudResource<RuleDefinition> { @Override public RuleDefinition newDelegate() { return new RuleDefinition(); } @Override public RuleDefinition save(RuleDefinition delegate) { return Context.getService(RuleDefinitionService.class).saveRuleDefinition(delegate); } @Override public RuleDefinition getByUniqueId(String uniqueId) { List<RuleDefinition> ruleDefinitions = Context.getService(RuleDefinitionService.class).getAllRuleDefinitions(); for (RuleDefinition ruleDefinition : ruleDefinitions) { if (ruleDefinition.getUuid().equals(uniqueId)) { return ruleDefinition; } } // throw new NotImplementedException("getByUuid method not available for RuleDefinitions"); // return Context.getService(ExternalObjectsServiceImpl.class).getRuleDefinitionByUuid(uniqueId); return null; } @Override public void purge(RuleDefinition delegate, RequestContext context) throws ResponseException { if (delegate != null) { Context.getService(RuleDefinitionService.class).purgeRuleDefinition(delegate); } } @Override public DelegatingResourceDescription getRepresentationDescription(Representation rep) { DelegatingResourceDescription description = new DelegatingResourceDescription(); if (rep instanceof DefaultRepresentation) { // description.addProperty("uuid"); description.addProperty("ruleContent"); description.addProperty("language"); description.addProperty("retired"); description.addSelfLink(); description.addLink("full", ".?v="+RestConstants.REPRESENTATION_FULL); return description; } else if (rep instanceof FullRepresentation) { // description.addProperty("uuid"); description.addProperty("ruleContent"); description.addProperty("language"); description.addProperty("retired"); description.addSelfLink(); description.addProperty("auditInfo",findMethod("getAuditInfo")); return description; } return null; } }
package ro.ase.csie.cts.g1093.mironcristina.assignment3.prototype; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class TestPrototype { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void test() { fail("Not yet implemented"); } @Test public void testPrototypeDifferentObjects() throws CloneNotSupportedException { Server server1 = new Server("192.158. 1.38", 5000, 5); Server server2 = (Server) server1.clone(); if(server1 == server2) { fail("Server1 and server2 are the same object"); } assertNotEquals("Instances must be differnt", server1, server2); } @Test public void testPrototypeChangingOneField() throws CloneNotSupportedException { Server server1 = new Server("192.158. 1.38", 5000, 5); Server server2 = (Server) server1.clone(); server2.port = 8080; if(server1.getPort() == 8080) { fail("Changes made in server2 are reflected in server1"); } assertNotEquals(server1.getPort(), server2.getPort()); } }
package com.jianwuch.giaifu.module; import android.Manifest; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.jianwuch.giaifu.R; import com.jianwuch.giaifu.SearchActivity; import com.jianwuch.giaifu.base.BaseActivity; import com.jianwuch.giaifu.model.BaseHttpResult; import com.jianwuch.giaifu.model.HotWordsBean; import com.jianwuch.giaifu.model.HotWordsList; import com.jianwuch.giaifu.module.adapter.HotPagerAdapter; import com.jianwuch.giaifu.net.GifImagerRequest; import com.jianwuch.giaifu.net.RetrofitInstance; import com.jianwuch.giaifu.util.LogUtil; import com.tbruyelle.rxpermissions2.RxPermissions; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; import java.util.List; /** * 首页热门 * * @author jove.chen */ public class HotActivity extends BaseActivity { private static final String TAG = HotActivity.class.getSimpleName(); private TabLayout tabLayout; private ViewPager viewPager; private HotPagerAdapter mPageAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hot); initView(); RxPermissions rxPermissions = new RxPermissions(this); rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.INTERNET) .subscribe(granted -> { if (granted) { loadHotWords(); } else { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.hot_page_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.app_bar_search: startActivity(new Intent(this, SearchActivity.class)); return true; } return super.onOptionsItemSelected(item); } private void loadHotWords() { LogUtil.d(TAG, "开始获取数据"); RetrofitInstance.getInstance() .create(GifImagerRequest.class) .getHotWords() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<BaseHttpResult<HotWordsList>>() { @Override public void onSubscribe(Disposable d) { LogUtil.d(TAG, "onSubscribe"); } @Override public void onNext(BaseHttpResult<HotWordsList> listBaseHttpResult) { onGetHotWords(listBaseHttpResult.data.list); mPageAdapter = new HotPagerAdapter(getSupportFragmentManager(), listBaseHttpResult.data.list); viewPager.setAdapter(mPageAdapter); } @Override public void onError(Throwable e) { LogUtil.d(TAG, "error"); e.printStackTrace(); } @Override public void onComplete() { LogUtil.d(TAG, "onComplete"); } }); } private void onGetHotWords(List<HotWordsBean> list) { if (list == null || list.size() == 0) { return; } for (int i = 0; i < list.size(); i++) { LogUtil.d(TAG, list.get(i).query); tabLayout.addTab(tabLayout.newTab().setText(list.get(i).query)); } } private void initView() { tabLayout = findViewById(R.id.tabLayout); viewPager = findViewById(R.id.vp_main); tabLayout.setupWithViewPager(viewPager); } }
/* * Created on 14/11/2008 */ package com.citibank.ods.persistence.pl.dao.rdb.oracle; import com.citibank.ods.common.persistence.dao.rdb.oracle.BaseOracleDAO; import com.citibank.ods.persistence.pl.dao.BaseTplIpDocTransFinancDAO; /** * @author lfabiano * @since 14/11/2008 */ public abstract class BaseOracleTplIpDocTransFinancDAO extends BaseOracleDAO implements BaseTplIpDocTransFinancDAO { protected final String C_CUST_NBR = "CUST_NBR"; protected final String C_PRMNT_INSTR_CODE = "PRMNT_INSTR_CODE"; protected final String C_PRMNT_INSTR_TRF_DATA_CODE = "PRMNT_INSTR_TRF_DATA_CODE"; protected final String C_PRMNT_INSTR_TRF_SEQ_NBR = "PRMNT_INSTR_TRF_SEQ_NBR"; protected final String C_CHNNL_ATTD_TEXT = "CHNNL_ATTD_TEXT"; protected final String C_TRF_ACCT_TYPE = "TRF_ACCT_TYPE"; protected final String C_TRF_AMT = "TRF_AMT"; protected final String C_TRF_DATE = "TRF_DATE"; }
package com.kodilla.stream.array; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class ArrayOperationsTestSuite{ @Test void testGetAverage(){ //Given int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; double average = 5.5; //When double resultAverage = ArrayOperators.getAverage(numbers); //Then Assertions.assertEquals(average, resultAverage); } }
package com.zp.integration.common.errors; public interface ServiceErrors { String getCode(); String getMessage(); }
package com.duanc.mapper.base; import com.duanc.model.base.BaseUserRoleExample; import com.duanc.model.base.UserRoleKey; import java.util.List; import org.apache.ibatis.annotations.Param; public interface UserRoleMapper { int countByExample(BaseUserRoleExample example); int deleteByExample(BaseUserRoleExample example); int deleteByPrimaryKey(UserRoleKey key); int insert(UserRoleKey record); int insertSelective(UserRoleKey record); List<UserRoleKey> selectByExample(BaseUserRoleExample example); int updateByExampleSelective(@Param("record") UserRoleKey record, @Param("example") BaseUserRoleExample example); int updateByExample(@Param("record") UserRoleKey record, @Param("example") BaseUserRoleExample example); }
/* * Copyright 2002-2017 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.core.codec; import org.springframework.lang.Nullable; /** * Indicates an issue with decoding the input stream with a focus on content * related issues such as a parse failure. As opposed to more general I/O * errors, illegal state, or a {@link CodecException} such as a configuration * issue that a {@link Decoder} may choose to raise. * * <p>For example in server web application, a {@code DecodingException} would * translate to a response with a 400 (bad input) status while * {@code CodecException} would translate to 500 (server error) status. * * @author Rossen Stoyanchev * @since 5.0 * @see Decoder */ @SuppressWarnings("serial") public class DecodingException extends CodecException { /** * Create a new DecodingException. * @param msg the detail message */ public DecodingException(String msg) { super(msg); } /** * Create a new DecodingException. * @param msg the detail message * @param cause root cause for the exception, if any */ public DecodingException(String msg, @Nullable Throwable cause) { super(msg, cause); } }
package com.hristofor.mirchev.outfittery.challenge.stylists.dtos; import com.hristofor.mirchev.outfittery.challenge.stylists.repository.StylistStatus; import java.io.Serializable; import java.time.ZoneId; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; public class StylistDTO implements Serializable { private Long id; @NotBlank private String firstName; @NotBlank private String lastName; @NotNull private StylistStatus status; @NotNull private ZoneId timeZone; public StylistDTO() { } public Long getId() { return id; } public StylistDTO setId(Long id) { this.id = id; return this; } public String getFirstName() { return firstName; } public StylistDTO setFirstName(String firstName) { this.firstName = firstName; return this; } public String getLastName() { return lastName; } public StylistDTO setLastName(String lastName) { this.lastName = lastName; return this; } public StylistStatus getStatus() { return status; } public StylistDTO setStatus(StylistStatus status) { this.status = status; return this; } public ZoneId getTimeZone() { return timeZone; } public StylistDTO setTimeZone(ZoneId timeZone) { this.timeZone = timeZone; return this; } }
package com.tdr.registrationv3.ui.fragment.register; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.parry.utils.code.SPUtils; import com.tdr.registrationv3.R; import com.tdr.registrationv3.adapter.InsuranceAdapter; import com.tdr.registrationv3.bean.BillBean; import com.tdr.registrationv3.bean.BlcakCarBean; import com.tdr.registrationv3.bean.InsuranceBean; import com.tdr.registrationv3.bean.InsuranceInfoBean; import com.tdr.registrationv3.bean.LableListBean; import com.tdr.registrationv3.bean.PhotoConfigBean; import com.tdr.registrationv3.bean.PhotoListBean; import com.tdr.registrationv3.bean.RegisterPutBean; import com.tdr.registrationv3.bean.VehicleConfigBean; import com.tdr.registrationv3.constants.BaseConstants; import com.tdr.registrationv3.http.utils.DdcResult; import com.tdr.registrationv3.service.impl.car.RegisterImpl; import com.tdr.registrationv3.service.presenter.RegisterPresenter; import com.tdr.registrationv3.ui.activity.car.RegisterMainActivity; import com.tdr.registrationv3.ui.fragment.base.LoadingBaseFragment; import com.tdr.registrationv3.utils.ConfigUtil; import com.tdr.registrationv3.utils.ToastUtil; import com.tdr.registrationv3.utils.UIUtils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import butterknife.BindView; import butterknife.OnClick; public class RegisterInsuranceFragment extends LoadingBaseFragment<RegisterImpl> implements RegisterPresenter.View { @BindView(R.id.com_title_back) RelativeLayout comTitleBack; @BindView(R.id.text_title) TextView textTitle; @BindView(R.id.com_title_setting_iv) ImageView comTitleSettingIv; @BindView(R.id.com_title_setting_tv) TextView comTitleSettingTv; @BindView(R.id.insurance_rv) RecyclerView insuranceRv; @BindView(R.id.insurance_p_no) TextView insurancePNo; @BindView(R.id.insurance_p_gr) TextView insurancePGr; @BindView(R.id.insurance_p_qy) TextView insurancePQy; @BindView(R.id.insurance_kp_ll) LinearLayout insuranceKpLl; @BindView(R.id.button_next) TextView buttonNext; @BindView(R.id.empty_iv) ImageView emptyIv; @BindView(R.id.empty_tv) TextView emptyTv; @BindView(R.id.empty_data_rl) RelativeLayout emptyDataRl; private InsuranceAdapter insuranceAdapter; private int vehicleType; private List<InsuranceBean> adapterList; @Override protected RegisterImpl setPresenter() { return new RegisterImpl(); } @Override protected void loadData() { setState(BaseConstants.STATE_SUCCESS); getInsuranceData(); } private void getInsuranceData() { try { zProgressHUD.show(); int systemId = SPUtils.getInstance().getInt(BaseConstants.City_systemID, -100); vehicleType = ((RegisterMainActivity) RegisterInsuranceFragment.this.getActivity()).vehicleType; String buyDate = ((RegisterMainActivity) RegisterInsuranceFragment.this.getActivity()).registerPutBean.getRegisterTime(); Map<String, Object> map = new HashMap<>(); map.put("subsystemId", systemId); map.put("vehicleType", vehicleType); map.put("insuranceMode", 0); map.put("buyDate", buyDate); mPresenter.getInsurance(getRequestBody(map)); } catch (Exception e) { e.printStackTrace(); } } @Override protected int getLayoutId() { return R.layout.fragment_register_insurance; } @Override protected void initView() { textTitle.setText("备案登记"); comTitleBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { ((RegisterMainActivity) RegisterInsuranceFragment.this.getActivity()).setVpCurrentItem(1); } }); initRv(); emptyTv.setText("暂无数据,点击重新加载"); emptyIv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getInsuranceData(); } }); initBill(); } private int insurance_bill = 1;//默认不开票 private void initBill() { insuranceKpLl.setVisibility(View.GONE); BillBean billBean = ConfigUtil.getBill(); if (billBean == null) { return; } if (billBean.isIsBill()) { insuranceKpLl.setVisibility(View.VISIBLE); setBillType(billBean.getBillType()); } } private void initRv() { List<InsuranceBean> insuranceBeans = new ArrayList<>(); insuranceRv.setLayoutManager(new LinearLayoutManager(this.getContext())); insuranceAdapter = new InsuranceAdapter(RegisterInsuranceFragment.this.getContext(), insuranceBeans, insuranceRv); insuranceRv.setAdapter(insuranceAdapter); } @OnClick({R.id.insurance_p_no, R.id.insurance_p_gr, R.id.insurance_p_qy, R.id.button_next}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.insurance_p_no: setBillType(1); break; case R.id.insurance_p_gr: setBillType(2); break; case R.id.insurance_p_qy: setBillType(3); break; case R.id.button_next: putData(); break; } } private void setBillType(int type) { switch (type) { case 1: insurancePNo.setTextColor(UIUtils.getColor(R.color.module_main)); insurancePGr.setTextColor(UIUtils.getColor(R.color.module_text_3)); insurancePQy.setTextColor(UIUtils.getColor(R.color.module_text_3)); insurance_bill = 1; break; case 2: insurancePNo.setTextColor(UIUtils.getColor(R.color.module_text_3)); insurancePGr.setTextColor(UIUtils.getColor(R.color.module_main)); insurancePQy.setTextColor(UIUtils.getColor(R.color.module_text_3)); insurance_bill = 2; break; case 3: insurancePNo.setTextColor(UIUtils.getColor(R.color.module_text_3)); insurancePGr.setTextColor(UIUtils.getColor(R.color.module_text_3)); insurancePQy.setTextColor(UIUtils.getColor(R.color.module_main)); insurance_bill = 3; break; } } private void putData() { try { adapterList = insuranceAdapter.getData(); for (InsuranceBean insuranceBean : adapterList) { if (insuranceBean.getIsChoose() == 1) { boolean isHaveCheck = false; for (InsuranceBean.PackagesBean packagesBean : insuranceBean.getPackages()) { if (packagesBean.isCheck()) { isHaveCheck = true; } } if (!isHaveCheck) { ToastUtil.showWX("请选择" + insuranceBean.getName()); return; } } } showSubmitRequestDialog(); } catch (Exception e) { e.printStackTrace(); } } @Override public void checkPlateNumberSuccess() { } @Override public void checkPlateNumberFail(String msg) { setState(BaseConstants.STATE_SUCCESS); } @Override public void getInsuranceSuccess(List<InsuranceBean> list) { zProgressHUD.dismiss(); if (list != null && list.size() > 0) { emptyDataRl.setVisibility(View.GONE); } else { emptyDataRl.setVisibility(View.VISIBLE); } insuranceAdapter.setNewData(list); } @Override public void getInsuranceFail(String msg) { zProgressHUD.dismiss(); setState(BaseConstants.STATE_SUCCESS); showCustomWindowDialog("服务提示", msg, true); emptyDataRl.setVisibility(View.VISIBLE); } @Override public void changeFail(String msg) { } @Override public void changeSuccess(String msg) { } @Override public void checkShelvesNumberFail(String msg) { } @Override public void checkShelvesNumberSuccess(List<BlcakCarBean> msg) { } @Override public void loadingSuccessForData(DdcResult mData) { setState(BaseConstants.STATE_SUCCESS); showCustomWindowDialog("服务提示", mData.getMsg(), true); } @Override public void loadingFail(String msg) { showCustomWindowDialog("服务提示", msg, false, true); setState(BaseConstants.STATE_SUCCESS); zProgressHUD.dismiss(); } @Override protected void submitRequestData() { RegisterPutBean registerBean = ((RegisterMainActivity) RegisterInsuranceFragment.this.getActivity()).registerPutBean; int subsystemId = SPUtils.getInstance().getInt(BaseConstants.City_systemID); Map<String, Object> map = new HashMap<>(); map.put("subsystemId", subsystemId); map.put("billType", insurance_bill); /*以下为baseInfo(基本信息)*/ Map<String, Object> baseInfoMap = new HashMap<>(); baseInfoMap.put("vehicleType", vehicleType); baseInfoMap.put("vehicleBrand", registerBean.getRegisterBrandCode()); baseInfoMap.put("vehicleBrandName", registerBean.getRegisterBrand()); baseInfoMap.put("colorId", registerBean.getRegisterColor1Id()); baseInfoMap.put("colorName", registerBean.getRegisterColor1Name()); baseInfoMap.put("colorSecondId", registerBean.getRegisterColor2Id()); baseInfoMap.put("colorSecondName", registerBean.getRegisterColor2Name()); baseInfoMap.put("plateNumber", registerBean.getRegisterPlate()); baseInfoMap.put("plateType", "1"); map.put("baseInfo", baseInfoMap); /*以下为labelInfo(标签信息)*/ Map<String, Object> labelInfoMap = new HashMap<>(); List<VehicleConfigBean.VehicleLicenseInfoListBean.VehicleNbLableConfigListBean> lableList = registerBean.getLableList(); List<LableListBean> lableListBeanList = new ArrayList<>(); for (VehicleConfigBean.VehicleLicenseInfoListBean.VehicleNbLableConfigListBean bean : lableList) { LableListBean lableBean = new LableListBean(); String lablenumber = bean.getEditValue(); lableBean.setIndex(bean.getIndex()); lableBean.setLableType(lablenumber.substring(0, 4)); lableBean.setLableNumber(lablenumber); lableBean.setLabelName(bean.getLableName()); lableListBeanList.add(lableBean); } labelInfoMap.put("lableList", lableListBeanList); labelInfoMap.put("engineNumber", registerBean.getRegisterElectrical()); labelInfoMap.put("shelvesNumber", registerBean.getRegisterFrame()); map.put("labelInfo", labelInfoMap); /*以下为buyInfo(车辆购买信息)*/ Map<String, Object> buyInfoMap = new HashMap<>(); buyInfoMap.put("buyDate", registerBean.getRegisterTime()); buyInfoMap.put("buyPrice", registerBean.getRegisterPrice()); List<PhotoConfigBean.PhotoTypeInfoListBean> photoList = registerBean.getPhotoList(); List<PhotoListBean> photoListBeans = new ArrayList<>(); for (PhotoConfigBean.PhotoTypeInfoListBean bean : photoList) { PhotoListBean photoBean = new PhotoListBean(); photoBean.setIndex(bean.getPhotoIndex()); photoBean.setPhotoType(bean.getPhotoType()); photoBean.setPhoto(bean.getPhotoId()); photoBean.setPhotoName(bean.getPhotoName()); photoListBeans.add(photoBean); } buyInfoMap.put("photoList", photoListBeans); map.put("buyInfo", buyInfoMap); /*以下为ownerInfo(车主信息)*/ Map<String, Object> ownerInfoMap = new HashMap<>(); ownerInfoMap.put("ownerName", registerBean.getPeopleName()); ownerInfoMap.put("cardType", registerBean.getPeopleCardType()); ownerInfoMap.put("cardId", registerBean.getPeopleCardNum()); ownerInfoMap.put("cardName", registerBean.getCardName()); ownerInfoMap.put("phone1", registerBean.getPeoplePhone1()); ownerInfoMap.put("phone2", registerBean.getPeoplePhone2()); ownerInfoMap.put("residentAddress", registerBean.getPeopleAddr()); ownerInfoMap.put("remark", registerBean.getPeopleRemark()); map.put("ownerInfo", ownerInfoMap); /*以下为insuranceInfo(保险信息)*/ Map<String, Object> packagesInfo = new HashMap<>(); List<InsuranceInfoBean> infoBeanList = new ArrayList<>(); for (InsuranceBean bean : adapterList) { for (InsuranceBean.PackagesBean packagesBean : bean.getPackages()) { if (packagesBean.isCheck()) { infoBeanList.add(new InsuranceInfoBean(bean.getId(), packagesBean.getId())); } } } packagesInfo.put("packages", infoBeanList); map.put("insuranceInfo", packagesInfo); zProgressHUD.show(); /*提交接口*/ mPresenter.register(getRequestBody(map)); } }
package de.varylab.discreteconformal.math; import de.jreality.math.Rn; import de.jtem.mfc.field.Complex; public class CP1 { protected static double[] sphereToParaboloid = { 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, -1, 0, 0, 1 }; protected static double[] paraboloidToSphere = { 1, 0, 0, -1, 0, 2, 0, 0, 0, 0, 2, 0, 1, 0, 0, 1 }; protected static double[] zxyToxyz = { 0,1,0,0, 0,0,1,0, 1,0,0,0, 0,0,0,1 }; public static double[] convertPSL2CToSO31(double[] dst, Complex[] lft) { if (dst == null) { dst = new double[16]; } double ax = lft[0].re; double ay = lft[0].im; double bx = lft[1].re; double by = lft[1].im; double cx = lft[2].re; double cy = lft[2].im; double dx = lft[3].re; double dy = lft[3].im; double[] tmp = new double[16]; tmp[0] = ax*ax + ay*ay; tmp[1] = 2*(ax*bx+ay*by); tmp[2] = 2*(ax*by-ay*bx); tmp[3] = bx*bx+by*by; tmp[4] = ax*cx+ay*cy; tmp[5] = bx*cx + by*cy + ax*dx + ay*dy; tmp[6] = by*cx - bx*cy - ay*dx + ax*dy; tmp[7] = bx*dx + by*dy; tmp[8] = ay*cx - ax*cy; tmp[9] = by*cx - bx*cy + ay*dx - ax*dy; tmp[10]= -(bx*cx) - by*cy + ax*dx + ay*dy; tmp[11]= by*dx - bx*dy; tmp[12]= cx*cx+cy*cy; tmp[13]= 2*(cx*dx + cy*dy); tmp[14]= 2*(-cy*dx + cx*dy); tmp[15]= dx*dx+dy*dy; Rn.conjugateByMatrix(dst, tmp, Rn.times(null, zxyToxyz, paraboloidToSphere)); return dst; } public static Complex[] projectivity(Complex[] dst, Complex z1, Complex z2, Complex z3, Complex w1, Complex w2, Complex w3) { //TODO make sure inputs are valid Complex[] m1 = standardProjectivity(null, z1, z2, z3); Complex[] m2 = standardProjectivity(null, w1, w2, w3); Complex[] im2 = Cn.invert(null, m2); dst = Cn.times(dst, im2, m1); return dst; } /** * Generate the Moebius tform taking (z1,z2,z3) to (0, 1, infinity) * @param m * @param z1 * @param z2 * @param z3 * @return */ public static Complex[] standardProjectivity(Complex[] m, Complex z1, Complex z2, Complex z3) { if (m == null || m.length != 4) { m = new Complex[4]; } for (int i = 0; i<4; ++i) { if (m[i] == null) m[i] = new Complex(); } if (z1.isInfinite()) { m[0].assign(0,0); m[1].assignMinus(z2, z3); m[2].assign(1,0); m[3].assignMinus(z3); } else if (z2.isInfinite()) { m[0].assign(1,0); m[1].assignMinus(z1); m[2].assign(1,0); m[3].assignMinus(z3); } else if (z3.isInfinite()) { m[0].assign(1,0); m[1].assignMinus(z1); m[2].assign(0,0); m[3].assignMinus(z2, z1); } else { m[0].assignMinus(z2, z3); m[1].assignTimes(z1.neg(), m[0]); m[2].assignMinus(z2, z1); m[3].assignTimes(z3.neg(), m[2]); } // Cn.normalize(m,m); return m; } }
package com.webproject.compro.web.controllers; import com.webproject.compro.utility.Converter; import com.webproject.compro.web.enums.GetItemResult; import com.webproject.compro.web.services.ApiService; import com.webproject.compro.web.vos.*; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; @RestController @RequestMapping(value = "/apis", method = RequestMethod.POST) public class ApiController { private final ApiService apiService; @Autowired public ApiController(ApiService apiService) { this.apiService = apiService; } // 아이템 목록 불러오기 @ResponseBody @RequestMapping(value = "/get-item", produces = MediaType.APPLICATION_JSON_VALUE) public String getProduct(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "page", defaultValue = "1") String pageString) throws SQLException { int page = Converter.stringToInt(pageString, -1); GetItemVo getItemVo = this.apiService.getItem(page); JSONArray jsonItems = new JSONArray(); for (ItemVo itemVo : getItemVo.getItemVos()) { JSONObject jsonItem = new JSONObject(); jsonItem.put("itemIndex", itemVo.getItemIndex()); jsonItem.put("itemCode", itemVo.getItemCode()); jsonItem.put("itemName", itemVo.getItemName()); jsonItem.put("itemColor", itemVo.getItemColor()); jsonItem.put("itemSize", itemVo.getItemSize()); jsonItem.put("itemPrice", itemVo.getItemPrice()); jsonItem.put("imageIndex", itemVo.getImageIndex()); jsonItems.put(jsonItem); } JSONObject jsonObject = new JSONObject(); jsonObject.put("startPage", getItemVo.getStartPage()); jsonObject.put("endPage", getItemVo.getEndPage()); jsonObject.put("requestPage", getItemVo.getRequestPage()); jsonObject.put("items", jsonItems); response.setCharacterEncoding("UTF-8"); return jsonObject.toString(4); } // 아이템 업로드 @RequestMapping(value = "/upload-item", produces = MediaType.TEXT_PLAIN_VALUE) public void uploadItem(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "up_file") MultipartFile itemImage, @RequestParam(name = "up_name", defaultValue = "") String itemName, @RequestParam(name = "up_code", defaultValue = "") String itemCode, @RequestParam(name = "up_color", defaultValue = "") String itemColor, @RequestParam(name = "up_size", defaultValue = "") String itemSize, @RequestParam(name = "up_price", defaultValue = "") String itemPrice) throws SQLException, IOException { UploadItemVo uploadItemVo = new UploadItemVo(itemName, itemCode, itemColor, itemSize, itemPrice, itemImage); this.apiService.uploadItem(uploadItemVo); // 파일 형식이 맞지 않는다면, IMAGE_NOT_ALLOWED response.getWriter().print("SUCCESS"); } // 게시판 목록 불러오기 @ResponseBody @RequestMapping(value = "/get-article", produces = MediaType.APPLICATION_JSON_VALUE) public String getArticle(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "page", defaultValue = "1") String pageString) throws SQLException { int page = Converter.stringToInt(pageString, -1); GetArticleVo getArticleVo = this.apiService.getArticle(page); JSONArray jsonArticles = new JSONArray(); for (ArticleVo articleVo : getArticleVo.getArticleVos()) { JSONObject jsonArticle = new JSONObject(); jsonArticle.put("index", articleVo.getArticleIndex()); jsonArticle.put("title", articleVo.getTitle()); jsonArticle.put("articleName", articleVo.getArticleName()); jsonArticle.put("writtenAt", articleVo.getWrittenAt()); jsonArticle.put("hit", articleVo.getHit()); jsonArticle.put("content", articleVo.getContent()); jsonArticles.put(jsonArticle); } JSONObject jsonObject = new JSONObject(); jsonObject.put("startPage", getArticleVo.getStartPage()); jsonObject.put("endPage", getArticleVo.getEndPage()); jsonObject.put("requestPage", getArticleVo.getRequestPage()); jsonObject.put("articles", jsonArticles); response.setCharacterEncoding("UTF-8"); return jsonObject.toString(4); } // 게시판 글 등록하기 @RequestMapping(value = "/write-article", produces = MediaType.APPLICATION_JSON_VALUE) public void write(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "article_title", defaultValue = "") String title, @RequestParam(name = "article_kind", defaultValue = "") String kind, @RequestParam(name = "article_content", defaultValue = "") String content) throws SQLException, IOException { WriteArticleVo writeArticleVo = new WriteArticleVo(title, kind, content); this.apiService.writeArticle(writeArticleVo); response.getWriter().print("SUCCESS"); } // FAQ 목록 불러오기 @ResponseBody @RequestMapping(value = "/get-faq", produces = MediaType.APPLICATION_JSON_VALUE) public String getFaqs(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "page", defaultValue = "1") String pageString) throws SQLException { int page = Converter.stringToInt(pageString, 1); GetFaqVo getFaqVo = this.apiService.getFaq(page); JSONArray jsonFaqs = new JSONArray(); for (FaqVo faqVo : getFaqVo.getFaqVos()) { JSONObject jsonFaq = new JSONObject(); jsonFaq.put("answerTitle", faqVo.getAnswerTitle()); jsonFaq.put("answerContent", faqVo.getAnswerContent()); jsonFaqs.put(jsonFaq); } JSONObject jsonObject = new JSONObject(); jsonObject.put("requestPage", getFaqVo.getRequestPage()); jsonObject.put("faqs", jsonFaqs); response.setCharacterEncoding("UTF-8"); return jsonObject.toString(4); } // FAQ 검색 @ResponseBody @RequestMapping(value = "/search", produces = MediaType.APPLICATION_JSON_VALUE) public String searchGet(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "page", defaultValue = "") String page, @RequestParam(name = "searchWord", defaultValue = "") String searchWord) throws SQLException { SearchVo searchVo = new SearchVo(page, searchWord); ArrayList<FaqVo> faqVos = this.apiService.search(searchVo); JSONArray jsonFaqs = new JSONArray(); for (FaqVo faqVo : faqVos) { JSONObject jsonFaq = new JSONObject(); jsonFaq.put("answerTitle", faqVo.getAnswerTitle()); jsonFaq.put("answerContent", faqVo.getAnswerContent()); jsonFaqs.put(jsonFaq); } JSONObject jsonObject = new JSONObject(); jsonObject.put("requestPage", searchVo.getPage()); jsonObject.put("faqs", jsonFaqs); response.setCharacterEncoding("UTF-8"); return jsonObject.toString(4); } // 장바구니에 담기 @RequestMapping(value = "/go-basket", produces = MediaType.TEXT_PLAIN_VALUE) public void goBasket(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "pr_color", defaultValue = "") String basketItemColor, @RequestParam(name = "pr_size", defaultValue = "") String basketItemSize, @RequestParam(name = "pr_count", defaultValue = "") String basketItemCount, @RequestParam(name = "pr_name", defaultValue = "") String itemName, @RequestParam(name = "pr_index", defaultValue = "") String itemIndex, @RequestParam(name = "pr_code", defaultValue = "") String itemCode, @RequestParam(name = "pr_price", defaultValue = "") String itemPrice ) throws IOException, SQLException { UserVo userVo = Converter.getUserVo(request); if (userVo != null) { BasketItemVo basketItemVo = new BasketItemVo(itemIndex, itemName, itemCode, itemPrice, basketItemColor, basketItemSize, basketItemCount); GetItemResult getItemResult = this.apiService.getBasketItem(basketItemVo, userVo); response.getWriter().print(getItemResult.name()); } else { response.getWriter().print("denied"); } } // 장바구니 목록 가져오기 @ResponseBody @RequestMapping(value = "/get-basket-item", produces = MediaType.APPLICATION_JSON_VALUE) public String getItem(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "page", defaultValue = "") String pageString) throws SQLException { UserVo userVo = Converter.getUserVo(request); int page = Converter.stringToInt(pageString, -1); GetBasketItemVo getBasketItemVo = this.apiService.getBasketItemList(page, userVo); JSONArray jsonBasketItems = new JSONArray(); for (BasketItemVo basketItemVo : getBasketItemVo.getBasketItemVos()) { JSONObject jsonBasket = new JSONObject(); jsonBasket.put("basketItemIndex", basketItemVo.getBasketIndex()); jsonBasket.put("basketItemName", basketItemVo.getItemName()); jsonBasket.put("basketItemColor", basketItemVo.getBasketItemColor()); jsonBasket.put("basketItemSize", basketItemVo.getBasketItemSize()); jsonBasket.put("basketItemCount", basketItemVo.getBasketItemCount()); jsonBasket.put("basketItemPrice", basketItemVo.getItemPrice()); jsonBasketItems.put(jsonBasket); } JSONObject jsonObject = new JSONObject(); jsonObject.put("startPage", getBasketItemVo.getStartPage()); jsonObject.put("endPage", getBasketItemVo.getEndPage()); jsonObject.put("requestPage", getBasketItemVo.getRequestPage()); jsonObject.put("basketItems", jsonBasketItems); response.setCharacterEncoding("UTF-8"); return jsonObject.toString(4); } //장바구니 목록 삭제 @RequestMapping(value = "delete-basket-item", produces = MediaType.TEXT_PLAIN_VALUE) public void deleteBasketItem(HttpServletRequest request, HttpServletResponse response, @RequestParam(name = "basketItemIndex", defaultValue = "") String basketItemIndex) throws SQLException, IOException { UserVo userVo = Converter.getUserVo(request); DeleteBasketItemVo deleteBasketItemVo = new DeleteBasketItemVo(basketItemIndex); if (!deleteBasketItemVo.isNormalized()) { response.getWriter().print("FAILURE"); } else { this.apiService.deleteBasketItem(deleteBasketItemVo, userVo); response.getWriter().print("SUCCESS"); } } }
import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Created by Ali on 5/18/2017 AD. */ public class Reshteh { private String name; private Map<Reshteh, Minor> minors = new HashMap<Reshteh, Minor>(); private ArrayList<Gerayesh> gerayeshHa = new ArrayList<Gerayesh>(); public Reshteh(String name) { Gerayesh defaultGerayesh = new Gerayesh("default"); defaultGerayesh.setReshtehName(name); this.name = name; this.gerayeshHa.add(defaultGerayesh); } public void addGerayesh(Gerayesh gerayesh) { gerayesh.setReshtehName(name); this.gerayeshHa.add(gerayesh); } public String getName(){ return this.name; } public boolean equals(Reshteh reshteh) { return this.name.equals(reshteh.name); } public void addMinor(Reshteh destReshteh, Minor minor){ this.minors.put(destReshteh, minor); } public Minor getMinorForReshteh(Reshteh destReshteh){ return minors.get(destReshteh); } public boolean hasGerayesh(String gerayeshName){ for (Gerayesh gerayesh : gerayeshHa) { if (gerayesh.getName().equals(gerayeshName)) { return true; } } return false; } public Gerayesh getGerayeshByName(String gerayeshName) { for (Gerayesh gerayesh : gerayeshHa) { if (gerayesh.getName().equals(gerayeshName)) { return gerayesh; } } return null; } }
public class ArraySum1 { public static int[] arrSum(int arr1[],int arr2[],int strt,int[] res) { if(arr1.length>arr2.length) { if(strt==arr1.length) return res; if(strt<arr2.length) { res[strt]=arr1[strt]+arr2[strt]; arrSum(arr1,arr2,strt+1,res); } else { res[strt]=arr1[strt]; arrSum(arr1,arr2,strt+1,res); } return res; } else { if(strt==arr2.length) return res; else if(strt<arr1.length) { res[strt]=arr1[strt]+arr2[strt]; arrSum(arr1,arr2,strt+1,res); } else { res[strt]=arr2[strt]; arrSum(arr1,arr2,strt+1,res); } return res; } } public static void main(String[]args) { int arr1[]={23,5,7,2,7,87}; int arr2[]={4,67,2,8}; int n=Math.max(arr1.length,arr2.length); int res[]=new int[n]; arrSum(arr1,arr2,0,res); for(int i:res) System.out.print(i+" , "); } }
package com.hzero.order.domain.repository; import com.hzero.order.api.controller.dto.OrderReturnDTO; import com.hzero.order.domain.entity.SoHeader; import org.hzero.mybatis.base.BaseRepository; import java.util.List; /** * 资源库 * */ public interface SoHeaderRepository extends BaseRepository<SoHeader> { void updateStatusBySoHeaderId(SoHeader soHeader); List<OrderReturnDTO> selectBySoHeaderId(Long soHeaderId); }
package p0400; import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JColorChooser; import p0200.P0215CP; import java.awt.Color; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; public class P0450 extends JFrame implements ActionListener, MouseListener { private JButton btnEpines; private JPanel pnlDrawing; private void initGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel pnlControl = new JPanel(); pnlControl.setBackground(Color.WHITE); getContentPane().add(pnlControl, BorderLayout.WEST); pnlControl.setLayout(new BoxLayout(pnlControl, BoxLayout.Y_AXIS)); JLabel lblEpines = new JLabel("Epines"); pnlControl.add(lblEpines); btnEpines = new JButton("Epines"); btnEpines.setBackground(new Color(0, 120, 0)); btnEpines.addActionListener(this); pnlControl.add(btnEpines); pnlDrawing = new JPanel(); pnlDrawing.setLayout(null); pnlDrawing.addMouseListener(this); getContentPane().add(pnlDrawing); setSize(550, 400); } public P0450() { super("P0450"); initGUI(); } public static void main(String[] args) { P0450 frame = new P0450(); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { JButton btnTmp = (JButton) e.getSource(); Color color = JColorChooser.showDialog(this, "Choisir la couleur des épines", btnTmp.getBackground()); if(color != null){ btnTmp.setBackground(color); } } /** * Calcule les dimensions et positions du panel en fonction des coordonnées du clic * @param x coordonnée en x du clic * @param y coordonnée en y du clic * @param ref hauteur totale du conteneur * @return */ private Rectangle getBounds(int x, int y, int ref) { final int h1 = 35; final int h2 = 150; final int delta = h2 - h1; final int h = h1 + delta * y / ref; final int w = h * 4 / 5; Rectangle r = new Rectangle(x - w / 2, y - h / 2, w, h); return r; } @Override public void mouseClicked(MouseEvent e) { //Crée un sapin P0215CP pnlSapin = new P0215CP(btnEpines.getBackground()); pnlSapin.setBounds(getBounds(e.getX(), e.getY(), pnlDrawing.getHeight())); pnlDrawing.add(pnlSapin); pnlSapin.setOpaque(false); pnlDrawing.repaint(); } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.context.annotation.ScopedProxyMode; import org.springframework.stereotype.Component; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; import javax.servlet.http.HttpSession; import java.io.Serializable; @SessionAttributes("demoSession") public class DemoSession{ public String step(@ModelAttribute ("demoSession") Demo demo){ //........ } }
package edu.mycourses.adt.basic.analysis; public class ClosestPair { public static void main(String[] args) { // TODO Auto-generated method stub } }
package com.dqm.utils; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.Arrays; /** * Created by dqm on 2018/8/31. */ public class IpUtil { /** * 将ipv6转成v4 * @param ipv6 * @return int可能为负数 * @throws UnknownHostException */ public static String v6Tov4(byte[] ipv6) throws UnknownHostException { byte[] src = Arrays.copyOfRange(ipv6, 12,16); return (src[0] & 0xff) + "." + (src[1] & 0xff) + "." + (src[2] & 0xff) + "." + (src[3] & 0xff); } /** * 将ip字符串转为byte数组,注意:ip不可以是域名,否则会进行域名解析 * @param ip * @return byte[] * @throws UnknownHostException */ public static byte[] ipToBytes(String ip) throws UnknownHostException { byte[] ipv6 = new byte[16]; byte [] tmp = InetAddress.getByName(ip).getAddress(); ByteBuffer byteBuffer = ByteBuffer.allocate(16).put(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}).put(tmp); byteBuffer.position(0); byteBuffer.get(ipv6); return ipv6; } public static final void main(String[] args) throws UnknownHostException { byte[] t = new byte[] { (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0xFF, (byte)0xFF, (byte)0x0A, (byte)0x00, (byte)0x00, (byte)0x02 }; System.out.println(v6Tov4(t)); System.out.println(ByteUtil.bytesToHexString(ipToBytes("183.193.213.50"))); } }
package com.beike.core.service.trx; import java.util.HashMap; import java.util.Map; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.beike.common.enums.trx.VoucherType; import com.beike.util.EnumUtil; /** * @Title: VoucherSendFactory.java * @Package com.beike.core.service.trx * @Description: 发送凭证码服务类工厂(生产不同发送渠道的凭证发送服务实现类) * @date 3 8, 2012 11:24:04 AM * @author wh.cheng * @version v1.0 */ @Service("voucherSendFactory") public class VoucherSendFactory { private static Map<String, VoucherSendService> serviceMap = null; @Resource(name = "platformVoucherSendService") private VoucherSendService platformVoucherSendService; @Resource(name = "merchantApiVoucherSendService") private VoucherSendService merchantApiVoucherSendService; @Resource(name = "twoDimVoucherSendService") private VoucherSendService twoDimVoucherSendService; @Resource(name = "filmApiVoucherSendService") private VoucherSendService filmApiVoucherSendService; public VoucherSendService getVoucherSendService(VoucherType voucherType) { if (serviceMap == null || serviceMap.isEmpty()) { serviceMap = new HashMap<String, VoucherSendService>(); serviceMap.put(EnumUtil.transEnumToString(VoucherType.PLATFORM), // 千品平台自有凭证码(含商户上传到千品平台的凭证码) platformVoucherSendService); serviceMap.put( EnumUtil.transEnumToString(VoucherType.MERCHANT_API), // 通过商家API,请求商家发送的凭证码 merchantApiVoucherSendService); serviceMap.put(EnumUtil.transEnumToString(VoucherType.TWO_DIM), // 二维码 twoDimVoucherSendService); serviceMap.put(EnumUtil.transEnumToString(VoucherType.FILM_API), // 网票网发码 filmApiVoucherSendService); } return serviceMap.get(EnumUtil.transEnumToString(voucherType)); } }
package aufgabenserie1.mitti.ch; import javax.swing.JButton; public class MyButton extends JButton { int counter; public MyButton(String name){ super(name); counter = 0; } public void count(){ counter++; } public int getCount(){ return counter; } }
package dwz.framework.identity.impl; import java.io.Serializable; import dwz.framework.identity.Identity; /** * @Author: LCF * @Date: 2020/1/8 16:40 * @Package: dwz.framework.identity.impl */ public class SessionIdentity implements Identity { private Serializable accessToken = null; public SessionIdentity(Serializable accessToken) { this.accessToken = accessToken; } public Serializable getAccessToken() { return this.accessToken; } public void setAccessToken(Serializable accessToken) { this.accessToken = accessToken; } }
package org.fonuhuolian.videoplay; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; public abstract class SimpleSingleLayoutAdapter<T> extends RecyclerView.Adapter<RecyclerViewHolder> implements View.OnClickListener, View.OnLongClickListener { private List<T> mDatas; private LayoutInflater mInflater; private int mLayoutResId; private RecyclerView mRecyclerView; private OnItemClickListener mListener; private OnItemLongClickListener mLongListener; private Context mContext; public SimpleSingleLayoutAdapter(Context context, int layoutResId) { this.mInflater = (LayoutInflater) context.getSystemService("layout_inflater"); this.mLayoutResId = layoutResId; this.mDatas = new ArrayList(); this.mContext = context; } public SimpleSingleLayoutAdapter(Context context, int layoutResId, List<T> list) { this(context, layoutResId); this.addData(list); } public void addData(List<T> data) { if (data != null) { this.mDatas.addAll(data); this.notifyDataSetChanged(); } } public int getItemCount() { return this.mDatas.size(); } @NonNull public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = this.mInflater.inflate(this.mLayoutResId, parent, false); itemView.setOnClickListener(this); itemView.setOnLongClickListener(this); return new RecyclerViewHolder(itemView); } public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { this.bind(holder, this.mDatas.get(position), position); } public void clearAll() { this.mDatas.clear(); this.notifyDataSetChanged(); } public abstract void bind(RecyclerViewHolder var1, T var2, int var3); public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); this.mRecyclerView = recyclerView; } public void onClick(View v) { int position = this.mRecyclerView.getChildAdapterPosition(v); T t = this.mDatas.get(position); if (this.mListener != null) { this.mListener.onClick(t, position, v); } } public boolean onLongClick(View view) { int position = this.mRecyclerView.getChildAdapterPosition(view); T t = this.mDatas.get(position); if (this.mLongListener != null) { this.mLongListener.onLongClick(t, position, view); } return this.mLongListener != null; } public List<T> getAttachDatas() { return this.mDatas; } public Context getAttachContext() { return this.mContext; } public void setOnItemClickListener(OnItemClickListener<T> listener) { this.mListener = listener; } public void setOnItemLongClickListener(OnItemLongClickListener<T> listener) { this.mLongListener = listener; } }
package com.deepakm.kstreams.echo; import com.deepakm.kstreams.ConfigKeys; import com.deepakm.kstreams.StreamingClient; import com.deepakm.kstreams.sink.ConsoleSink; import com.deepakm.kstreams.sink.HttpSink; import com.deepakm.kstreams.sink.Sink; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.KafkaStreams; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.StreamsConfig; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.KStreamBuilder; import org.apache.kafka.streams.processor.Processor; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.log4j.Level; import org.apache.log4j.Logger; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; /** * Created by deepakmarathe on 12/9/16. */ /** * $KAFKA_HOME/bin/kafktopics.sh --create --topic TextLinesTopic --partitions 4 --zookeeper $ZK --replication-factor 1 * <p> * $KAFKA_HOME/bin/kafka-topics.sh --create --topic RekeyedIntermediateTopic --partitions 4 --zookeeper $ZK --replication-factor 1 * <p> * $KAFKA_HOME/bin/kafka-topics.sh --create --topic WordsWithCountsTopic --partitions 4 --zookeeper $ZK --replication-factor 1 * <p> * $KAFKA_HOME/bin/kafka-console-producer.sh --topic=TextLinesTopic --broker-list=`broker-list.sh` * <p> * $KAFKA_HOME/bin/kafka-console-consumer.sh --topic=WordsWithCountsTopic --zookeeper=$ZK --from-beginning --property print.key=true --property value.deserializer=org.apache.kafka.common.serialization.StringDeserializer */ public class EchoConsumer { private static final Logger logger = Logger.getLogger(EchoConsumer.class); public static void main(String[] args) { String sourceTopic = System.getenv().get(ConfigKeys.SOURCE_TOPIC); String intermediateTopic = System.getenv().get(ConfigKeys.INTERMEDIATE_TOPIC); String sinkTopic = System.getenv().get(ConfigKeys.SINK_TOPIC); String bootstrapServers = System.getenv().get(ConfigKeys.BOOTSTRAP_SERVERS_VALUE); String zookeeperConnectValue = System.getenv().get(ConfigKeys.ZOOKEEPER_CONNECT_CONFIG_VALUE); String applicationId = System.getenv().get(ConfigKeys.APPLICATION_ID); logger.log(Level.DEBUG, "apploicationId : " + applicationId); logger.log(Level.DEBUG, "zookeeper config value : " + zookeeperConnectValue); logger.log(Level.DEBUG, "bootstrap servers : " + bootstrapServers); logger.log(Level.DEBUG, "sink topic : " + sinkTopic); logger.log(Level.DEBUG, "intermediate topic : " + intermediateTopic); logger.log(Level.DEBUG, "source topic : " + sourceTopic); Properties streamsConfig = new Properties(); streamsConfig.put(ConfigKeys.KAFKA_APPLICATION_ID, applicationId); streamsConfig.put(ConfigKeys.BOOTSTRAP_SERVERS_KEY, bootstrapServers); streamsConfig.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, zookeeperConnectValue); streamsConfig.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); streamsConfig.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName()); Sink sink = new HttpSink("http://localhost:8080/bookinglog"); sink = new ConsoleSink(); StreamingClient client = new StreamingClient(streamsConfig, sink, sourceTopic); client.start(); client.close(); } }
package com.example.android.quizapp; import org.junit.Test; import java.util.ArrayList; import static org.junit.Assert.*; public class QuestionTest { private static final QuestionManager questionManager = new QuestionManager(); @Test public void textEntryQuestionTest() throws Exception { TextEntryQuestion textEntryQuestion = questionManager.createTextQuestion("Question1", "Answer1"); assertFalse(textEntryQuestion.isAnswered()); assertFalse(textEntryQuestion.isCorrect()); textEntryQuestion.setRespond("Answer1"); assertTrue(textEntryQuestion.isAnswered()); assertTrue(textEntryQuestion.isCorrect()); textEntryQuestion = questionManager.createTextQuestion("Question2", "Answer2"); textEntryQuestion.setRespond("Answer1"); assertTrue(textEntryQuestion.isAnswered()); assertFalse(textEntryQuestion.isCorrect()); } @Test public void singleChoiceQuestionTest() throws Exception { String question = "Question2"; String answer = "Answer1"; String[] choices = {"Answer2", "Answer3", "Answer4"}; SingleChoiceQuestion singleChoiceQuestion = questionManager.createSingleChoiceQuestion(question, answer, choices); assertFalse(singleChoiceQuestion.isAnswered()); assertFalse(singleChoiceQuestion.isCorrect()); ArrayList<Choice> choicesList = singleChoiceQuestion.getChoices(); for (Choice choice : choicesList) { if (choice.getChoiceText().equals(choices[0])) { choice.setChosen(true); assertTrue(singleChoiceQuestion.isAnswered()); assertFalse(singleChoiceQuestion.isCorrect()); choice.setChosen(false); assertFalse(singleChoiceQuestion.isAnswered()); assertFalse(singleChoiceQuestion.isCorrect()); } if (choice.getChoiceText().equals(answer)) { choice.setChosen(true); assertTrue(singleChoiceQuestion.isAnswered()); assertTrue(singleChoiceQuestion.isCorrect()); choice.setChosen(false); assertFalse(singleChoiceQuestion.isAnswered()); assertFalse(singleChoiceQuestion.isCorrect()); } } } @Test public void multipleChoiceQuestionTest() throws Exception { String question = "Question2"; String[] answers = {"Answer1", "Answer3"}; String[] choices = {"Answer2", "Answer4"}; MultipleChoiceQuestion multipleChoiceQuestion = questionManager.createMultipleChoiceQuestion(question, answers, choices); assertFalse(multipleChoiceQuestion.isAnswered()); assertFalse(multipleChoiceQuestion.isCorrect()); ArrayList<Choice> choicesList = multipleChoiceQuestion.getChoices(); for (Choice choice : choicesList) { if (choice.getChoiceText().equals(answers[0])) { choice.setChosen(true); } } assertTrue(multipleChoiceQuestion.isAnswered()); assertFalse(multipleChoiceQuestion.isCorrect()); for (Choice choice : choicesList) { if (choice.getChoiceText().equals(answers[1])) { choice.setChosen(true); } } assertTrue(multipleChoiceQuestion.isAnswered()); assertTrue(multipleChoiceQuestion.isCorrect()); for (Choice choice : choicesList) { if (choice.getChoiceText().equals(choices[0])) { choice.setChosen(true); } } assertTrue(multipleChoiceQuestion.isAnswered()); assertFalse(multipleChoiceQuestion.isCorrect()); } }
package com.nefi.chainrat.server.network.ControlServer.CommandHandler; import com.google.common.base.Charsets; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.nefi.chainrat.server.network.ControlServer.packets.Packet; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; public class JsonEncoderHandler extends ChannelOutboundHandlerAdapter { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { Packet packet = (Packet) msg; GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); String sPacket = gson.toJson(packet, Packet.class); ByteBuf bytes = ctx.alloc().buffer(sPacket.length()); bytes.writeCharSequence(sPacket, Charsets.UTF_8); ctx.write(bytes, promise); } }
/* * SocialAdapter * * Version 1.0 * * November 25, 2017 * * Copyright (c) 2017 Team 26, CMPUT 301, University of Alberta - All Rights Reserved. * You may use, distribute, or modify this code under terms and conditions of the Code of Student Behavior at University of Alberta. * You can find a copy of the license in this project. Otherwise please contact rohan@ualberta.ca * * Purpose: Adapter class to convert Feed (model objects) to List view items. * Displays for each of your friends their habits and most recent habit event. */ package cmput301f17t26.smores.all_adapters; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.support.v7.widget.RecyclerView; 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 cmput301f17t26.smores.R; import cmput301f17t26.smores.all_exceptions.CommentNotSetException; import cmput301f17t26.smores.all_exceptions.ImageNotSetException; import cmput301f17t26.smores.all_models.Feed; import cmput301f17t26.smores.all_models.HabitEvent; import cmput301f17t26.smores.all_storage_controller.UserController; import cmput301f17t26.smores.utils.ProgressBarUtil; import java.util.List; public class SocialAdapter extends RecyclerView.Adapter<SocialAdapter.ViewHolder> { private List<Feed> mFeed; private Context mContext; private RecyclerView mRecyclerView; private ImageView mImageView; public SocialAdapter(Context context, RecyclerView recyclerView, ImageView imageView) { mContext = context; mRecyclerView = recyclerView; mImageView = imageView; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.fragment_social_element, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.mFeed = mFeed.get(position); holder.mUsername.setText(mFeed.get(position).getUsername()); holder.mHabitType.setText(mFeed.get(position).getHabit().getTitle()); int progress = (int) mFeed.get(position).getHabit().getPercentageFollowed(); holder.mProgressNum.setText(progress + " %"); ProgressBarUtil.DrawBar(progress, holder, holder.mProgress); HabitEvent habitEvent = mFeed.get(position).getHabitEvent(); if (habitEvent != null) { try { holder.mHabitEventComment.setText(habitEvent.getComment()); holder.mHabitEventImage.setImageBitmap(habitEvent.getImage()); } catch (CommentNotSetException e) { holder.mHabitEventComment.setText("No comment avaliable."); } catch (ImageNotSetException e) { holder.mHabitEventImage.setImageResource(R.mipmap.app_icon_round); } } else { holder.mHabitEventImage.setImageResource(R.mipmap.app_icon_round); holder.mHabitEventComment.setText(mFeed.get(position).getHabit().getReason()); } } @Override public int getItemCount() { if (mFeed == null) { return 0; } return mFeed.size(); } public class ViewHolder extends RecyclerView.ViewHolder { public final View mView; public final TextView mUsername; public final TextView mHabitType; public final TextView mHabitEventComment; public final ImageView mHabitEventImage; public final ImageView mProgress; public final TextView mProgressNum; public Feed mFeed; public ViewHolder(View view) { super(view); mView = view; mUsername = (TextView) view.findViewById(R.id.Username); mHabitType = (TextView) view.findViewById(R.id.HabitType); mHabitEventComment = (TextView) view.findViewById(R.id.HabitEventComment); mHabitEventImage = (ImageView) view.findViewById(R.id.HabitEventImage); mProgress = (ImageView) view.findViewById(R.id.HabitEventProgess); mProgressNum = (TextView) view.findViewById(R.id.HabitEventProgessNum); } @Override public String toString() { return super.toString() + " '" + mHabitType.getText() + "'"; } } public void loadList() { // Searching could be complex..so we will dispatch it to a different thread... final ProgressDialog progressDialog = new ProgressDialog(mContext); progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); progressDialog.setMessage("Now loading feed..."); progressDialog.setIndeterminate(true); progressDialog.setCanceledOnTouchOutside(false); progressDialog.show(); new Thread(new Runnable() { @Override public void run() { UserController.getUserController(mContext).updateFollowingList(); mFeed = UserController.getUserController(mContext).getFeed(); // Set on UI Thread ((Activity) mContext).runOnUiThread(new Runnable() { @Override public void run() { // Notify the List that the DataSet has changed... notifyDataSetChanged(); progressDialog.dismiss(); if (getItemCount() == 0) { mRecyclerView.setVisibility(View.GONE); mImageView.setVisibility(View.VISIBLE); } else { mImageView.setVisibility(View.GONE); mRecyclerView.setVisibility(View.VISIBLE); } } }); } }).start(); } }
package com.romens.yjkgrab.ui.fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import com.avos.avoscloud.AVException; import com.avos.avoscloud.AVObject; import com.avos.avoscloud.AVQuery; import com.avos.avoscloud.GetCallback; import com.avos.avoscloud.SaveCallback; import com.romens.yjkgrab.Constant; import com.romens.yjkgrab.R; import com.romens.yjkgrab.model.Order; import com.romens.yjkgrab.table.OrderTable; import com.romens.yjkgrab.ui.adapter.OrderAdapter; import com.romens.yjkgrab.ui.widget.GrabSuccessDialog; import com.romens.yjkgrab.utils.StatusHelper; import com.romens.yjkgrab.utils.ToastUtils; import com.romens.yjkgrab.wokinterface.CancelOrderInterface; import com.romens.yjkgrab.wokinterface.GrabInterface; import com.romens.yjkgrab.wokinterface.PickUpInterface; import com.romens.yjkgrab.wokinterface.ResultCallBack; import java.util.ArrayList; import java.util.List; /** * Created by myq on 15-12-9. */ public class HomeFragment extends BaseFragment implements AdapterView.OnItemClickListener, CancelOrderInterface, PickUpInterface { private ListView orderListView; private View contentView; private OrderAdapter adapter; private List<Order> data = new ArrayList<>(); //防止重复抢单 private boolean grabbing = false; protected GrabInterface grabInterface; @Override public void onAttach(Context context) { super.onAttach(context); grabInterface = (GrabInterface) mActivity; } @Override void dealOrder(final Order order) { if (grabInterface != null) { if (grabbing) { grabInterface.grabing(order, new ResultCallBack() { @Override public void onSuccess() { GrabSuccessDialog grabSuccessDialog = new GrabSuccessDialog(mActivity, order); grabSuccessDialog.setOrder(order); // grabSuccessDialog.setCancelClick(new GrabSuccessDialog.CancelClickListener() { // @Override // public void onCancelClick() { // cancelOrder(order, new ResultCallBack() { // @Override // public void onSuccess() { // mActivity.notifyAllObservers(); // ToastUtils.toastMsg(mActivity, "取消成功"); // } // // @Override // public void onFail() { // ToastUtils.toastMsg(mActivity, "取消失败"); // } // }); // } // }); // grabSuccessDialog.setPickupClick(new GrabSuccessDialog.PickupClickListener() { // @Override // public void onPickupClick() { // pickUp(order, new ResultCallBack() { // @Override // public void onSuccess() { // mActivity.notifyAllObservers(); // ToastUtils.toastMsg(mActivity, "取件成功"); // } // // @Override // public void onFail() { // ToastUtils.toastMsg(mActivity, "取件失败"); // } // }); // } // }); grabSuccessDialog.show(); } @Override public void onFail() { ToastUtils.toastMsg(mActivity, "抢单失败"); } }); grabbing = false; } } } @Override public void onDetach() { grabInterface = null; super.onDetach(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { contentView = inflater.inflate(R.layout.fragment_home, null, true); initViews(); initData(); return contentView; } private void initData() { notifyChanged(); } private void initViews() { orderListView = (ListView) contentView.findViewById(R.id.order_listview); adapter = new OrderAdapter(data, mActivity, this); orderListView.setAdapter(adapter); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.i(">>>>>>>>>", "onItemClick"); if (mActivity.isWorking()) { final Order order = data.get(position); progressDialog.show(); mOrderDetailInterface.getOrderDetail(order, new ResultCallBack() { @Override public void onSuccess() { dealOrder(order); progressDialog.dismiss(); } @Override public void onFail() { progressDialog.dismiss(); ToastUtils.toastMsg(mActivity, "抢单失败"); } }); grabbing = true; } else { ToastUtils.toastMsg(mActivity, "先上班!!!"); } } private synchronized void dealOrderAll(final Order order) { if (grabInterface != null) { if (TextUtils.equals(order.getStatus(), Constant.STATUS_WAITING_GRAB)) { grabInterface.grabing(order, new ResultCallBack() { @Override public void onSuccess() { mActivity.notifyAllObservers(); if (data.size() <= 0) { progressDialog.dismiss(); } ToastUtils.toastMsg(mActivity, "订单" + order.getOrderId() + "抢单成功!"); } @Override public void onFail() { if (data.size() <= 0) { progressDialog.dismiss(); } ToastUtils.toastMsg(mActivity, "订单" + order.getOrderId() + "抢单失败"); } }); } else { if (data.size() <= 0) { progressDialog.dismiss(); } } } else { progressDialog.dismiss(); } } @Override public void notifyChanged() { if (!mActivity.isGrabing()) return; if (adapter == null) return; List<Order> list = mActivity.getData(); data.clear(); for (Order order : list) { if (TextUtils.equals(Constant.STATUS_WAITING_GRAB, order.getStatus())) { data.add(order); } } adapter.notifyDataSetChanged(); } @Override public void cancelOrder(Order order, ResultCallBack resultCallBack) { StatusHelper.update(order, resultCallBack, StatusHelper.TO_CANCEL); } @Override public void pickUp(Order order, ResultCallBack resultCallBack) { StatusHelper.update(order, resultCallBack, StatusHelper.TO_SEND); } public void grabbingAll() { if (!mActivity.isWorking()) { ToastUtils.toastMsg(mActivity, "先上班!!!"); return; } if (data == null || data.size() == 0) { ToastUtils.toastMsg(mActivity, "没有订单可抢"); return; } for (final Order order : data) { progressDialog.show(); mOrderDetailInterface.getOrderDetail(order, new ResultCallBack() { @Override public void onSuccess() { dealOrderAll(order); } @Override public void onFail() { // if (data.size() <= 0) { progressDialog.dismiss(); // } ToastUtils.toastMsg(mActivity, "抢单失败"); } }); } } }
package com.sprint.crm.pojo; public class Roles { private Integer roleId; private String name; public Roles() { super(); // TODO Auto-generated constructor stub } public Roles(Integer roleId, String name) { super(); this.roleId = roleId; this.name = name; } public Integer getRoleId() { return roleId; } public void setRoleId(Integer roleId) { this.roleId = roleId; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Roles [roleId=" + roleId + ", name=" + name + "]"; } }
package com.corebaseit.advancedgridviewjson.models; import android.provider.BaseColumns; /** * Created by Vincent Bevia on 27/10/16. <br /> * vbevia@ieee.org */ public class FavoritesListModel { private long id; private String title; private String extra_text; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getExtra_text() { return extra_text; } public void setExtra_text(String extra_text) { this.extra_text = extra_text; } public static abstract class Entry implements BaseColumns { public static final String TABLE_NAME = "search"; public static final String COLUMN_ID = "_id"; public static final String COLUMN_TITLE = "title"; } }
package io.github.matheus.domain.repository; import io.github.matheus.domain.entity.Produto; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface Produtos extends JpaRepository<Produto, Integer> { // @Query(value = "select * from produto p where p.descricao like '%:descricao%' ", nativeQuery = true) // List<Produto> procurarPorDescricao(@Param("descricao") String descricao); }
package nesto.walker.bean; /** * Created on 2015/8/5 14:25 */ public class GpsStatusCode { public static final int GPS_STATUS_CHANGED = 100; public static final int LOCATION_CHANGED = 101; }
package clinic.service; import java.util.Arrays; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; import clinic.business.Doctor; import clinic.business.Nurse; @Service public class NurseService { @Autowired private RestTemplate restTemplate = new RestTemplate(); public RestTemplate restTemplate() { return new RestTemplate(); } public List<Nurse> findAll(){ return (List<Nurse>) Arrays.asList(restTemplate.getForObject("http://localhost:8181/nurse", Nurse[].class)); } public void update(Integer id, Nurse nurse) { restTemplate.put("http://localhost:8181/nurse/update/"+id, nurse); } public void delete(Integer id) { restTemplate.delete("http://localhost:8181/nurse/delete/{id}", id); } public Nurse create(Nurse nurse) { return restTemplate.postForObject("http://localhost:8181/nurse", nurse, Nurse.class); } public List<Nurse> findByTen( String ten){ return (List<Nurse>) Arrays.asList(restTemplate.getForObject("http://localhost:8181/nurse/find?ten="+ten, Nurse[].class)); } public Nurse findById( Integer id){ return restTemplate.getForObject("http://localhost:8181/nurse/find/"+id, Nurse.class); } }
package roshaan.quizapplication.activities; import android.app.Activity; import android.content.Intent; import android.databinding.DataBindingUtil; import android.graphics.drawable.Animatable; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.viksaa.sssplash.lib.activity.AwesomeSplash; import com.viksaa.sssplash.lib.cnst.Flags; import com.viksaa.sssplash.lib.model.ConfigSplash; import roshaan.quizapplication.R; import roshaan.quizapplication.UserModel; import roshaan.quizapplication.databinding.ActivitySplashBinding; import static java.lang.Thread.sleep; public class SplashActivity extends Activity { FirebaseAuth mAuth; DatabaseReference mRef; ActivitySplashBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding= DataBindingUtil.setContentView(this,R.layout.activity_splash); mAuth=FirebaseAuth.getInstance(); mRef=FirebaseDatabase.getInstance().getReference("Users"); // binding.imgV.setVisibility(View.INVISIBLE); Animation anim= AnimationUtils.loadAnimation(SplashActivity.this,R.anim.fade_in); binding.imgV.startAnimation(anim); new Handler().postDelayed(new Runnable() { @Override public void run() { if (mAuth.getCurrentUser() == null) { //imageAnimation(); startActivity(new Intent(SplashActivity.this, AuthenticationActivity.class)); overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left); //overridePendingTransition(R.anim.fade_in,R.anim.fade_out); finish(); } else { mAuth = FirebaseAuth.getInstance(); mRef = FirebaseDatabase.getInstance().getReference("Users"); if (mAuth.getCurrentUser() == null) { // imageAnimation(); startActivity(new Intent(SplashActivity.this, AuthenticationActivity.class)); overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left); // overridePendingTransition(R.anim.fade_in,R.anim.fade_out); finish(); } else { mRef.orderByChild("userID").equalTo(mAuth.getCurrentUser().getUid()) .addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (dataSnapshot.exists()) { Iterable<DataSnapshot> child = dataSnapshot.getChildren(); // System.out.println(user); UserModel user = null; for (DataSnapshot ch : child) user = ch.getValue(UserModel.class); System.out.println(dataSnapshot.getValue()); if (user.getUserType().equals("Player")) { startActivity(new Intent(SplashActivity.this, PlayerHomeActivity.class)); finish(); } else if (user.getUserType().equals("QuizTaker")) { startActivity(new Intent(SplashActivity.this, QuizTakerHomeActivity.class)); finish(); } } else { Toast.makeText(SplashActivity.this, "User doesnt exists", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled(DatabaseError databaseError) { } }); } } } }, 3000); } }
package pdamjanovic.service; import pdamjanovic.calculation.CostPathPair; import pdamjanovic.model.Airport; import java.io.IOException; import java.util.Map; /** * Created by p.damjanovic on 11/18/2017. */ public interface RouteService { public CostPathPair<Integer> findRoute(Map<String, Airport> airports, String start, String end) throws IOException; }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tfar.servicesImpl; import com.tfar.dao.FrereDao; import com.tfar.entity.Frere; import com.tfar.services.FrereService; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; /** * * @author hatem */ public class FrereServiceImpl implements FrereService { @Autowired private FrereDao frereDao; public FrereDao getFrereDao() { return frereDao; } public void setCytogenetiqueDao(FrereDao frereDao) { this.frereDao = frereDao; } @Override public void add(Frere newFrere) { frereDao.add(newFrere); } @Override public void update(Frere frere) { frereDao.update(frere); } @Override public List<Frere> getAllFrere() { return frereDao.getAllFrere(); } @Override public List<Frere> getListFrereParnDossier(String nDossier) { System.out.println("getListFrereParnDossier:----------------------"); return frereDao.getFreresParNDossier(nDossier); } @Override public void delete(Frere frere) { frereDao.delete(frere); } }
package com.prep.quiz83; import java.util.Random; //Write a function that given a list of items and weights return a random item in the list with probability relative to the weights public class Drill14 { public static void main(String[] args){ //given item int[] input ={1,3,5,7,9}; //probability {1/25, 3/25, 5/25, 7/25, 9/25} // {{0}, {1,2,3},{4,5,6,7,8,9},{10,11,12,13,14,15,16},{17,18,19,20,21,22,23,24,25}} int weightSum=0; for(int i=0;i<input.length;i++){ weightSum+=input[i]; } //common denominator 25 Random random = new Random(System.currentTimeMillis()); int elem1=0; int elem2=0; int elem3=0; int elem4=0; int elem5=0; for(int i=0;i<10000;i++){ int tmp=random.nextInt(weightSum); if(tmp==0) elem1++; else if(tmp>=1 && tmp<=3) elem2++; else if(tmp>=4 && tmp<=8) elem3++; else if(tmp>=9 && tmp<=15) elem4++; else //if (tmp >=17 && tmp<=25) elem5++; if(i==999){ System.out.println("probability of element 1 : " + (float)elem1/10000f); System.out.println("probability of element 2 : " + (float)elem2/10000f); System.out.println("probability of element 3 : " + (float)elem3/10000f); System.out.println("probability of element 4 : " + (float)elem4/10000f); System.out.println("probability of element 5 : " + (float)elem5/10000f); System.out.println(elem1+elem2+elem3+elem4+elem5); } } } }
/* * Copyright (C) 2019 The Android Open Source Project * * 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. */ import art.Redefinition; import java.lang.invoke.*; import java.lang.reflect.Field; import java.util.Base64; public class Main { public static final class Transform { static { } public static Object foo = null; } /* Base64 encoded dex bytes for: * * public static final class Transform { * static {} * public static Object bar = null; * public static Object foo = null; * } */ public static final byte[] DEX_BYTES = Base64.getDecoder() .decode( "ZGV4CjAzNQCjkRjcSr1RJO8FnnCjHV/8h6keJP/+P3WQAwAAcAAAAHhWNBIAAAAAAAAAANgCAAAQ" + "AAAAcAAAAAYAAACwAAAAAQAAAMgAAAACAAAA1AAAAAMAAADkAAAAAQAAAPwAAAB0AgAAHAEAAFwB" + "AABmAQAAbgEAAIABAACIAQAArAEAAMwBAADgAQAA6wEAAPYBAAD5AQAABgIAAAsCAAAQAgAAFgIA" + "AB0CAAACAAAAAwAAAAQAAAAFAAAABgAAAAkAAAAJAAAABQAAAAAAAAAAAAQACwAAAAAABAAMAAAA" + "AAAAAAAAAAAAAAAAAQAAAAQAAAABAAAAAAAAABEAAAAEAAAAAAAAAAcAAADIAgAApAIAAAAAAAAB" + "AAAAAAAAAFABAAAGAAAAEgBpAAAAaQABAA4AAQABAAEAAABVAQAABAAAAHAQAgAAAA4ABwAOPAAF" + "AA4AAAAACDxjbGluaXQ+AAY8aW5pdD4AEExNYWluJFRyYW5zZm9ybTsABkxNYWluOwAiTGRhbHZp" + "ay9hbm5vdGF0aW9uL0VuY2xvc2luZ0NsYXNzOwAeTGRhbHZpay9hbm5vdGF0aW9uL0lubmVyQ2xh" + "c3M7ABJMamF2YS9sYW5nL09iamVjdDsACU1haW4uamF2YQAJVHJhbnNmb3JtAAFWAAthY2Nlc3NG" + "bGFncwADYmFyAANmb28ABG5hbWUABXZhbHVlAHZ+fkQ4eyJjb21waWxhdGlvbi1tb2RlIjoiZGVi" + "dWciLCJtaW4tYXBpIjoxLCJzaGEtMSI6IjI4YmNlZjUwYWM4NTk3Y2YyMmU4OTJiMWJjM2EzYjky" + "Yjc0ZTcwZTkiLCJ2ZXJzaW9uIjoiMS42LjMyLWRldiJ9AAICAQ4YAQIDAgoEGQ0XCAIAAgAACQEJ" + "AIiABJwCAYGABLgCAAAAAAIAAACVAgAAmwIAALwCAAAAAAAAAAAAAAAAAAAPAAAAAAAAAAEAAAAA" + "AAAAAQAAABAAAABwAAAAAgAAAAYAAACwAAAAAwAAAAEAAADIAAAABAAAAAIAAADUAAAABQAAAAMA" + "AADkAAAABgAAAAEAAAD8AAAAASAAAAIAAAAcAQAAAyAAAAIAAABQAQAAAiAAABAAAABcAQAABCAA" + "AAIAAACVAgAAACAAAAEAAACkAgAAAxAAAAIAAAC4AgAABiAAAAEAAADIAgAAABAAAAEAAADYAgAA"); public static void main(String[] args) throws Exception, Throwable { System.loadLibrary(args[0]); Field f = Transform.class.getDeclaredField("foo"); Transform.foo = "THIS IS A FOO VALUE"; System.out.println("Foo value is " + f.get(null)); final int max_depth = 10; Object[] results = new Object[max_depth]; Runnable res = () -> { Redefinition.doCommonStructuralClassRedefinition(Transform.class, DEX_BYTES); }; for (int i = 0; i < max_depth; i++) { final Runnable next = res; final int id = i; res = () -> { try { results[id] = NativeFieldScopeCheck(f, next).invokeExact(); } catch (Throwable t) { throw new Error("Failed!", t); } }; } res.run(); for (int i = 0; i < max_depth; i++) { System.out.println("Result at depth " + i + ": " + results[i]); } } // Hold the field as a ArtField, run the 'test' function, turn the ArtField into a MethodHandle // directly and return that. public static native MethodHandle NativeFieldScopeCheck(Field in, Runnable test); }
package com.fanoi.dream.module.update.beans; import java.io.Serializable; /** * 升级 * * @author JetteZh * */ public class Update implements Serializable { private static final long serialVersionUID = -6899516758129656897L; private String arid; private String name; private String version; private String os; private String size; private String flag; private String change_log; private String download_url; public String getArid() { return arid; } public void setArid(String arid) { this.arid = arid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getOs() { return os; } public void setOs(String os) { this.os = os; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } public String getChange_log() { return change_log; } public void setChange_log(String change_log) { this.change_log = change_log; } public String getDownload_url() { return download_url; } public void setDownload_url(String download_url) { this.download_url = download_url; } @Override public String toString() { return "Update [arid=" + arid + ", name=" + name + ", version=" + version + ", os=" + os + ", size=" + size + ", flag=" + flag + ", change_log=" + change_log + ", download_url=" + download_url + "]"; } }
package com.example.ips.service; import com.example.ips.model.ServiceDepUatUp; import java.util.List; import java.util.Map; public interface ServiceDepUatUpService { /** * 查询全部uatUp信息 * @return */ List<ServiceDepUatUp> getAllUatUp(); /** * 根据主键查询uatUp信息 */ ServiceDepUatUp getUatUpByKey(Integer id); /** * 保存信息 */ Map<String, Object> uatUpAdd(ServiceDepUatUp record); /** * 更新信息 */ Map<String, Object> uatUpUpdate(ServiceDepUatUp record); /** * 删除信息 */ Map<String, Object> uatUpDel(Integer id); }
/* ExecutionResolver.java Purpose: Description: History: Fri Jun 24 12:22:23 2005, Created by tomyeh Copyright (C) 2005 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.zk.xel.impl; import java.util.Collections; import org.zkoss.util.resource.Labels; import org.zkoss.xel.XelContext; import org.zkoss.xel.VariableResolver; import org.zkoss.xel.VariableResolverX; import org.zkoss.xel.XelException; import org.zkoss.xel.util.Evaluators; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.Execution; import org.zkoss.zk.ui.Page; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.UiException; import org.zkoss.zk.ui.sys.ExecutionCtrl; /** * A variable resolver that is based on the specified execution. * * @author tomyeh * @since 3.0.0 */ public class ExecutionResolver implements VariableResolverX { /** The parent resolver. */ private final VariableResolver _parent; private final Execution _exec; private Object _self; /** Constructs a resolver with a parent and a page. * @param parent the parent resolver (null means ignored). * @param exec the current execution */ public ExecutionResolver(Execution exec, VariableResolver parent) { if (exec == null) throw new NullPointerException(); _exec = exec; _parent = parent; } /** Sets the self variable. * The self variable also acts as the context to resolve other variables. */ public void setSelf(Object self) { _self = self; } /** Returns the self variable. */ public Object getSelf() { return _self; } //-- VariableResolver --// public Object resolveVariable(String name) throws XelException { return resolveVariable(null, null, name); } //-- VariableResolverX --// public Object resolveVariable(XelContext ctx, Object base, Object onm) { if (base != null) { final Page page = ((ExecutionCtrl)_exec).getCurrentPage(); return page != null ? page.getXelVariable(ctx, base, onm, true): null; } if (onm == null) return null; final String name = onm.toString(); if (name == null || name.length() == 0) //just in case return null; //Note: we have to access keyword frist (rather than component's ns) //since 1) BeanShell interpreter will store back variables //and page.getZScriptVariable will return the old value //2) ZK 5, getAttributeOrFellow doesn't look for variable resolvers and implicit objects if ("arg".equals(name)) return _exec.getArg(); if ("componentScope".equals(name)) { if (_self instanceof Component) return ((Component)_self).getAttributes(Component.COMPONENT_SCOPE); return Collections.EMPTY_MAP; } if ("desktopScope".equals(name)) return _exec.getDesktop().getAttributes(); if ("desktop".equals(name)) return _exec.getDesktop(); if ("execution".equals(name)) return _exec; if ("pageScope".equals(name)) { if (_self instanceof Component) return ((Component)_self).getAttributes(Component.PAGE_SCOPE); if (_self instanceof Page) return ((Page)_self).getAttributes(); final Page page = ((ExecutionCtrl)_exec).getCurrentPage(); return page != null ? page.getAttributes(): Collections.EMPTY_MAP; } if ("page".equals(name)) { if (_self instanceof Component) return getPage((Component)_self); if (_self instanceof Page) return (Page)_self; return ((ExecutionCtrl)_exec).getCurrentPage(); } if ("requestScope".equals(name)) return _exec.getAttributes(); if ("self".equals(name)) return _self; if ("sessionScope".equals(name)) return _exec.getDesktop().getSession().getAttributes(); if ("session".equals(name)) return _exec.getDesktop().getSession(); if ("spaceOwner".equals(name)) { if (_self instanceof Component) return ((Component)_self).getSpaceOwner(); if (_self instanceof Page) return (Page)_self; return null; } if ("spaceScope".equals(name)) { if (_self instanceof Component) return ((Component)_self).getAttributes(Component.SPACE_SCOPE); if (_self instanceof Page) return ((Page)_self).getAttributes(); return Collections.EMPTY_MAP; } if ("param".equals(name) || "paramValues".equals(name)) return Evaluators.resolveVariable(_parent, name); //Bug 3131983: cannot go through getZScriptVariable if (_self instanceof Component) { final Component comp = (Component)_self; //We have to look getZScriptVariable first and then namespace //so it is in the same order of interpreter final Page page = getPage(comp); if (page != null) { final Object o = page.getZScriptVariable(comp, name); if (o != null) return o; } Object o = _exec.getAttribute(name); if (o != null/* || _exec.hasAttribute(name)*/) //ServletRequest not support hasAttribute return o; o = comp.getAttributeOrFellow(name, true); if (o != null) return o; if (page != null) { o = page.getXelVariable(ctx, null, name, true); if (o != null) return o; } } else { Page page; if (_self instanceof Page) { page = (Page)_self; } else { page = ((ExecutionCtrl)_exec).getCurrentPage(); } if (page != null) { Object o = page.getZScriptVariable(name); if (o != null) return o; o = _exec.getAttribute(name); if (o != null/* || _exec.hasAttribute(name)*/) //ServletRequest not support hasAttribute return o; o = page.getAttributeOrFellow(name, true); if (o != null) return o; o = page.getXelVariable(ctx, null, name, true); if (o != null) return o; } else { Object o = _exec.getAttribute(name, true); if (o != null/* || _exec.hasAttribute(name, true)*/) //ServletRequest not support hasAttribute return o; } } Object o = Evaluators.resolveVariable(_parent, name); if (o != null) return o; //lower priority (i.e., user could override it) //Reason: they were introduced later, and have to maintain backward comparibility if ("labels".equals(name)) return Labels.getSegmentedLabels(); return null; } private static Page getPage(Component comp) { Page page = comp.getPage(); if (page != null) return page; final Execution exec = Executions.getCurrent(); return exec != null ? ((ExecutionCtrl)exec).getCurrentPage(): null; } //Object// public String toString() { return "[ExecutionResolver: " + _self + ']'; } }
package f.star.iota.milk.ui.xiuren.xiu; import android.os.Bundle; import f.star.iota.milk.base.ScrollImageFragment; public class XiuRenFragment extends ScrollImageFragment<XiuRenPresenter, XiuRenAdapter> { public static XiuRenFragment newInstance(String url) { XiuRenFragment fragment = new XiuRenFragment(); Bundle bundle = new Bundle(); bundle.putString("base_url", url); bundle.putString("page_suffix", ".html"); fragment.setArguments(bundle); return fragment; } @Override protected XiuRenPresenter getPresenter() { return new XiuRenPresenter(this); } @Override protected XiuRenAdapter getAdapter() { return new XiuRenAdapter(); } }
package ranner; public class ranner { }
package com.upokecenter.cbor; /* Written by Peter O. in 2014. Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ If you like this, you should donate to Peter O. at: http://peteroupc.github.io/ */ import com.upokecenter.util.*; import com.upokecenter.numbers.*; final class CBORNativeConvert { private CBORNativeConvert() { } private static CBORObject FromObjectAndInnerTags( Object objectValue, CBORObject objectWithTags) { CBORObject newObject = CBORObject.FromObject(objectValue); if (!objectWithTags.isTagged()) { return newObject; } objectWithTags = objectWithTags.UntagOne(); if (!objectWithTags.isTagged()) { return newObject; } EInteger[] tags = objectWithTags.GetAllTags(); for (int i = tags.length - 1; i >= 0; --i) { newObject = CBORObject.FromObjectAndTag(newObject, tags[i]); } return newObject; } public static CBORObject ConvertToNativeObject(CBORObject o) { if (o.HasMostOuterTag(2)) { return ConvertToBigNum(o, false); } if (o.HasMostOuterTag(3)) { return ConvertToBigNum(o, true); } if (o.HasMostOuterTag(4)) { return ConvertToDecimalFrac(o, true, false); } if (o.HasMostOuterTag(5)) { return ConvertToDecimalFrac(o, false, false); } if (o.HasMostOuterTag(30)) { return ConvertToRationalNumber(o); } if (o.HasMostOuterTag(264)) { return ConvertToDecimalFrac(o, true, true); } return o.HasMostOuterTag(265) ? ConvertToDecimalFrac(o, false, true) : o; } private static CBORObject ConvertToDecimalFrac( CBORObject o, boolean isDecimal, boolean extended) { if (o.getType() != CBORType.Array) { throw new CBORException("Big fraction must be an array"); } if (o.size() != 2) { throw new CBORException("Big fraction requires exactly 2 items"); } if (!o.get(0).isIntegral()) { throw new CBORException("Exponent is not an integer"); } if (!o.get(1).isIntegral()) { throw new CBORException("Mantissa is not an integer"); } EInteger exponent = o.get(0).AsEInteger(); EInteger mantissa = o.get(1).AsEInteger(); if (!extended && exponent.GetSignedBitLengthAsEInteger().compareTo(64) > 0) { throw new CBORException("Exponent is too big"); } if (exponent.isZero()) { // Exponent is 0, so return mantissa instead return CBORObject.FromObject(mantissa); } // NOTE: Discards tags. See comment in CBORTag2. return isDecimal ? CBORObject.FromObject(EDecimal.Create(mantissa, exponent)) : CBORObject.FromObject(EFloat.Create(mantissa, exponent)); } private static CBORObject ConvertToBigNum(CBORObject o, boolean negative) { if (o.getType() != CBORType.ByteString) { throw new CBORException("Byte array expected"); } byte[] data = o.GetByteString(); if (data.length <= 7) { long x = 0; for (int i = 0; i < data.length; ++i) { x <<= 8; x |= ((long)data[i]) & 0xff; } if (negative) { x = -x; --x; } return FromObjectAndInnerTags(x, o); } int neededLength = data.length; byte[] bytes; EInteger bi; boolean extended = false; if (((data[0] >> 7) & 1) != 0) { // Increase the needed length // if the highest bit is set, to // distinguish negative and positive // values ++neededLength; extended = true; } bytes = new byte[neededLength]; for (int i = 0; i < data.length; ++i) { bytes[i] = data[data.length - 1 - i]; if (negative) { bytes[i] = (byte)((~((int)bytes[i])) & 0xff); } } if (extended) { bytes[bytes.length - 1] = negative ? (byte)0xff : (byte)0; } bi = EInteger.FromBytes(bytes, true); // NOTE: Here, any tags are discarded; when called from // the Read method, "o" will have no tags anyway (beyond tag 2), // and when called from FromObjectAndTag, we prefer // flexibility over throwing an error if the input // Object contains other tags. The tag 2 is also discarded // because we are returning a "natively" supported CBOR Object. return CBORObject.FromObject(bi); } private static CBORObject ConvertToRationalNumber(CBORObject obj) { if (obj.getType() != CBORType.Array) { throw new CBORException("Rational number must be an array"); } if (obj.size() != 2) { throw new CBORException("Rational number requires exactly 2 items"); } CBORObject first = obj.get(0); CBORObject second = obj.get(1); if (!first.isIntegral()) { throw new CBORException("Rational number requires integer numerator"); } if (!second.isIntegral()) { throw new CBORException("Rational number requires integer denominator"); } if (second.signum() <= 0) { throw new CBORException("Rational number requires denominator greater than 0"); } EInteger denom = second.AsEInteger(); // NOTE: Discards tags. return denom.equals(EInteger.FromInt32(1)) ? CBORObject.FromObject(first.AsEInteger()) : CBORObject.FromObject( ERational.Create( first.AsEInteger(), denom)); } }
package slimeknights.tconstruct.tools; import com.google.common.eventbus.Subscribe; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.apache.commons.lang3.tuple.Pair; import org.apache.logging.log4j.Logger; import slimeknights.mantle.pulsar.pulse.Pulse; import slimeknights.tconstruct.common.ClientProxy; import slimeknights.tconstruct.common.CommonProxy; import slimeknights.tconstruct.common.ModelRegisterUtil; import slimeknights.tconstruct.library.TinkerRegistry; import slimeknights.tconstruct.library.Util; import slimeknights.tconstruct.library.modifiers.IModifier; import slimeknights.tconstruct.library.tinkering.PartMaterialType; import slimeknights.tconstruct.library.tools.Pattern; import slimeknights.tconstruct.library.tools.ToolCore; import slimeknights.tconstruct.library.tools.ToolPart; import slimeknights.tconstruct.tools.modifiers.ModExtraTraitDisplay; import slimeknights.tconstruct.tools.modifiers.ModFortifyDisplay; import static slimeknights.tconstruct.tools.TinkerModifiers.modCreative; import static slimeknights.tconstruct.tools.TinkerModifiers.modHarvestHeight; import static slimeknights.tconstruct.tools.TinkerModifiers.modHarvestWidth; // this class is called after all other pulses that add stuff have been called and registers all the tools, modifiers // and more in one swoop @Pulse( id = AggregateModelRegistrar.PulseId, description = "Registers tool models and co", pulsesRequired = TinkerTools.PulseId, forced = true) public class AggregateModelRegistrar extends AbstractToolPulse { public static final String PulseId = "TinkerModelRegister"; static final Logger log = Util.getLogger(PulseId); @SidedProxy(clientSide = "slimeknights.tconstruct.tools.AggregateModelRegistrar$AggregateClientProxy", serverSide = "slimeknights.tconstruct.common.CommonProxy") public static CommonProxy proxy; @Override @SubscribeEvent public void registerItems(Register<Item> event) { for(Pair<Item, ToolPart> toolPartPattern : toolPartPatterns) { registerStencil(toolPartPattern.getLeft(), toolPartPattern.getRight()); } } @SubscribeEvent public void registerModels(ModelRegistryEvent event) { proxy.registerModels(); } @Subscribe public void preInit(FMLPreInitializationEvent event) { proxy.preInit(); } private void registerStencil(Item pattern, ToolPart toolPart) { for(ToolCore toolCore : TinkerRegistry.getTools()) { for(PartMaterialType partMaterialType : toolCore.getRequiredComponents()) { if(partMaterialType.getPossibleParts().contains(toolPart)) { ItemStack stencil = new ItemStack(pattern); Pattern.setTagForPart(stencil, toolPart); TinkerRegistry.registerStencilTableCrafting(stencil); return; } } } } public static class AggregateClientProxy extends ClientProxy { @Override public void registerModels() { super.registerModels(); // toolparts for(ToolPart part : toolparts) { ModelRegisterUtil.registerPartModel(part); } // tools for(ToolCore tool : tools) { ModelRegisterUtil.registerToolModel(tool); } registerModifierModels(); } private void registerModifierModels() { for(IModifier modifier : modifiers) { if(modifier == modCreative || modifier == modHarvestWidth || modifier == modHarvestHeight) { // modifiers without model are blacklisted continue; } ModelRegisterUtil.registerModifierModel(modifier, Util.getModifierResource(modifier.getIdentifier())); } // we add a temporary modifier that does nothing to work around the model restrictions for the fortify modifier ModelRegisterUtil.registerModifierModel(new ModFortifyDisplay(), Util.getResource("models/item/modifiers/fortify")); new ModExtraTraitDisplay(); } } }
package SixGen.World; import SixGen.GameObject.GameObject; import SixGen.Handler.Handler; import SixGen.Window.SixCanvas; import java.awt.Color; import java.awt.image.BufferedImage; import java.util.LinkedList; import SixGen.GameObject.GameObject.TexturePosition; import SixGen.Utils.Utils.Direction; /** * * WorldManager * This class contains voids useful for generating the world. * Abilities : * Generating world from BufferedImage map * Generating world from Level level */ public abstract class WorldManager { protected Handler handler; protected Color color; protected Color colors[] = new Color[9]; LinkedList<Level> levels = new LinkedList<Level>(); public WorldManager(Handler handler) { this.handler = handler; for (int i = 0; i < colors.length; i++) { colors[i] = new Color(0, 0, 0); } } public abstract GameObject objectSpawning(int xx, int yy, int gridSizeWidth, int gridSizeHeight); public void spawnLevelFromMap(BufferedImage map, int gridSize) { spawnLevelFromMap(map, gridSize, gridSize); } public void spawnLevelFromMap(BufferedImage map, int gridSizeWidth, int gridSizeHeight) { int w = map.getWidth(); int h = map.getHeight(); int counter = 0; for (int xx = 0; xx < w; xx++) { for (int yy = 0; yy < h; yy++) { counter = 0; for (int yyy = 0; yyy < 3; yyy++) { for (int xxx = 0; xxx < 3; xxx++) { int getX = xx - 1 + xxx; int getY = yy - 1 + yyy; if (getX < 0) { getX = 0; } if (getY < 0) { getY = 0; } if (getX > w) { getX = w; } if (getY > h) { getY = h; } int pixel; if(getX < w && getY < h) { pixel = map.getRGB(getX, getY); } else { pixel = color.black.getRGB(); } int r = (pixel >> 16) & 0xff; int g = (pixel >> 8) & 0xff; int b = (pixel) & 0xff; colors[counter] = new Color(r, g, b); counter++; } } color = colors[4]; objectSpawning(xx * gridSizeWidth, yy * gridSizeHeight, gridSizeWidth, gridSizeHeight); } } } public void spawnLevelFromMap(BufferedImage map, int gridSize, int x, int y, boolean center) { spawnLevelFromMap(map, gridSize, gridSize, x, y, center); } public void spawnLevelFromMap(BufferedImage map, int gridSizeWidth, int gridSizeHeight, int x, int y, boolean center) { int counter = 0; int w = map.getWidth(); int h = map.getHeight(); int bx, by; if (center) { bx = x - w * gridSizeWidth / 2; by = y - h * gridSizeHeight / 2; } else { bx = x; by = y; } for (int xx = 0; xx < w; xx++) { for (int yy = 0; yy < h; yy++) { counter = 0; for (int yyy = 0; yyy < 3; yyy++) { for (int xxx = 0; xxx < 3; xxx++) { int getX = xx - 1 + xxx; int getY = yy - 1 + yyy; if (getX < 0) { getX = 0; } if (getY < 0) { getY = 0; } if (getX > w - 1) { getX = w - 1; } if (getY > h - 1) { getY = h - 1; } int pixel = map.getRGB(getX, getY); int r = (pixel >> 16) & 0xff; int g = (pixel >> 8) & 0xff; int b = (pixel) & 0xff; colors[counter] = new Color(r, g, b); // System.out.printf("%d %d %d %n" ,counter ,getX , getY); counter++; } } color = colors[4]; objectSpawning(bx + xx * gridSizeWidth, by + yy * gridSizeHeight, gridSizeWidth, gridSizeHeight); } } } public boolean isColor(Color color) { if (color.equals(this.color)) { return true; } else { return false; } } public void addLevel(Level level) { levels.add(level); } public void removeLevel(Level level) { levels.remove(level); } public void spawnLevel(int levelId) { for (int i = 0; i < levels.size(); i++) { Level level = levels.get(i); if (level.getLevelId() == levelId) { spawnLevelFromMap(level.getMap(), level.getGridSizeWidth(), level.getGridSizeHeight(), level.getX(), level.getY(), level.isCenter()); } } } public void spawnLevel(int levelId , SixCanvas canv) { for (int i = 0; i < levels.size(); i++) { Level level = levels.get(i); if (level.getLevelId() == levelId) { canv.setBoundsClamp(level); spawnLevelFromMap(level.getMap(), level.getGridSizeWidth(), level.getGridSizeHeight(), level.getX(), level.getY(), level.isCenter()); } } } public void spawnLevel(Level level) { spawnLevelFromMap(level.getMap(), level.getGridSizeWidth(), level.getGridSizeHeight(), level.getX(), level.getY(), level.isCenter()); } public void spawnLevel(Level level , SixCanvas canv) { canv.setBoundsClamp(level); spawnLevelFromMap(level.getMap(), level.getGridSizeWidth(), level.getGridSizeHeight(), level.getX(), level.getY(), level.isCenter()); } public Level getLevel(int levelId) { for (int i = 0; i < levels.size(); i++) { Level level = levels.get(i); if (level.getLevelId() == levelId) { return level; } } return null; } public TexturePosition getFromColours() { boolean same[] = new boolean[colors.length]; for (int i = 0; i < colors.length; i++) { if (colors[i].getRGB() == colors[4].getRGB()) { same[i] = true; } else { same[i] = false; } } return texutrePositionDecide(same); } public TexturePosition texutrePositionDecide(boolean same[]) { if (!same[1] && !same[3] && same[5] && same[7]) { return TexturePosition.topLeft; } else if (!same[1] && same[3] && !same[5] && same[7]) { return TexturePosition.topRight; } else if (same[1] && !same[3] && same[5] && same[7]) { return TexturePosition.left; } else if (same[1] && same[3] && !same[5] && same[7]) { return TexturePosition.right; } else if (same[1] && !same[3] && same[5] && !same[7]) { return TexturePosition.bottomLeft; } else if (same[1] && same[3] && same[5] && !same[7]) { return TexturePosition.bottom; } else if (same[1] && same[3] && !same[5] && !same[7]) { return TexturePosition.bottomRight; } else if (!same[1]) { return TexturePosition.top; } else { return TexturePosition.center; } } /** * Checks if objects near by aren't of the same type (if they are functions will edit objects bounds). * @author filip * @param object object that will be edited */ public void checkForBounds(GameObject object) { boolean same[] = new boolean[colors.length]; for (int i = 0; i < colors.length; i++) { same[i] = colors[i].getRGB() == colors[4].getRGB(); } object.setBoundsSwitch(Direction.up, !same[1]); object.setBoundsSwitch(Direction.left, !same[3]); object.setBoundsSwitch(Direction.right, !same[5]); object.setBoundsSwitch(Direction.down, !same[7]); } public void checkForBounds(GameObject object , Color[] c){ Color[] check = new Color[1 + c.length]; for(int i = 0 ; i < check.length ; i++) { if(i!=check.length - 1) { check[i] = c[i]; } else { check[i] = colors[4]; } } boolean same[] = new boolean[colors.length]; for (int i = 0; i < colors.length; i++) { boolean result = false; for(int f = 0 ; f < check.length ; f++) { if(colors[i].getRGB() == check[f].getRGB()) { result = true; } } same[i] = result; } object.setBoundsSwitch(Direction.up, !same[1]); object.setBoundsSwitch(Direction.left, !same[3]); object.setBoundsSwitch(Direction.right, !same[5]); object.setBoundsSwitch(Direction.down, !same[7]); } public void setHandler(Handler handler) { this.handler = handler; } public Handler getHandler() { return handler; } }
package removeNthFromEnd19; import dataStructure.ListNode; import java.util.*; /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { /** * 额外空间 * @param head * @param n * @return */ public ListNode removeNthFromEnd(ListNode head, int n) { List<ListNode> list = new ArrayList<>(); ListNode node, pre; while (head != null) { list.add(head); head = head.next; } node = list.get(list.size() - n); if (n == list.size()) { return list.get(0).next; } pre = list.get(list.size() - n - 1); pre.next = node.next; return list.get(0); } /* 快慢指针,first先走n步,然后和second一起遍历 */ }
package com.openfeint.game.archaeology.message; import com.openfeint.game.message.GenericMessage; public class NewPlayerMessag extends GenericMessage { private String playId; public NewPlayerMessag(String playId) { this.playId = playId; } public String getPlayId() { return playId; } }
import java.io.*; class Account {//implements Serializable{ private int accno; private float balance; /* System.out.println("Enter the balance"); balance=Float.parseFloat(br.readLine()); } catch (Exception e) { System.out.println(e.toString()); } }*/ public void disp(){ System.out.println("Account number ="+accno); System.out.println("Balance Amount ="+balance); } public float getBalance(){ return balance; } public void setBalance(float bal){ balance = bal; } } public class FileObject1{ public static void main(String []args){ /* try{//writing object into file Account [] obj = new Account[6] ; FileOutputStream fileout = new FileOutputStream("dasa"); ObjectOutputStream objout = new ObjectOutputStream(fileout); for(int i=0;i<3;i++){ obj[i]=new Account(); obj[i].read(); objout.writeObject(obj[i]); } objout.close(); } catch(Exception ex){ System.out.println(ex.toString()); }*/ //reading object from file try{ Account obj = new Account(); FileInputStream fis = new FileInputStream("dasa"); ObjectInputStream ois = new ObjectInputStream(fis); for(int i=0;i<3;i++){ try{ obj = (Account)ois.readObject(); } catch(Exception e){ } obj.disp(); System.out.println("Hello"); } ois.close(); } catch(Exception e){ } } }
package com.clicky.profepa; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import com.clicky.profepa.data.Documentos; import com.clicky.profepa.data.MateriaPrima; import com.clicky.profepa.data.PROFEPAPreferences; import com.clicky.profepa.utils.Utils; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.SaveCallback; import java.util.List; /** * * Created by Clicky on 4/3/15. * */ public class UpdateActivity extends ActionBarActivity{ private PROFEPAPreferences pref; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_update); pref = new PROFEPAPreferences(UpdateActivity.this); } @Override public void onResume(){ super.onResume(); if(Utils.isConnected(this)){ loadDocumentos(); } } private void toMain(){ pref.setIsFirst(false); Intent i = new Intent(UpdateActivity.this, MainActivity.class); startActivity(i); finish(); } private void loadDocumentos() { ParseQuery<Documentos> query = Documentos.getQuery(); query.include("Titular"); query.include("Transportista"); query.include("CAT"); query.findInBackground(new FindCallback<Documentos>() { public void done(List<Documentos> docs, ParseException e) { if (e == null) { if(!docs.isEmpty()){ pref.setLastUpdateDocs(docs.get(0).getUpdatedAt().toString()); } ParseObject.pinAllInBackground(docs,new SaveCallback() { public void done(ParseException e) { if (e == null) { if (!isFinishing()) { loadMateriaPrima(); } } else { Log.i("TodoListActivity", "Error pinning todos: " + e.getMessage()); } } }); } else { Log.i("TodoListActivity","loadDocumentos: Error finding pinned todos: "+ e.getMessage()); } } }); } private void loadMateriaPrima() { ParseQuery<MateriaPrima> query = MateriaPrima.getQuery(); query.findInBackground(new FindCallback<MateriaPrima>() { public void done(List<MateriaPrima> materia, ParseException e) { if (e == null) { if(!materia.isEmpty()){ pref.setLastUpdateMat(materia.get(0).getUpdatedAt().toString()); } ParseObject.pinAllInBackground(materia,new SaveCallback() { public void done(ParseException e) { if (e == null) { if (!isFinishing()) { toMain(); } } else { Log.i("TodoListActivity", "Error pinning todos: " + e.getMessage()); } } }); } else { Log.i("TodoListActivity","loadMateriaPrima: Error finding pinned todos: "+ e.getMessage()); } } }); } }
package com.citibank.ods.entity.pl.valueobject; /** * @author m.nakamura * * Representação da tabela de Requerimento de Execução de Processos de Carga. */ public class TplLoadProcExecRequestEntityVO extends BaseTplLoadProcExecRequestEntityVO { }
/* * 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.cache.interceptor; import org.springframework.lang.Nullable; /** * Abstract the invocation of a cache operation. * * <p>Does not provide a way to transmit checked exceptions but * provide a special exception that should be used to wrap any * exception that was thrown by the underlying invocation. * Callers are expected to handle this issue type specifically. * * @author Stephane Nicoll * @since 4.1 */ @FunctionalInterface public interface CacheOperationInvoker { /** * Invoke the cache operation defined by this instance. Wraps any exception * that is thrown during the invocation in a {@link ThrowableWrapper}. * @return the result of the operation * @throws ThrowableWrapper if an error occurred while invoking the operation */ @Nullable Object invoke() throws ThrowableWrapper; /** * Wrap any exception thrown while invoking {@link #invoke()}. */ @SuppressWarnings("serial") class ThrowableWrapper extends RuntimeException { private final Throwable original; public ThrowableWrapper(Throwable original) { super(original.getMessage(), original); this.original = original; } public Throwable getOriginal() { return this.original; } } }
package org.kuali.ole.docstore.document.rdbms; import org.kuali.ole.DocumentUniqueIDPrefix; import org.kuali.ole.docstore.model.rdbms.bo.BibRecord; import org.kuali.ole.docstore.model.xmlpojo.ingest.RequestDocument; import org.kuali.rice.krad.service.BusinessObjectService; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created with IntelliJ IDEA. * User: srirams * Date: 7/16/13 * Time: 5:13 PM * To change this template use File | Settings | File Templates. */ public class RdbmsWorkBibMarcDocumentManager extends RdbmsWorkBibDocumentManager { private static RdbmsWorkBibMarcDocumentManager ourInstance = null; public static RdbmsWorkBibMarcDocumentManager getInstance() { if (null == ourInstance) { ourInstance = new RdbmsWorkBibMarcDocumentManager(); } return ourInstance; } protected void modifyDocumentContent(RequestDocument doc, String identifier, BusinessObjectService businessObjectService) { String content = doc.getContent().getContent(); if (content != null && content != "" && content.length() > 0) { Pattern pattern = Pattern.compile("tag=\"001\">.*?</controlfield"); Pattern pattern2 = Pattern.compile("<controlfield.*?tag=\"001\"/>"); Matcher matcher = pattern.matcher(content); Matcher matcher2 = pattern2.matcher(content); if (matcher.find()) { doc.getContent().setContent(matcher.replaceAll("tag=\"001\">" + identifier + "</controlfield")); } else if (matcher2.find()) { doc.getContent() .setContent(matcher2.replaceAll("<controlfield tag=\"001\">" + identifier + "</controlfield>")); } else { int ind = content.indexOf("</leader>") + 9; if (ind == 8) { ind = content.indexOf("<leader/>") + 9; if (ind == 8) { ind = content.indexOf("record>") + 7; } } StringBuilder sb = new StringBuilder(); sb.append(content.substring(0, ind)); sb.append("<controlfield tag=\"001\">"); sb.append(identifier); sb.append("</controlfield>"); sb.append(content.substring(ind + 1)); doc.getContent().setContent(sb.toString()); } Map bibMap = new HashMap(); bibMap.put("bibId", DocumentUniqueIDPrefix.getDocumentId(identifier)); List<BibRecord> bibRecords = (List<BibRecord>) businessObjectService .findMatching(BibRecord.class, bibMap); if (bibRecords != null && bibRecords.size() > 0) { BibRecord bibRecord = bibRecords.get(0); bibRecord.setContent(doc.getContent().getContent()); businessObjectService.save(bibRecord); } } } }
package com.challenge.drawme.email; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.Toast; import com.challenge.drawme.R; import com.challenge.drawme.io.BitmapIo; /** * Utility for working with emails. */ public class EmailUtil { /* public static methods */ /** * Show an email chooser to allow the user to send an email with the screenshot as an attachment. * * @param context The current context. */ public static void sendEmail(Context context) { Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.setType("message/rfc822"); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "subject of email"); emailIntent.putExtra(Intent.EXTRA_TEXT, "body of email"); emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(BitmapIo.getFile())); try { context.startActivity(Intent.createChooser(emailIntent, context.getString(R.string.dialog_email_chooser))); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(context, context.getString(R.string.toast_no_email), Toast.LENGTH_SHORT).show(); } } }
package exercicio05; public class FabricaFiat implements FabricadeCarros { @Override public CarroSedan criarCarroSdedan() { return new Siena(); } @Override public CarroPopular criarCarroPopular() { return new Palio(); } }
package flowers.bean; import flowers.bean.ifaces.Flower; import java.awt.*; public class Daisy extends Flower { private static final int flowerPrice = 10; private static final String name = "Daisy"; public Daisy() { super(name, flowerPrice); } }
package dominio.participantes; public class Participante extends Pessoa { private String email; private int valorPagar; private int qtdConvidados; private String situacao; private boolean pago; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getValorPagar() { return valorPagar; } public void setValorPagar(int valorPagar) { this.valorPagar = valorPagar; } public int getQtdConvidados() { return qtdConvidados; } public void setQtdConvidados(int qtdConvidados) { this.qtdConvidados = qtdConvidados; } public String getSituacao() { return situacao; } public void setSituacao(String situacao) { this.situacao = situacao; } public boolean isPago() { return pago; } public void setPago(boolean pago) { this.pago = pago; } }
//accept MxN matrix n numbers calculate and display total count of even and odd? import java.util.*; class even_odd { public static void main (String[] args) { Scanner x=new Scanner(System.in); int r,c; System.out.print("Enter size of Row/dimminson:-"); int m=x.nextInt(); System.out.print("Enter size of columan Dimmision:-"); int n=x.nextInt(); int num [][]=new int[m][n]; int even=0,odd=0; for(r=0;r<m;r++){ System.out.println("Enter row value::"+(r+1)); for(c=0;c<n;c++){ System.out.print("Enter number"+(c+1)+":-"+" "); num[r][c]=x.nextInt(); if(num[r][c]%2==0) even++; else odd++; } } System.out.println("Total count of "+(m*n)+"matrix in Even number:-"+even); System.out.println("Total count of "+(m*n)+"matrix in Odd number:-"+odd); }//close of main }//close of class
public class Member { public Data currentSolution; public Data bestSolution; private FocusGroup group; public Data impact; public Member(Data impact,FocusGroup group) { this.impact = impact; this.group = group; } }
package com.pdd.pop.sdk.http.api.request; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.api.response.PddOneExpressCostTemplateResponse; import com.pdd.pop.sdk.http.HttpMethod; import com.pdd.pop.sdk.http.PopBaseHttpRequest; import com.pdd.pop.sdk.common.util.JsonUtil; import java.util.Map; import java.util.TreeMap; public class PddOneExpressCostTemplateRequest extends PopBaseHttpRequest<PddOneExpressCostTemplateResponse>{ /** * 运费模板id */ @JsonProperty("cost_template_id") private Long costTemplateId; @Override public String getVersion() { return "V1"; } @Override public String getDataType() { return "JSON"; } @Override public String getType() { return "pdd.one.express.cost.template"; } @Override public HttpMethod getHttpMethod() { return HttpMethod.POST; } @Override public Class<PddOneExpressCostTemplateResponse> getResponseClass() { return PddOneExpressCostTemplateResponse.class; } @Override public Map<String, String> getParamsMap() { Map<String, String> paramsMap = new TreeMap<String, String>(); paramsMap.put("version", getVersion()); paramsMap.put("data_type", getDataType()); paramsMap.put("type", getType()); paramsMap.put("timestamp", getTimestamp().toString()); if(costTemplateId != null) { paramsMap.put("cost_template_id", costTemplateId.toString()); } return paramsMap; } public void setCostTemplateId(Long costTemplateId) { this.costTemplateId = costTemplateId; } }
package io.github.zunpiau; import java.text.MessageFormat; public class Dict { private static final String BASE_VOICE_URL = "http://dict.youdao.com/dictvoice?audio="; private String word; private String phone; private String speech; public Dict(String word) { this.word = word; } public String getWord() { return word; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = "/" + phone + "/"; } public String getSpeech() { return speech; } public void setSpeech(String speech) { this.speech = speech; } private String generateLink(String phonation, String url) { if (phonation == null) { return ""; } else if (url == null) { return phonation; } else { return MessageFormat.format ("[{0}](" + BASE_VOICE_URL + "{1})", phonation, url); } } @Override public String toString() { return MessageFormat.format ("| {0} | {1} |", word, generateLink (phone, speech)); } }