text
stringlengths
10
2.72M
package com.belhomme.alexandre.sudokuandroid.objects; import java.util.Objects; public class Cellule { private int x; private int y; private int valeur; private boolean readOnly = false; public Cellule(int x, int y) { this.x = x; this.y = y; this.valeur = 0; } public Cellule(int x, int y, int valeur) { this.x = x; this.y = y; this.valeur = valeur; } public Cellule(int x, int y, int valeur, boolean readOnly) { this.x = x; this.y = y; this.valeur = valeur; this.readOnly = readOnly; } public int getY() { return y; } public int getX() { return x; } public int getValeur() { return valeur; } public boolean setValeur(int valeur) { if (valeur >= 0 && valeur < 10) { this.valeur = valeur; return true; } else return false; } public boolean isReadOnly() { return readOnly; } }
package com.mysql; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ColumnListHandler; import model.CarSaleModel; public class QueryRunnerTest { //获取数据库信息 static DataSource ds = getDataSource("jdbc:mysql://127.0.0.1:3306/csdncourse"); //使用QueryRunner库,操作数据库 static QueryRunner qr = new QueryRunner(ds); public static DataSource getDataSource(String connectURI){ BasicDataSource ds = new BasicDataSource(); //MySQL的jdbc驱动 ds.setDriverClassName("com.mysql.jdbc.Driver"); ds.setUsername("root"); //所要连接的数据库名 ds.setPassword("112233"); //MySQL的登陆密码 ds.setUrl(connectURI); return ds; } //第一类方法 public void executeUpdate(String sql){ try { qr.update(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //按照SQL查询多个结果,这里需要构建Bean对象 public <T> List<T> getListInfoBySQL (String sql, Class<T> type ){ List<T> list = null; try { list = qr.query(sql,new BeanListHandler<T>(type)); } catch (SQLException e) { e.printStackTrace(); } return list; } //查询一列 @SuppressWarnings({ "unchecked", "rawtypes" }) public List<Object> getListOneBySQL (String sql,String id){ List<Object> list=null; try { list = (List<Object>) qr.query(sql, new ColumnListHandler(id)); } catch (SQLException e) { e.printStackTrace(); } return list; } //将所爬数据插入数据库 public static void insertData ( List<CarSaleModel> datalist ) { Object[][] params = new Object[datalist.size()][2]; for ( int i = 0; i < datalist.size(); i++ ){ //需要存储的字段 params[i][0] = datalist.get(i).getMonth(); params[i][1] = datalist.get(i).getSales(); } QueryRunner qr = new QueryRunner(ds); try { //执行批处理语句 qr.batch("INSERT INTO carsales(month,sales) VALUES (?,?)", params); } catch (SQLException e) { System.out.println(e); } System.out.println("新闻数据入库完毕"); } public static void main(String[] args) { QueryRunnerTest QueryRunnerTest = new QueryRunnerTest(); //执行更新操作 QueryRunnerTest.executeUpdate("update carsales set sales = '4000' where month = '2017-10-01'"); //执行更新操作 System.out.println("更新操作完成!"); //查询单列 List<Object> listdata = QueryRunnerTest.getListOneBySQL("select sales from carsales", "sales"); for (int i = 0; i < listdata.size(); i++) { System.out.println(listdata.get(i).toString()); } System.out.println("按列读取数据完成!"); //查询多列 List<CarSaleModel> mutllistdata = QueryRunnerTest.getListInfoBySQL("select month,sales from carsales", CarSaleModel.class); for (CarSaleModel model : mutllistdata) { System.out.println(model.getMonth() + "\t" +model.getSales()); } System.out.println("读取多列数据完成"); } }
package com.tuyenmonkey.tlist.ui; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.tuyenmonkey.tlist.R; import com.tuyenmonkey.tlist.base.BaseFragment; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.util.ArrayList; import java.util.List; import butterknife.Bind; /** * Created by Tiki on 3/2/16. */ public class ListFragment extends BaseFragment { @Bind(R.id.rv_list) RecyclerView rvList; private ListAdapter mAdapter; private LinearLayoutManager mLayoutManager; private List<String> mNames; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); } @Override public void onDestroy() { EventBus.getDefault().unregister(this); super.onDestroy(); } @Override protected int getLayoutId() { return R.layout.fragment_list; } @Override protected void setUpUI() { mLayoutManager = new LinearLayoutManager(getContext()); rvList.setLayoutManager(mLayoutManager); } @Override protected void initialize() { mNames = getDummyData(); mAdapter = new ListAdapter(getContext(), mNames); rvList.setAdapter(mAdapter); } @Subscribe public void onEvent(ListAdapter.DeleteItemEvent event) { mAdapter.remove(event.name); } @Subscribe public void onEvent(ListAdapter.AddItemEvent event) { String newName = event.name + String.valueOf(event.position); mAdapter.insert(event.position, newName); } private List<String> getDummyData() { List<String> names = new ArrayList<>(); names.add("Tuyen"); names.add("Quan"); names.add("Viet"); names.add("Giang"); names.add("Cuong"); names.add("Khoi"); return names; } }
package com.codecool.movieorganizer.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.*; import org.hibernate.annotations.NaturalId; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToMany; import java.util.HashSet; import java.util.Objects; import javax.persistence.*; import java.util.Set; @Entity @Getter @Setter @ToString @Builder @NoArgsConstructor @AllArgsConstructor public class Artist { @Id @GeneratedValue private long id; @NaturalId private String name; @JsonIgnore @OneToMany(mappedBy = "actor") Set<CharacterActorMovieMap> characterActorMovieMaps; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Artist artist = (Artist) o; return Objects.equals(name, artist.name); } @Override public int hashCode() { return Objects.hash("artist", name); } }
package com.Study.day1; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class FindElementDay06 { WebDriver wb; //查找页面元素id @Test public void OpenChrome() throws InterruptedException { System.setProperty("webdriver.chrome.driver","E:\\IDEAProject\\drivers\\chromedriver.exe"); wb = new ChromeDriver(); wb.get("https://www.baidu.com"); Thread.sleep(3000); WebElement fileElement = wb.findElement(By.id("kw")); Thread.sleep(2000); wb.quit(); } //查找页面元素name、class @Test public void findbyName1() throws InterruptedException{ System.setProperty("webdriver.chrome.driver","E:\\IDEAProject\\drivers\\chromedriver.exe"); wb = new ChromeDriver(); wb.get("https://www.baidu.com"); Thread.sleep(3000); WebElement file = wb.findElement(By.name("tj_settingicon")); Thread.sleep(2000); wb.quit(); } @Test public void findbyClass1() throws InterruptedException { System.setProperty("webdriver.chrome.driver","E:\\IDEAProject\\drivers\\chromedriver.exe"); wb = new ChromeDriver(); wb.get("https://www.baidu.com"); Thread.sleep(3000); WebElement file = wb.findElement(By.className("mnav")); Thread.sleep(2000); wb.quit(); } }
package ch.ethz.geco.t4j.obj.base; public interface Closable { /** * Returns whether the object is still open or not. When an object was closed * this often means that it cannot be modified anymore. * * @return whether the object is still open or not. */ Boolean isOpen(); }
package com.lenovohit.hwe.pay.exception; import java.io.PrintWriter; import java.io.StringWriter; /** * 交易异常记录,包括交易码,错误级别,以及异常信息 * <p>异常码组成规则说明:异常码由8位数字组成,第1位代表错误级别,第2-4位代表模块编号,第5-8位为错误编号</p> * <p>一级级别,错误级别说明:9-"ERROR", 4-"WARN", 1-"INFO", 0-"DEFAULT" 默认"0"</p> * <p>二级业务,业务模块说明:000-"系统错误", 100-"支付业务异常", 900-"其他错误"</p> * <p>三级系统错误码,系统错误说明:0000-"程序错误", 1000-"文件错误",2000-"数据库错误",3000-"数据库异常"....9000-"其他错误"</p> * <p>三级业务错误码,业务异常说明:00xx-"预留", 10xx-"数据错误",20xx-"权限错误",30xx-"交易异常",40xx-"第三方异常",50xx-"账务异常"....9000-"其他错误"</p> * <p>数据错误说明:00-"预留", 1x-"非空字段未空",2x-"数据格式错误",3x-"业务控制错误",....</p> * <p>权限错误说明:00-"预留", 1x-"商户账户状态错误",2x-"开通支付渠道权限错误",3x-"开通费种权限错误"</p> * <p>交易错误说明:00-"预留", 1x-"数据错误",2x-"签名错误",3x-"网络错误"</p> * <p>第三方错误说明:00-"预留", 1x-"数据错误",2x-"签名错误",3x-"网络错误"</p> * <p>账务异常说明:00-"预留"</p> */ public class PayException extends RuntimeException { private static final long serialVersionUID = -623045610790927931L; private static String EXCEPTION_CODE_DEFAULT = "00000000";//系统默认错误 protected String exceptionCode; protected String exceptionMsg; protected ExceptionLevel level; public PayException() { } public PayException(String message) { super(); this.exceptionMsg = message; this.exceptionCode = EXCEPTION_CODE_DEFAULT; } public PayException(PayException e) { super(); this.exceptionCode = e.getExceptionCode(); this.exceptionMsg = e.getExceptionMsg(); } public PayException(Exception e) { super(getTraceMessage(e)); this.exceptionCode = EXCEPTION_CODE_DEFAULT; this.exceptionMsg = e.getMessage(); } public PayException(Throwable cause) { super(cause); this.exceptionCode = EXCEPTION_CODE_DEFAULT; this.exceptionMsg = cause.getMessage(); } public PayException(String exceptionCode, String message) { super(message); this.exceptionCode = exceptionCode; this.exceptionMsg = message; } public PayException(String exceptionCode, Exception e) { super(getTraceMessage(e)); this.exceptionCode = exceptionCode; this.exceptionMsg = e.getMessage(); } public PayException(String exceptionCode, Throwable cause) { super(cause); this.exceptionCode = exceptionCode; this.exceptionMsg = cause.getMessage(); } public String getExceptionCode() { return this.exceptionCode; } public void setExceptionCode(String exceptionCode) { this.exceptionCode = exceptionCode; } public String getExceptionMsg() { return exceptionMsg; } public void setExceptionMsg(String exceptionMsg) { this.exceptionMsg = exceptionMsg; } public ExceptionLevel getLevel(){ switch (Integer.valueOf(exceptionCode) / 10000000) { case 1: this.level = ExceptionLevel.EXCEPTION_LEVEL_INFO; break; case 2: this.level = ExceptionLevel.EXCEPTION_LEVEL_INFO; break; case 3: this.level = ExceptionLevel.EXCEPTION_LEVEL_INFO; break; case 4: this.level = ExceptionLevel.EXCEPTION_LEVEL_WARN; break; case 5: this.level = ExceptionLevel.EXCEPTION_LEVEL_WARN; break; case 6: this.level = ExceptionLevel.EXCEPTION_LEVEL_WARN; break; case 7: this.level = ExceptionLevel.EXCEPTION_LEVEL_ERROR; break; case 8: this.level = ExceptionLevel.EXCEPTION_LEVEL_ERROR; break; case 9: this.level = ExceptionLevel.EXCEPTION_LEVEL_ERROR; break; default: this.level = ExceptionLevel.EXCEPTION_LEVEL_UNDEFINED; break; } return this.level; } public void setExceptionLevel(ExceptionLevel level){ this.level = level; } public String getExceptionCodeAndMessage() { return " 错误号:【"+this.getExceptionCode() + "】<br/>" + this.getExceptionMsg(); } static String getTraceMessage(Exception e){ StringWriter stringWriter = new StringWriter(); e.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } }
import java.util.Scanner; /** * 입력받은 10진수를 2~36진수로 기수 변환하여 나타냄 */ public class DoIt_Q8 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); int no; //변환하는 정수 int cd; //기수 int dno; //변환 후의 자릿수 char[] cno = new char[32]; // 변환 후 각 자리의 숫자를 넣어두는 문자열 System.out.println("10진수를 기수로 변환합니다."); do { System.out.print("변환하는 음이 아닌 정수 : "); no = stdIn.nextInt(); } while (no < 0); do { System.out.print("어떤 진수로 변환할까요? (2~36) : "); cd = stdIn.nextInt(); } while (cd < 2 || cd > 36); cardConvDetail(no, cd, cno); } // x 를 r 진수로 변환하여 배열 d에 아랫자리 부터 넣어두고 자릿수를 반환 static int cardConvR(int x, int r, char[] d) { int digits = 0; String dchar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; do { d[digits++] = dchar.charAt(x % r); x /= r; } while (x != 0); return digits; } //배열의 앞쪽에 윗자리를 넣어두는 메소드 static int cardConv(int x, int r, char[] d) { int digits = 0; String dchar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; do { d[digits++] = dchar.charAt(x % r); x = x / r; } while (x != 0); // 배열을 반대로 정렬 for (int i = 0; i < d.length / 2; i++) { char temp = d[i]; d[i] = d[d.length - i - 1]; d[d.length - i - 1] = temp; } return digits; } // 기수 변환 과정을 자세히 나타내는 메소드 static void cardConvDetail(int x, int r, char[] d) { int digits = 0; String dchar = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println(r + " | " + x); do { System.out.println(" + ---------------"); System.out.println(r + " | " + x / r + " ... " + dchar.charAt(x % r)); d[digits++] = dchar.charAt(x % r); x = x / r; } while (x != 0); System.out.print(r + " 진수로 "); // 배열을 반대로 정렬 for (int i = 0; i < d.length / 2; i++) { char temp = d[i]; d[i] = d[d.length - i - 1]; d[d.length - i - 1] = temp; } // 배열 출력 for (int i = 0; i < d.length; i++) { System.out.print(d[i]); } System.out.println("입니다."); } }
package insa; public class Insa { private String name; public void setName(String name) { this.name=name; //나중에 인자가 객체로 넘어올 수 있다..//setter injection } public String insaGo(String str) { return this.name+" 님\n"+str; } }
package com.infoworks.lab.client.jersey; import com.infoworks.lab.exceptions.HttpInvocationException; import com.infoworks.lab.rest.breaker.CircuitBreaker; import com.infoworks.lab.rest.models.Message; import com.infoworks.lab.rest.models.QueryParam; import com.infoworks.lab.rest.template.HttpInteractor; import com.infoworks.lab.rest.template.Invocation; import com.infoworks.lab.rest.template.Route; import com.it.soul.lab.sql.entity.EntityInterface; import com.it.soul.lab.sql.query.models.Property; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; public class HttpTemplate<P extends com.infoworks.lab.rest.models.Response, C extends EntityInterface> extends HttpAbstractTemplate implements HttpInteractor<P,C> { private String _domain; private Class<P> inferredProduce; private Class<C> inferredConsume; private List<Property> properties = new ArrayList<>(); public HttpTemplate(){ /*Must needed to create dynamic instance from type*/ super(); } public HttpTemplate(Object...config){ try { configure(config); } catch (InstantiationException e) { e.printStackTrace(); } } @Override @SuppressWarnings("Duplicates") public void configure(Object... config) throws InstantiationException{ if (config == null) throw new InstantiationException(); Arrays.stream(config).forEach(o -> { if (o instanceof URI){ _domain = ((URI)o).toString(); }else if(o instanceof Property) { properties.add((Property) o); }else if (o instanceof Class<?>){ if (inferredProduce == null) inferredProduce = (Class<P>) o; else if (inferredConsume == null) inferredConsume = (Class<C>) o; } }); } private Class<P> getInferredProduce(){ if (inferredProduce == null) inferredProduce = (Class<P>) com.infoworks.lab.rest.models.Response.class; return inferredProduce; } private Class<? extends EntityInterface> getInferredConsume(){ if (inferredConsume == null) inferredConsume = (Class<C>) Message.class; return inferredConsume; } public Property[] getProperties(){ return properties.toArray(new Property[0]); } @Override protected synchronized String domain() throws MalformedURLException { _domain = String.format("%s%s:%s%s", schema(), host(), port(), validatePaths(api())); validateURL(_domain); return _domain; } protected String schema(){ return "http://"; } protected String host(){ return "localhost"; } protected Integer port(){ return 8080; } protected String api(){ return ""; } protected URL validateURL(String urlStr) throws MalformedURLException{ return new URL(urlStr); } protected String routePath() { String routeTo = "/"; if (getClass().isAnnotationPresent(Route.class)){ routeTo = getClass().getAnnotation(Route.class).value(); } return routeTo; } public P get(C consume, QueryParam...params) throws HttpInvocationException { P produce = null; Class<P> type = getInferredProduce(); try { //Finding those are intended to be path: e.g. new QueryParam("key", "") OR new QueryParam("key", null) if (params != null && params.length > 0) { String[] paths = parsePathsFrom(params); target = initializeTarget(paths); mutateTargetWith(params); }else{ target = initializeTarget(); } // Response response; if (isSecure(consume)){ response = getAuthorizedJsonRequest(consume).get(); }else{ response = getJsonRequest().get(); } produce = inflate(response, type); }catch (IOException e) { e.printStackTrace(); } return produce; } private String[] parsePathsFrom(QueryParam...params){ return Arrays.stream(params) .filter(query -> query.getValue() == null || query.getValue().isEmpty()) .map(query -> query.getKey()) .collect(Collectors.toList()).toArray(new String[0]); } private void mutateTargetWith(QueryParam...params){ if (target == null) return; Arrays.stream(params) .filter(query -> query.getValue() != null && !query.getValue().isEmpty()) .forEach(query -> target = getTarget().queryParam(query.getKey(), query.getValue())); } public P post(C consume, String...paths) throws HttpInvocationException { P produce = null; Class<P> type = getInferredProduce(); try { target = initializeTarget(paths); Response response; if (isSecure(consume)){ response = getAuthorizedJsonRequest(consume) .post(consume, MediaType.APPLICATION_JSON_TYPE); }else{ response = getJsonRequest().post(consume, MediaType.APPLICATION_JSON_TYPE); } produce = inflate(response, type); }catch (IOException e) { e.printStackTrace(); } return produce; } public P put(C consume , String...paths) throws HttpInvocationException { P produce = null; Class<P> type = getInferredProduce(); try { target = initializeTarget(paths); Response response; if (isSecure(consume)){ response = getAuthorizedJsonRequest(consume) .put(consume, MediaType.APPLICATION_JSON_TYPE); }else{ response = getJsonRequest().put(consume, MediaType.APPLICATION_JSON_TYPE); } produce = inflate(response, type); }catch (IOException e) { e.printStackTrace(); } return produce; } public boolean delete(C consume, QueryParam...params) throws HttpInvocationException { try { //Finding those are intended to be path: e.g. new QueryParam("key", "") OR new QueryParam("key", null) if (params != null && params.length > 0) { String[] paths = parsePathsFrom(params); target = initializeTarget(paths); mutateTargetWith(params); }else { target = initializeTarget(); } // Response response; if (isSecure(consume)){ response = getAuthorizedJsonRequest(consume) .delete(consume, MediaType.APPLICATION_JSON_TYPE); }else{ response = getJsonRequest().delete(consume, MediaType.APPLICATION_JSON_TYPE); } if (response.getStatusInfo() == Response.Status.INTERNAL_SERVER_ERROR) throw new HttpInvocationException("Internal Server Error!"); return response.getStatusInfo() == Response.Status.OK; }catch (IOException e) { e.printStackTrace(); } return false; } private WebTarget target; @Override public WebTarget getTarget() { return target; } @Override public void setTarget(WebTarget target) { this.target = target; } @SuppressWarnings("Duplicates") public void get(C consume , List<QueryParam> query , Consumer<P> consumer){ //Add to Queue addConsumer(consumer); submit(() ->{ P produce = null; try { QueryParam[] items = (query == null) ? new QueryParam[0] : query.toArray(new QueryParam[0]); produce = get(consume, items); } catch (HttpInvocationException e) { e.printStackTrace(); } notify(produce); }); } @SuppressWarnings("Duplicates") public void delete(C consume , List<QueryParam> query , Consumer<P> consumer){ //Add to Queue addConsumer(consumer); submit(() ->{ Boolean produce = null; try { QueryParam[] items = (query == null) ? new QueryParam[0] : query.toArray(new QueryParam[0]); produce = delete(consume, items); } catch (HttpInvocationException e) { e.printStackTrace(); } notify(produce); }); } @Override public <T> URI getUri(T... params) { return getTarget().getUri(); } @SuppressWarnings("Duplicates") public void post(C consume , List<String> paths , Consumer<P> consumer){ //Add to queue addConsumer(consumer); submit(() -> { P produce = null; try { String[] items = (paths == null) ? new String[0] : paths.toArray(new String[0]); produce = post(consume, items); } catch (HttpInvocationException e) { e.printStackTrace(); } notify(produce); }); } @SuppressWarnings("Duplicates") public void put(C consume , List<String> paths , Consumer<P> consumer){ //Add to queue addConsumer(consumer); submit(() -> { P produce = null; try { String[] items = (paths == null) ? new String[0] : paths.toArray(new String[0]); produce = put(consume, items); } catch (HttpInvocationException e) { e.printStackTrace(); } notify(produce); }); } protected <T extends Object> Response execute(EntityInterface consume, Invocation.Method method, T...params) throws MalformedURLException, HttpInvocationException { if (params != null){ if (params instanceof String[]){ setTarget(initializeTarget((String[]) params)); }else if (params instanceof QueryParam[]){ setTarget(initializeTarget()); Arrays.stream((QueryParam[])params).forEach(param -> setTarget(getTarget().queryParam(param.getKey(), param.getValue())) ); }else{ //Means T...params are arbitrary value e.g. "/path-a", "path-b", QueryParam("offset","0"), QueryParam("limit","10") ... etc //First: Separate Paths from mixed array: String[] paths = Arrays.stream(params).filter(obj -> obj instanceof String).collect(Collectors.toList()).toArray(new String[0]); setTarget(initializeTarget(paths)); //Then: Separate QueryParam from mixed array: QueryParam[] queryParams = Arrays.stream(params).filter(obj -> obj instanceof QueryParam).collect(Collectors.toList()).toArray(new QueryParam[0]); Arrays.stream(queryParams).forEach(param -> setTarget(getTarget().queryParam(param.getKey(), param.getValue())) ); } }else { setTarget(initializeTarget()); } return execute(consume, method); } private Response execute(EntityInterface consume, Invocation.Method method) throws HttpInvocationException { //CircuitBreaker CODE: Response response = null; try { CircuitBreaker breaker = CircuitBreaker.create(HttpCircuitBreaker.class); Invocation invocation = isSecure(consume) ? getAuthorizedJsonRequest(consume) : getJsonRequest(); if (breaker != null) response = (Response) breaker.call(invocation, method, consume); else response = callForwarding(invocation, method, consume); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } // return response; } @SuppressWarnings("Duplicates") protected Response callForwarding(Invocation invocation, Invocation.Method method, EntityInterface data) throws HttpInvocationException { Response response = null; switch (method){ case GET: response = (Response) invocation.get(); break; case POST: response = (Response) invocation.post(data, MediaType.APPLICATION_JSON_TYPE); break; case DELETE: response = (Response) invocation.delete(data, MediaType.APPLICATION_JSON_TYPE); break; case PUT: response = (Response) invocation.put(data, MediaType.APPLICATION_JSON_TYPE); break; } return response; } }
package com.soa.domain; import lombok.Getter; import lombok.RequiredArgsConstructor; @Getter @RequiredArgsConstructor public enum Power { POWER_1(1), POWER_2(2), POWER_3(3); private final Integer intValue; }
package com.pshc.cmg.controller; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.web.PageableDefault; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.pshc.cmg.dto.PostDto; import com.pshc.cmg.model.LoggedUser; import com.pshc.cmg.model.PostCondition; import com.pshc.cmg.service.BoardTypeService; import com.pshc.cmg.service.PageMaker; import com.pshc.cmg.service.PostComentService; import com.pshc.cmg.service.PostService; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; @Controller @RequestMapping("/post") @AllArgsConstructor @Slf4j public class PostController { private final String PRIFIX = "/post"; private BoardTypeService boardTypeService; private PostService postService; private PostComentService comentService; //private FirebaseService firebeseService; private PostDto postDto; private PageMaker pageMaker; @GetMapping("/{id}") public String Mainview(@PathVariable int id, Model model, @PageableDefault(sort = { "id" }, direction = Direction.DESC, size = 8) Pageable pageable, PostCondition postCondition) { log.info(postCondition.getCondition()); Page page = postService.findPage(postCondition, pageable, id); pageMaker.pageData(page, postCondition); model.addAttribute("postList", page); model.addAttribute("boardList", boardTypeService.findActiveBoardType()); model.addAttribute("board", boardTypeService.findOne(id)); model.addAttribute("pageMaker", pageMaker); model.addAttribute("postcondition", postCondition); return PRIFIX + "/index"; } @GetMapping("/new/{id}") public String newPostView(@PathVariable int id, Model model) { model.addAttribute("boardTypeId", id); model.addAttribute("post", postDto); model.addAttribute("boardList", boardTypeService.findActiveBoardType()); return PRIFIX + "/new"; } @GetMapping("/detail/{id}") public String detailView(@PathVariable int id, Model model, @AuthenticationPrincipal LoggedUser customUser, @PageableDefault(sort = { "createdatetime" }, direction = Direction.DESC, size = 10) Pageable pageable) { model.addAttribute("post", postService.findOne(id)); model.addAttribute("coments", comentService.findById(id, pageable)); model.addAttribute("user", customUser); model.addAttribute("boardList", boardTypeService.findActiveBoardType()); postService.setUpCount(id); return PRIFIX + "/detail"; } @GetMapping("/edit/{id}") public String editView(@PathVariable int id, Model model) { model.addAttribute("post", postService.findOne(id)); model.addAttribute("boardList", boardTypeService.findActiveBoardType()); return PRIFIX + "/edit"; } @PostMapping public String createPost(PostDto postDto, @AuthenticationPrincipal LoggedUser customUser) { log.info(postDto.toString()); int boardTypeId = postDto.getBoardtypeid(); postService.save(postDto, customUser.getUsername()); //firebeseService.sendTopicsMessaging(postDto); return "redirect:/post/" + boardTypeId; } @PutMapping public String edit(PostDto postDto) { log.info(postDto.toString()); int boardTypeId = postDto.getBoardtypeid(); postService.update(postDto); return "redirect:/post/" + boardTypeId; } @DeleteMapping @ResponseBody public String delete(@RequestBody PostDto postDto) { log.info(postDto.toString()); postService.delete(postDto); return "success"; } }
package practices.written; /** * ÒøÐлµÕË */ import java.util.Scanner; public class BankBadDebts { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); String[] strs = str.split(" "); long n = Long.parseLong(strs[0]); long w = Long.parseLong(strs[1]); long k = 100003; long n1 = n % k; long n2 = (n - 1) % k; long result1 = n1; for (long i = 1; i < w; i++) { result1 = (result1 * n1) % k; } long result2 = n % k; for (int i = 1; i < w; i++) { result1 = (result1 * n2) % k; } System.out.println((result1 - result2 + k) % k); System.out.println(n * (w - 1) % k); } }
import dataFactory.impl.OrderMysqlDataHelper; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import po.OrderEvaluationPO; import po.OrderPO; import java.util.Map; import static org.junit.Assert.assertEquals; /** * OrderMysqlDataHelper Tester. * * @author <Authors name> * @since <pre>十一月 25, 2016</pre> * @version 1.0 */ public class OrderMysqlDataHelperTest { Map<Integer, OrderPO> map; Map<Integer, OrderEvaluationPO> orderEvaluationPOMap; OrderMysqlDataHelper orderMysqlDataHelper=new OrderMysqlDataHelper(); @Before public void setUp(){ map=orderMysqlDataHelper.getOrderData(); orderEvaluationPOMap=orderMysqlDataHelper.getEvaluation(); } @After public void after() throws Exception { } /** * * Method: updateOrderEvaluation(OrderEvaluationPO oepo) * */ @Test@Ignore public void testUpdateOrderEvaluation() throws Exception { //TODO: Test goes here... OrderEvaluationPO oepo=new OrderEvaluationPO(2,4.0,"天啦"); OrderEvaluationPO oldOepo1=orderEvaluationPOMap.get(2); orderEvaluationPOMap=orderMysqlDataHelper.updateOrderEvaluation(oepo); assertEquals("天啦",orderEvaluationPOMap.get(2).getPingjia()); assertEquals(4.0,orderEvaluationPOMap.get(2).getPingfen(),0); //还原数据库 orderEvaluationPOMap=orderMysqlDataHelper.updateOrderEvaluation(oldOepo1); } /** * * Method: insertOrder(OrderPO opo) * */ @Test@Ignore public void testInsertOrder() throws Exception { //TODO: Test goes here... int OrderID= MockOrderProcesser.getOrderID(); //System.out.println(OrderID); OrderPO opo=new OrderPO(OrderID,"arlo","如家","未执行","大床房",4,5,"no","2016-11-30 10:11:12",null,"2016-12-30 12:00:00",null,380,300,3000); /*OrderPO opo=map.get(6); opo.setOrderID(OrderID); opo.setCheckOutTime(null); */ map=orderMysqlDataHelper.insertOrder(opo); OrderPO newopo=map.get(OrderID); //System.out.println(newopo.getOrderID()); //assertEquals(OrderID,newopo.getOrderID(),0); assertEquals(opo.getStatus(),newopo.getStatus()); assertEquals(opo.getRoomID(),newopo.getRoomID()); assertEquals(opo.getRoomNum(),newopo.getRoomNum(),0); assertEquals("1970-01-01 00:00:01",newopo.getCheckOutTime()); } /** * * Method: deleteOrderByID(int OrderID) * */ @Test@Ignore public void testDeleteOrderByID() throws Exception { //TODO: Test goes here... OrderPO oldopo=map.get(2); map=orderMysqlDataHelper.deleteOrderByID(2); assertEquals("已撤销",map.get(2).getStatus()); //恢复数据库,顺便测试updateOrder map=orderMysqlDataHelper.updateOrder(oldopo); assertEquals("已执行",map.get(2).getStatus()); } /** * * Method: updateOrder(OrderPO opo) * */ @Test@Ignore public void testUpdateOrder() throws Exception { //TODO: Test goes here... OrderPO oldpo=map.get(3); OrderPO newpo=new OrderPO(3,"arloo","如家","未执行","标间",4,5,"no","2016-11-30 10:11:12","2016-11-30 10:11:12","2016-12-30 12:00:00","2000-04-21 12:00:00",380,300,3000); map=orderMysqlDataHelper.updateOrder(newpo); newpo=map.get(3); assertEquals("arloor",newpo.getCustomerID()); assertEquals("汉廷",newpo.getHotel()); assertEquals("未执行",newpo.getStatus()); assertEquals("大床房",newpo.getRoomID()); assertEquals("2016-11-30 10:11:12",newpo.getLastCheckInTime()); assertEquals("2000-04-21 12:00:00",newpo.getCheckOutTime()); } }
package org.nhnnext.web; import java.util.List; 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; @Entity public class Board { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(length = 100, nullable = false) private String title; @Column(length = 5000, nullable = false) private String contents; @Column(length = 1000, nullable = false) private String fileName; @OneToMany(mappedBy = "board", fetch = FetchType.EAGER) private List<Comment> comments; public void setComments(List<Comment> comments) { this.comments = comments; } public List<Comment> getComments() { return comments; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContents() { return contents; } public void setContents(String contents) { this.contents = contents; } public Long getId() { return id; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } @Override public String toString() { return "Board [title=" + title + ", contents=" + contents + "]"; } }
package com.cssl.oop.demo05; //计算器类 /* * 根据用户选择运算符,进行运算并返回结果 */ public class JiQuanQi { public void add(int num1, int num2) { System.out.println("运算结果为:" + (num1 + num2)); } public void add(int num1, double num2) { System.out.println("运算结果为:" + (num1 + num2)); } public void jian(int num1, int num2) { System.out.println("运算结果为:" + (num1 - num2)); } public void jian(int num1, double num2) { System.out.println("运算结果为:"+ (num1 - num2)); } public void chengFa(int num1, double num2) { System.out.println("运算结果为:" + (num1 * num2)); } public void chengFa(int num1, int num2) { System.out.println("运算结果为:" + (num1 * num2)); } public void chengFa(double num1,int num2){ System.out.println("运算结果为:" + (num1 * num2)); } public void chuFa(int num1, double num2) { System.out.println("运算结果为:" + (num1 / num2)); } public void chuFa(int num1, int num2) { System.out.println("运算结果为:" + (num1 / num2)); } public void chuFa(double num1, int num2) { System.out.println("运算结果为:" + (num1 / num2)); } }
/* * Copyright 2002-2022 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.beans.factory.annotation; import jakarta.inject.Inject; import jakarta.inject.Qualifier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; import org.springframework.beans.factory.aot.AotServices; import org.springframework.util.ClassUtils; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link JakartaAnnotationsRuntimeHints}. * * @author Brian Clozel */ class JakartaAnnotationsRuntimeHintsTests { private final RuntimeHints hints = new RuntimeHints(); @BeforeEach void setup() { AotServices.factories().load(RuntimeHintsRegistrar.class) .forEach(registrar -> registrar.registerHints(this.hints, ClassUtils.getDefaultClassLoader())); } @Test void jakartaInjectAnnotationHasHints() { assertThat(RuntimeHintsPredicates.reflection().onType(Inject.class)).accepts(this.hints); } @Test void jakartaQualifierAnnotationHasHints() { assertThat(RuntimeHintsPredicates.reflection().onType(Qualifier.class)).accepts(this.hints); } }
package com.example.onix_android.Models; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.example.onix_android.Interfaces.ItemClickListener; import com.example.onix_android.R; public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener { TextView title, dateCreate, tag, text; LinearLayout color; ItemClickListener itemClickListener; public MyHolder(@NonNull View itemView) { super(itemView); this.text = itemView.findViewById(R.id.text); this.title = itemView.findViewById(R.id.title); this.tag = itemView.findViewById(R.id.tag); this.color = itemView.findViewById(R.id.to_change_color); this.dateCreate = itemView.findViewById(R.id.date_created); itemView.setOnClickListener(this); } @Override public void onClick(View v) { this.itemClickListener.onClickListener(v, getLayoutPosition()); } public void setItemClickListener(ItemClickListener ic) { this.itemClickListener = ic; } }
package com.docker.annotations; import java.lang.annotation.*; @Target(value = {ElementType.METHOD}) @Retention(value = RetentionPolicy.RUNTIME) @Documented public @interface PeriodicTask { //业务自行指定,每个任务type固定,最好带上项目标识 public String type(); //间隔时间(单位:秒) public int period() default 0; // 第一次执行时间 2018-1-3 11:00:00 public String scheduleTime() default ""; //时区 public String timezone() default "Asia/Shanghai"; //是否自动开始,true为立即开始,不用触发;false相反 public boolean autoStart() default true; //失败了尝试多少次 int tryTimes() default 100; //失败了每次尝试间隔多少时间(单位:秒) int tryPeriod() default 30; //cron表达式 String cron() default ""; int allowedExpireSeconds() default 0; }
package com.atakan.app.converter; import org.apache.tomcat.util.codec.binary.Base64; import com.vaadin.server.ExternalResource; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.ui.Image; @SpringComponent public class Convert { public Convert() { } public Image bytesToResource(byte[] bs) { String url = "data:"+"image/png"+";base64," + Base64.encodeBase64String(bs); Image image = new Image("", new ExternalResource(url)); return image; } }
package com.liujc.codeencapsulation; import android.app.Application; import com.liujc.commonlibrary.AppContext; import com.liujc.commonlibrary.ApplicationAsLibrary; import com.liujc.httplib.HttpBaseContext; import com.liujc.modulea.ApplicationA; import java.util.ArrayList; import java.util.List; /** * 类名称:MainApplication * 创建者:Create by liujc * 创建时间:Create on 2017/3/30 10:46 * 描述:TODO */ public class MainApplication extends Application { private List<ApplicationAsLibrary> mChildApplicationList = new ArrayList<>(); @Override public void onCreate() { super.onCreate(); AppContext.init(getApplicationContext()); HttpBaseContext.init(getApplicationContext()); mChildApplicationList.add(new ApplicationA()); // mChildApplicationList.add(new ApplicationB()); for (ApplicationAsLibrary app : mChildApplicationList) { app.onCreateAsLibrary(this); } } @Override public void onTrimMemory(int level) { super.onTrimMemory(level); for (ApplicationAsLibrary app : mChildApplicationList) { app.onTrimMemoryAsLibrary(this, level); } } @Override public void onLowMemory() { super.onLowMemory(); for (ApplicationAsLibrary app : mChildApplicationList) { app.onLowMemoryAsLibrary(this); } } }
package com.Memento.phone; /** * Created by Valentine on 2018/5/11. */ public class Client { public static void main(String[] args){ PhoneOriginator phone = new PhoneOriginator(); phone.setName("hello"); phone.setNumber("123"); phone.show(); PhoneCaretaker pcaretaker = new PhoneCaretaker(); pcaretaker.setMemento(phone.saveMemento()); phone.setNumber("321"); phone.setName("world"); phone.show(); phone.resumeMemento(pcaretaker.getMemento()); phone.show(); } }
package com.wenyuankeji.spring.dao.impl; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Repository; import com.wenyuankeji.spring.dao.IBaseConfigDao; import com.wenyuankeji.spring.model.BaseBusinessareaModel; import com.wenyuankeji.spring.model.BaseConfigModel; import com.wenyuankeji.spring.util.BaseException; @Repository public class BaseConfigDaoImpl implements IBaseConfigDao { @Resource(name = "sessionFactory") private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public SessionFactory getSessionFactory() { return sessionFactory; } @Override public BaseConfigModel searchBaseConfigByCode(String configcode) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { String hql = "FROM BaseConfigModel WHERE configcode=? order by sortnum,configid"; Query query = session.createQuery(hql); query.setString(0, configcode); BaseConfigModel baseConfig = new BaseConfigModel(); if (query.list() != null && query.list().size() > 0) { baseConfig = (BaseConfigModel) query.list().get(0); } return baseConfig; } catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public boolean updateBaseConfig(String configcode, String configvalue) { Session session = sessionFactory.getCurrentSession(); StringBuffer sql = new StringBuffer("UPDATE BaseConfigModel "); sql.append(" SET configvalue= ?"); sql.append(" WHERE configcode = ? "); Query query = session.createQuery(sql.toString()); query.setString(0, configvalue); query.setString(1, configcode); int isok = query.executeUpdate(); if (isok > 0) { return true; } return false; } @SuppressWarnings("unchecked") @Override public List<BaseConfigModel> searchBaseConfigList(String configcode) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { String hql = "FROM BaseConfigModel WHERE configcode=? order by sortnum,configid"; Query query = session.createQuery(hql); query.setString(0, configcode); List<BaseConfigModel> baseConfigList = new ArrayList<BaseConfigModel>(); if (query.list() != null && query.list().size() > 0) { baseConfigList = (List<BaseConfigModel>) query.list(); } return baseConfigList; } catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public BaseConfigModel searchBaseConfigByCode(String configcode, String configvalue) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { String hql = "FROM BaseConfigModel WHERE configcode=? and configvalue=? order by sortnum,configid"; Query query = session.createQuery(hql); query.setString(0, configcode); query.setString(1, configvalue); BaseConfigModel baseConfig = new BaseConfigModel(); if (query.list() != null && query.list().size() > 0) { baseConfig = (BaseConfigModel) query.list().get(0); } return baseConfig; } catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public boolean updateBaseConfig(String configcode, String configvalue, String value1) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { StringBuffer sql = new StringBuffer("UPDATE BaseConfigModel "); sql.append(" SET value1= ?"); sql.append(" WHERE configcode = ? AND configvalue=? "); Query query = session.createQuery(sql.toString()); query.setString(0, value1); query.setString(1, configcode); query.setString(2, configvalue); int isok = query.executeUpdate(); if (isok > 0) { return true; } } catch (Exception e) { throw new BaseException(e.getMessage()); } return false; } @Override public List<BaseConfigModel> searchBaseConfig(String configcode) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { String hql = "FROM BaseConfigModel WHERE configcode=? order by sortnum,configid"; Query query = session.createQuery(hql); query.setString(0, configcode); @SuppressWarnings("unchecked") List<BaseConfigModel> baseConfigList = (List<BaseConfigModel>) query .list(); return baseConfigList; } catch (Exception e) { throw new BaseException(e.getMessage()); } } @Override public boolean updateBaseConfigByConfigCode(String configcode, String configvalue) throws BaseException { Session session = sessionFactory.getCurrentSession(); try { StringBuffer sql = new StringBuffer("UPDATE BaseConfigModel "); sql.append(" SET configvalue= ?"); sql.append(" WHERE configcode = ?"); Query query = session.createQuery(sql.toString()); query.setString(0, configvalue); query.setString(1, configcode); int isok = query.executeUpdate(); if (isok > 0) { return true; } } catch (Exception e) { throw new BaseException(e.getMessage()); } return false; } @Override public boolean addBaseBusinessarea(BaseBusinessareaModel o) throws BaseException { try { Session session = sessionFactory.getCurrentSession(); Integer id = (Integer) session.save(o); if (id > 0) { return true; } } catch (Exception e) { throw new BaseException(e.getMessage()); } return false; } @Override public boolean addBaseConfig(BaseConfigModel o) throws BaseException { try { Session session = sessionFactory.getCurrentSession(); Integer id = (Integer) session.save(o); if (id > 0) { return true; } return false; } catch (Exception e) { throw new BaseException(e.getMessage()); } } }
abstract class LibraryBook extends Book implements Comparable<LibraryBook>{ private String callNumber; public LibraryBook(String newAuthor, String newTitle, String newISBN, String newcallNumber){ super(newAuthor, newTitle, newISBN); callNumber = newcallNumber; } public boolean setAuthor(String newAuthor){ super.setAuthor(newAuthor); return true; } public boolean setTitle(String newTitle){ super.setTitle(newTitle); return true; } public boolean setISBN(String newISBN){ super.setISBN(newISBN); return true; } public boolean setcallNumber(String newCall){ callNumber = newCall; return true; } public String getAuthor(){ return super.getAuthor(); } public String getTitle(){ return super.getTitle(); } public String getISBN(){ return super.getISBN(); } public String getcallNumber(){ return callNumber; } abstract void checkout(String patron, String due); abstract void returned(); abstract String circulationStaus(); public int compareTo(LibraryBook o){ if(getcallNumber().equals(o.getcallNumber())){ return 0; } else if ((getcallNumber().compareTo(o.getcallNumber()) < 0)) { return -1; } else{ return 1;} } public String toString(){ return super.toString() + ", " + callNumber; } public static void main(String[] args) { } }
package MapTEST; import java.util.LinkedList; public class MapTest { LinkedList<Integer> queue=new LinkedList(); public void put(int data) { this.queue.addLast(data); } public int get() { return this.queue.removeFirst(); } public boolean isEmpty() { return this.queue.isEmpty(); } public static void main(String[] args) { // TODO Auto-generated method stub MapTest q1=new MapTest(); q1.put(3); if(!q1.isEmpty()) { System.out.println("不空"); int data= q1.get(); System.out.println(data); } else { System.out.println("empty"); } if(!q1.isEmpty()) { System.out.println("不空"); } else { System.out.println("empty"); } } }
package com.goldenasia.lottery.data; import com.android.volley.Request; import com.goldenasia.lottery.base.net.RequestConfig; import com.google.gson.annotations.SerializedName; /** * 追号订单详情 * Created by Alashi on 2016/1/21. */ @RequestConfig(api = "?c=game&a=traceDetail", method = Request.Method.GET) public class TraceDetailCommand { @SerializedName("wrap_id") private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } }
package com.examples.io.generics.boundedtypeparameters.multiplebounds; public class Dog extends Animal { @Override void show() { System.out.println("Im dog and my sound is"); sound(); } @Override public void sound() { System.out.println("Bark!"); } }
import java.util.*; import java.io.*; public class Cross { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Scanner in = new Scanner(System.in); Scanner in = new Scanner(new File("cross.dat")); int N = in.nextInt(); in.nextLine(); for (int idx = 0; idx < N; idx++) { String line = in.nextLine(), one = line.substring(0, line.indexOf(" and")), two = line.substring(line.indexOf(" and") + 5); int o = -1, t = -1; for (int i = 0; i < one.length(); i++) { int index = two.indexOf(one.charAt(i)); if (index < 0) continue; else {o = i; t = index; break;} } if (o < 0 && t < 0) {System.out.println("none\n"); continue;} char[][] map = new char[two.length()][one.length()]; map[t] = one.toCharArray(); for (int r = 0; r < two.length(); r++) map[r][o] = two.charAt(r); for (char[] a: map) { for (char x: a) { if (x > 123 || x < 97) System.out.print(" "); else System.out.print(x); } System.out.println(); } System.out.println(); } in.close(); } }
package br.com.formsoft.bean; import java.util.List; import javax.faces.bean.ManagedBean; import br.com.formsoft.interfaces.Cadastravel; import br.com.formsoft.modelo.Produto; @ManagedBean public class ProdutoBean implements Cadastravel<Produto> { private Produto produto; public ProdutoBean() { this.produto = Produto.getInstance(); } public void cadastra(Produto produto) { this.produto.getDao().adiciona(produto); } public void remove(Produto produto) { this.produto.getDao().remove(produto); } public List<Produto> lista() { return this.produto.getDao().listaTodos(); } public List<Produto> listaPaginada(int inicio, int maximo) { return this.produto.getDao().listaPaginada(inicio, maximo); } @Override public Produto buscaPorId(Long id) { return this.produto.getDao().buscaPorId(id); } }
package my.app.apitrialrun2; import androidx.appcompat.app.AppCompatActivity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import java.io.IOException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { TextView resultview; Button submit; ProgressBar spinner; StringBuilder sb = new StringBuilder(); InputStream caInput; String endpoint = "https://gulunodejs.myvnc.com:4050/api/user1"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); spinner=(ProgressBar)findViewById(R.id.progressBar); resultview=(TextView)findViewById(R.id.textView2); submit=(Button)findViewById(R.id.button); spinner.setVisibility(View.GONE); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new getdetails().execute(""); } }); } private class getdetails extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { sb=CustomFunc1.getresponsebody(caInput,endpoint); return null; } @Override protected void onPostExecute(String result) { resultview.setText(sb); spinner.setVisibility(View.GONE); } @Override protected void onPreExecute() { try { caInput = getAssets().open("server.cert"); } catch (IOException e) { e.printStackTrace(); } spinner.setVisibility(View.VISIBLE); } @Override protected void onProgressUpdate(Void... values) { } } }
package com.training.rettiwt.service.api; import javax.transaction.Transactional; import java.util.List; public interface Service<Entity, Id> { @Transactional void save(Entity entity); Entity findById(Id id); List<Entity> findAll(); @Transactional void update(Id id, Entity entity); @Transactional void delete(Id id); }
package gui.form; import java.io.Serializable; /** * This interface provides an API for form item filters. */ public interface Filter extends Serializable { /** * Filters the data by returning a value (possibly an null character) * based on the input character. * * Usually, this method would either return the given character (if * the filter criteria were satisfied), or a null character (if * not), or possibly a different character (if the Filter was * acting as a transformer). */ char process (char input); /** * Filters the data by returning a value (possibly an empty string) * based on the input string. * * Usually, this method would either return a subset of the string, * or possibly a transformed (e.g. uppercased) version of the input * data. */ String process (String input); /** * Enable or disable audio feedback (a single beep) when filtering * data. */ void enableAudio (boolean status); }
package com.junzhao.rongyun.response; /** * Created by AMing on 16/1/4. * Company RongCloud */ public class GetGroupData { /** {"status":"100", "message":"查询讨论组基本信息成功", "showMessage":null, "result":{"groupsId":"3b289cf2538e45af9095cc1f0fa8d3ff", "groupsName":"aa、哈哈one、哇个广告", "photo":"http://sanfen-bucket.oss-cn-shenzhen.aliyuncs.com/upload/shanfen/groupImage/3b289cf2538e45af9095cc1f0fa8d3ff.jpg", "memberNum":3}} * //dzxx:点赞 ;qzxx 群组;lwxx 礼物;zfxx 支付;phbx 排行榜 ; gzxx 关注;plxx评论,qzfk:群众反馈:qzyq,群主邀请,qzsq:申请加入群,lwth 礼物退回 */ public String status; public String message; public String showMessage; public String qianzhui; private ResultEntity result; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getShowMessage() { return showMessage; } public void setShowMessage(String showMessage) { this.showMessage = showMessage; } public ResultEntity getResult() { return result; } public void setResult( ResultEntity result) { this.result = result; } public static class ResultEntity { private String groupsId; private String photo; private String groupsName; public String memberNum; public String introduction; private int sex; private String tel; private String signature; private int loginType; public String qianzhui; public String getGroupsId() { return groupsId; } public void setGroupsId(String groupsId) { this.groupsId = groupsId; } public String getGroupsName() { return groupsName; } public void setGroupsName(String groupsName) { this.groupsName = groupsName; } public String getMemberNum() { return memberNum; } public void setMemberNum(String memberNum) { this.memberNum = memberNum; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } public int getLoginType() { return loginType; } public void setLoginType(int loginType) { this.loginType = loginType; } } }
import java.text.SimpleDateFormat; import java.util.*; class Config <T> { private String[] args; private List<String> log; // Config private Map<String, CfgArguments> cfg; Config(String[] args) { this.args = args; log = new LinkedList<>(); cfg = new HashMap<>(); loadSettings(); } /* Argumentos: -l : Muestra el log en la consola -t : Ejecuta todas las pruebas de todos los algoritmos conocidos -n : 'n' que se utiliza para realizar la prueba -1 <algoritmo, ...> : Selecciona el/los algoritmos a ejecutar -log : Muestra el log completo final al acabar -7 : Simula que esta en 7 para probar */ private void loadSettings() { for (int i = 0; i < args.length; i++) { switch (args[i].toLowerCase()) { case "-x": case "-7": case "-log": case "-t": cfg.put(args[i], new CfgArguments(true)); break; case "-l": case "-n": case "-1": cfg.put(args[i], new CfgArguments<>(true, getArguments(i))); break; } } } private Object[] getArguments(int i) { return Arrays.copyOfRange(args, i + 1, auxCheckArg(args, i)); } private int auxCheckArg(String[] args, int index) { if (args != null) { for (int i = index + 1; i < args.length; i++) { if (args[i].contains("-")) { return i; } } return args.length; } else { return 0; } } boolean enabled(String arg) { return cfg.containsKey(arg) && cfg.get(arg).enabled; } void disable(String arg) { if (cfg.get(arg) != null) { cfg.get(arg).enabled = false; } } @SuppressWarnings("unchecked") List<T> arguments(String arg) { if (cfg.containsKey(arg)) { return (cfg.get(arg).args); } else { return null; } } T argument(String arg) { if (arguments(arg) == null) { return null; } else { try { return arguments(arg).get(0); } catch (IndexOutOfBoundsException e) { return null; } } } void writeLog(String line) { writeLog(line, logType.INFO); } void writeLog(String line, logType type) { writeLog(line, type, null); } void writeLog(String line, List<String> list) { writeLog(line, logType.INFO, list); } void writeLog(String line, logType type, List<String> list) { Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("[dd/MM/yy HH:mm:ss,S]"); StringBuilder sb = new StringBuilder(sdf.format(now) + "\t[" + type.name() + "]" + (type == logType.SYSTEM ? "" : "\t") + " - " + line); if (list != null) { for (String elem : list) { sb.append("\t\t\t\t\t - ").append(elem); if (!elem.equalsIgnoreCase(list.get(list.size()-1))) { sb.append('\n'); } } } log.add(sb.toString()); if (enabled("-l") && (type == logType.INFO || (type == logType.ERROR && argument("-l") != null))) { System.out.println(sb.toString()); } } String readFullLog() { StringBuilder sb = new StringBuilder(); for (String line : log) { sb.append(line).append("\n"); } return sb.toString(); } static List<String> longToString(List<Long> list) { List<String> newList = new LinkedList<>(); for (Long n : list) { newList.add(String.valueOf(n)); } return newList; } static List<String> doubleToString(List<Double> list) { List<String> newList = new LinkedList<>(); for (Double n : list) { newList.add(String.valueOf(n)); } return newList; } public enum logType {INFO, ERROR, SYSTEM} private static class CfgArguments<T> { private boolean enabled; private List<T> args = null; CfgArguments(boolean enabled) { this.enabled = enabled; } @SafeVarargs CfgArguments(boolean enabled, T... args) { this(enabled); this.args = new LinkedList<>(); this.args.addAll(Arrays.asList(args)); } } }
package com.leetcode.google; public class isSubTree { public static class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int data) { this.val = data; this.left = null; this.right = null; } } public static boolean isSubtree(TreeNode s, TreeNode t) { if(t == null && s == null) return true; if(s == null) return false; if(isSame(s,t)) return true; return isSubtree(s.left,t)||isSubtree(s.right,t); } public static boolean isSame(TreeNode s,TreeNode t){ if(s == null && t== null) return true; if(s== null || t== null) return false; if(s.val != t.val) return false; return isSame(s.left, t.left) && isSame(s.right, t.right); } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode root = new TreeNode(1); /* * TreeNode one = new TreeNode(4); TreeNode three = new TreeNode(5); TreeNode * four = new TreeNode(1); TreeNode five = new TreeNode(2); TreeNode six = new * TreeNode(0); root.left = one; root.right = three; one.left = four; one.right * = five; five.left = six; */ TreeNode next = new TreeNode(0); /* * TreeNode they = new TreeNode(1); TreeNode there = new TreeNode(2); next.left * = they; next.right = there; */ System.out.println(isSubtree(root, next)); } }
package de.cuuky.varo.api.event; import java.lang.reflect.Method; import java.util.ArrayList; import de.cuuky.varo.Main; import de.cuuky.varo.api.event.register.VaroEventMethod; import de.cuuky.varo.api.event.register.VaroListener; public class EventManager { private ArrayList<EventHandler> handlerList; public EventManager() { this.handlerList = new ArrayList<>(); } @SuppressWarnings("unchecked") public void registerEvent(VaroListener listener) { for (Method method : listener.getClass().getDeclaredMethods()) { if (method.getAnnotation(VaroEventMethod.class) == null) continue; Class<?>[] clazzes = method.getParameterTypes(); if (clazzes.length != 1 || !VaroAPIEvent.class.isAssignableFrom(clazzes[0])) { System.out.println(Main.getConsolePrefix() + "Failed to register listener " + listener.getClass().getName() + " caused by wrong parameters given."); continue; } handlerList.add(new EventHandler(listener, method, (Class<? extends VaroAPIEvent>) clazzes[0])); } } public boolean executeEvent(VaroAPIEvent event) { for (EventHandler handler : this.handlerList) { if (!handler.getEvent().equals(event.getClass())) continue; handler.execute(event); return event.isCancelled(); } return false; } public ArrayList<EventHandler> getHandler() { return handlerList; } }
package com.xixiwan.platform.module.minio.config; import io.minio.MinioClient; import io.minio.errors.InvalidEndpointException; import io.minio.errors.InvalidPortException; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration @ConditionalOnClass(MinioProperties.class) @EnableConfigurationProperties(MinioProperties.class) public class MinioAutoConfiguration { private final MinioProperties properties; public MinioAutoConfiguration(MinioProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean(MinioClient.class) @ConditionalOnProperty(name = "minio.url") MinioClient minioClient() throws InvalidPortException, InvalidEndpointException { return new MinioClient( properties.getUrl(), properties.getAccessKey(), properties.getSecretKey() ); } }
public class MutaliskEasy { public int minimalAttacks(int[] x) { int a = x[0]; int b = 0; int c = 0; if(1 < x.length) { b = x[1]; } if(2 < x.length) { c = x[2]; } int[][][] min = new int[a + 1][b + 1][c + 1]; for(int i = 0; i < min.length; ++i) { for(int j = 0; j < min[i].length; ++j) { for(int k = 0; k < min[i][j].length; ++k) { min[i][j][k] = 10000; } } } int[][] moves = new int[6][3]; moves[0][0] = 9; moves[0][1] = 3; moves[0][2] = 1; moves[1][0] = 9; moves[1][1] = 1; moves[1][2] = 3; moves[2][0] = 3; moves[2][1] = 9; moves[2][2] = 1; moves[3][0] = 3; moves[3][1] = 1; moves[3][2] = 9; moves[4][0] = 1; moves[4][1] = 9; moves[4][2] = 3; moves[5][0] = 1; moves[5][1] = 3; moves[5][2] = 9; min[0][0][0] = 0; for(int i = 0; i < min.length; ++i) { for(int j = 0; j < min[i].length; ++j) { for(int k = 0; k < min[i][j].length; ++k) { for(int m = 0; m < moves.length; ++m) { int newI = Math.min(i + moves[m][0], min.length - 1); int newJ = Math.min(j + moves[m][1], min[i].length - 1); int newK = Math.min(k + moves[m][2], min[i][j].length - 1); min[newI][newJ][newK] = Math.min(min[newI][newJ][newK], 1 + min[i][j][k]); } } } } return min[a][b][c]; } }
package me.libraryaddict.disguise.utilities.backwards; import me.libraryaddict.disguise.disguisetypes.MetaIndex; import me.libraryaddict.disguise.utilities.LibsPremium; import me.libraryaddict.disguise.utilities.ReflectionManager; import me.libraryaddict.disguise.utilities.backwards.metadata.Version_1_11; import java.lang.reflect.Field; import java.util.ArrayList; /** * Created by libraryaddict on 8/06/2017. */ public class BackwardsSupport { public static BackwardMethods getMethods() { try { String version = ReflectionManager.getBukkitVersion(); if (LibsPremium.isPremium()) { if (version.equals("v1_11_R1")) { return setupMetadata(Version_1_11.class); } } return setupMetadata(BackwardMethods.class); } catch (Exception e) { e.printStackTrace(); } return null; } private static BackwardMethods setupMetadata(Class<? extends BackwardMethods> backwardsClass) { try { BackwardMethods backwards = backwardsClass.newInstance(); ArrayList<MetaIndex> newIndexes = new ArrayList<>(); for (Field field : backwards.getClass().getFields()) { if (field.getType() != MetaIndex.class) continue; if (MetaIndex.setMetaIndex(field.getName(), (MetaIndex) field.get(backwards))) { continue; } newIndexes.add((MetaIndex) field.get(backwards)); } MetaIndex.setValues(); MetaIndex.addMetaIndexes(newIndexes.toArray(new MetaIndex[0])); if (backwards.isOrderedIndexes()) { MetaIndex.fillInBlankIndexes(); MetaIndex.orderMetaIndexes(); } return backwards; } catch (Exception ex) { ex.printStackTrace(); } return null; } }
package com.cjkj.insurance.controller; import com.cjkj.insurance.entity.other.*; import com.cjkj.insurance.service.InsuranceService; import com.cjkj.insurance.service.MsgHandleService; import com.cjkj.insurance.utils.ApiCode; import com.cjkj.insurance.utils.ApiResult; import com.cjkj.insurance.utils.TimeToString; import com.cjkj.insurance.utils.json.JSONUtil; import com.google.gson.Gson; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @RestController @RequestMapping(value = "/api/v1/insurance") @Api(tags = "车保管理业务") public class InsuranceController { @Autowired private InsuranceService insuranceService ; @Autowired private MsgHandleService msgHandleService; Gson gson = new Gson(); /** * 3.获取token * @param id * @param request * @return */ @GetMapping("/getToken") @ApiOperation("3添加接口访问规则中所需的header信息") @ApiImplicitParam(name = "id",value = "用户ID",required = true) public ApiResult getToken( int id, HttpServletRequest request) throws Exception { request.getSession().setAttribute("userId",id); ApiResult a = new ApiResult(); a = insuranceService.getToken(request,a); a.setParams(request.getSession().getId().toString()); System.out.println(TimeToString.DateToStr(new Date())+a.toString()); return a; } /* **4.获取投保地区 * 440000 */ @PostMapping("/getAgreementAreas") @ApiOperation("4获取投保地区") @ApiImplicitParam(name = "agreementProvCode",value = "省编码或null",required = true) public ApiResult getAgreementAreas(HttpServletRequest request, String agreementProvCode) throws Exception { ApiResult a =new ApiResult(); a=insuranceService.getAgreementAreas(request,agreementProvCode,a); System.out.println(TimeToString.DateToStr(new Date())+a.toString()); return a; } /** * 4+.获取地区车牌 */ @ApiOperation("4+.获取地区车牌") @GetMapping("/getLicensePlateByCityId") @ApiImplicitParam(name = "cityId",value = "城市编号",required = true) public ApiResult getLicensePlateByCityId(String cityId){ ApiResult apiResult = new ApiResult(); apiResult.setCode(ApiCode.SUCCESS); apiResult.setMsg(ApiCode.SUCCESS_MSG); apiResult.setData(insuranceService.findLicensePlateByCityId(cityId)); return apiResult; } /*5.获取供应商列表 * 例如,东莞市 : 441900 **/ @PostMapping("/getProviders") @ApiOperation("5获取供应商列表") @ApiImplicitParam(name = "insureAreaCode",value = "国标地区编码(市级)",required = true) public ApiResult getProviders(HttpServletRequest request, String insureAreaCode ) throws Exception { ApiResult a =new ApiResult(); a = insuranceService.getProviders(request,insureAreaCode,a); System.out.println(a.toString()); System.out.println(TimeToString.DateToStr(new Date())+a); return a; } /* 6 创建报价任务 {"insureAreaCode":"441900","carLicenseNo":"粤STTT33","name":"汪莹"} **/ @PostMapping("/createTaskA") @ApiOperation("6创建报价任务A") public ApiResult createTaskA(HttpServletRequest request, @ApiParam(name = "params",value = "insureAreaCode:地区编码(市级), carInfo(carLicenseNo:车牌号),carOwner(name:车主姓名)",required = true) @RequestBody ReqCreateTaskA reqCreateTaskA) throws Exception { ApiResult a =new ApiResult(); a = insuranceService.createTaskA(reqCreateTaskA,request,a); if(-1 == a.getCode()){ a.setParams("车辆信息查询失败,请跳转至创建报价(标准接口),即/CreateTaskB所对应的界面进行创建报价"); } System.out.println(TimeToString.DateToStr(new Date())+":"+a); return a; } /* *7 创建报价任务(标准接口) **/ @PostMapping("/createTaskB") @ApiOperation("7创建报价任务B(标准接口)") public ApiResult createTaskB(HttpServletRequest request, @ApiParam(name = "params",value = "很多信息",required = true) @RequestBody ReqCreateTaskB reqCreateTaskB) throws Exception { ApiResult a =new ApiResult(); a = insuranceService.createTaskB(reqCreateTaskB,request,a); System.out.println(TimeToString.DateToStr(new Date())+a); return a; } /* *8查询车型信息 **/ @PostMapping("/queryCarModelInfos") @ApiOperation("8查询车型信息") public ApiResult queryCarModelInfos(HttpServletRequest request, @ApiParam(name = "params",value = "pageSize:每页记录数(限制50),pageNum:第几页,vehicleName:车型名称/VIN码,carLicenseNo:车牌号,registDate:初登日期,",required = true) @RequestBody JSONObject params) throws Exception { ApiResult a =new ApiResult(); a=insuranceService.queryCarModelInfos(request,params,a); System.out.println(TimeToString.DateToStr(new Date())+a); return a; } /* 9修改报价/投保数据 **/ @PostMapping("/updateTask") @ApiOperation("9修改报价/投保数据") public ApiResult updateTask(HttpServletRequest request, @ApiParam(name = "params",value = "提交需要修改的数据,JSON格式",required = true) @RequestBody String json) throws Exception { ApiResult a =new ApiResult(); ReqUpdateTask reqUpdateTask = gson.fromJson(json,ReqUpdateTask.class); a=insuranceService.updateTask(request,reqUpdateTask,a); System.out.println(TimeToString.DateToStr(new Date())+a); return a; } /* 10提交报价,等待报价信息结果 taskId:2629432 **/ @PostMapping("/submitQuote") @ApiOperation("10提交报价,等待报价信息结果") public ApiResult submitQuote(HttpServletRequest request, @ApiParam(name = "params",value = "提交报价任务==" + "初次提交:{taskId:任务号},重新提交=={taskId: 任务号,prvId: 供应商id}",required = true) @RequestBody JSONObject params) throws Exception { ApiResult a =new ApiResult(); System.out.println("传给提交报价任务的参数为:"+params.toString()); a=insuranceService.submitQuote(request,params,a); System.out.println(TimeToString.DateToStr(new Date())+a.toString()); return a; } /* 11 提交核保任务 **/ @PostMapping("/submitInsure") @ApiOperation("11提交核保任务") public ApiResult submitInsure( HttpServletRequest request, @ApiParam(name = "params",value = "提交核保任务(需提供taskId与供应商Id)",required = true) @RequestBody JSONObject params) throws Exception { ApiResult a =new ApiResult(); a=insuranceService.submitInsure(params,request,a); System.out.println(TimeToString.DateToStr(new Date())+a.toString()); return a; } /* * 12回调接口 **/ @PostMapping("/finalState") @ApiOperation("12回调接口") public ApiResult finalState(@RequestBody String jsonStr) { System.out.println("================================泛华回调================================================="); System.out.println("jsonStr===>"+jsonStr); System.out.println("================================泛华回调================================================="); //回调信息处理 insuranceService.finalState(jsonStr); ApiResult apiResult = new ApiResult(); apiResult.setCode(ApiCode.SUCCESS); apiResult.setMsg(ApiCode.SUCCESS_MSG); return apiResult; } /* 13 影像识别 **/ @PostMapping("/recognizeImage") @ApiOperation("13影像识别") public ApiResult recognizeImage( @ApiParam(name = "params",value = "imageType: 影像类型," + "imageMode: 图片格式(jpg、png、bmp)," + "imageUrl: 影像URL," + "imageContent: 影像内容(BASE64编码)",required = true) @RequestBody JSONObject params, HttpServletRequest request) throws Exception { ApiResult a =new ApiResult(); a = insuranceService.recognizeImage(params,request,a); System.out.println(TimeToString.DateToStr(new Date())+a.toString()); return a; } /* 14影像上传 **/ @PostMapping("/uploadImage") @ApiOperation("14影像上传") public ApiResult uploadImage(HttpServletRequest request, @ApiParam(name = "params",value = "taskId=任务号,imageInfos=影像信息集合" + "【imageMode: 图片格式(jpg、png、bmp),imageUrl: 影像URL,imageContent: 影像内容(BASE64编码)】",required = true) @RequestBody ReqImgUpload reqImgUpload) throws Exception { ApiResult a =new ApiResult(); a = insuranceService.uploadImage(reqImgUpload,request,a); System.out.println(TimeToString.DateToStr(new Date())+a.toString()); return a; } /* 15支付 **/ @PostMapping("/pay") @ApiOperation("15支付") public ApiResult pay(HttpServletRequest request, @ApiParam(name = "params",value = "提交核保任务(需提供taskId与供应商Id)",required = true) @RequestBody JSONObject params) throws Exception { ApiResult a =new ApiResult(); a=insuranceService.pay(params,request,a); System.out.println(TimeToString.DateToStr(new Date())+a.toString()); return a; } /** * 查询所有的报价结果 * * @return */ @ApiOperation("20---查询所有的回调结果") @PostMapping("/findAllCallback") public ApiResult findAllCallback(HttpServletRequest request, @ApiParam(name = "map",value = "taskId=任务号,taskStates=任务状态码集合【{\"taskId\":\"2637743\",\"taskStates\":[13,14]}】",required = true) @RequestBody Map map){ HttpSession session = request.getSession(); ApiResult apiResult = new ApiResult(); apiResult.setCode(ApiCode.SUCCESS); apiResult.setMsg(ApiCode.SUCCESS_MSG); apiResult.setData( msgHandleService.findAllCallback(session,map)); return apiResult; } }
package assignment.io; import java.util.ArrayList; import java.util.List; public class GpaCalcualtion { private List<String> allStudentResult = null; public GpaCalcualtion() { this.allStudentResult = new ArrayList<>(); } public void resultCalculation(List<String> studentDetails, List<String> headInfo) { int size = studentDetails.size() / headInfo.size() - 1; int sz = (headInfo.size() + 2); while (size > 0) { double result = 0; float ck = 0f; byte count = 0; int limit = sz + 4; String studentInfo = null; String resultInfo = null; String courseInfo ="------------------------------------------\n"+ "Subject | " + " Marks | " + " Grade point | " + " Grade |"; courseInfo = courseInfo + "\n------------------------------------------"; for (int i = sz, j = 2; i < limit; i++, j++) { ck = getGradePoint(Double.valueOf(studentDetails.get(i))); courseInfo = courseInfo + "\n" + headInfo.get(j) + " |" + studentDetails.get(i) + " | " + ck + " | " + grade(ck) + " |"; courseInfo = courseInfo + "\n------------------------------------------"; if (ck == 0f) { count++; } result = result + ck; } result = result / 4; if (count >= 1) { resultInfo = "GPA " + result + " Fail due to requir " + count + " subject grade below the pass"; } else { resultInfo = "GPA " + result; } studentInfo = "Student Name: " + studentDetails.get(sz - 1) + " Student Id: " + studentDetails.get(sz - 2); this.allStudentResult.add((studentInfo + "\n" + courseInfo + "\n" + resultInfo)); sz = limit + 2; size--; } } public String grade(float number) { String gp = null; if (number == 4.0f) { gp = "A+"; } else if (number == 3.5f) { gp = "A"; } else if (number == 3.5f) { gp = "A"; } else if (number == 3.0f) { gp = "A-"; } else if (number == 2.5f) { gp = "B"; } else if (number == 2.0f) { gp = "C"; } else if (number == 1.0f) { gp = "D"; } else if (number == 0.0f) { gp = "F"; } return gp; } public float getGradePoint(double number) { float grade = 0f; if (number >= 80 && number <= 100) { grade = 4.0f; } else if (number >= 70 && number < 80) { grade = 3.5f; } else if (number >= 65 && number < 70) { grade = 3.0f; } else if (number >= 60 && number < 65) { grade = 2.5f; } else if (number >= 50 && number < 60) { grade = 2.0f; } else if (number >= 40 && number < 50) { grade = 1.0f; } else if (number < 40) { grade = 0.0f; } return grade; } public List<String> getAllStudentResult() { return new ArrayList<>(allStudentResult); } }
package com.example.plotarmapa; import android.os.AsyncTask; import com.example.plotarmapa.GoogleGeoCoding.GoogleGeoCode; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpService extends AsyncTask<Void, Void, GoogleGeoCode> { private final String cep; public HttpService(String cep){ this.cep = cep; } @Override protected GoogleGeoCode doInBackground(Void... voids) { StringBuilder resposta = new StringBuilder(); StringBuilder results = new StringBuilder(); if (this.cep != null && this.cep.length() == 8){ try{ URL url = new URL("http://viacep.com.br/ws/" + this.cep + "/json/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setDoOutput(true); connection.setConnectTimeout(5000); connection.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(url.openStream())); String line; while ((line = rd.readLine()) != null) { resposta.append(line); } }catch (MalformedURLException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); } } Cep cep = new Gson().fromJson(resposta.toString(), Cep.class); String logradouro = cep.getLogradouro().replace(" ", "+"); String cidade = cep.getLocalidade().replace(" ", "+"); String uf = cep.getUf(); try { URL urlGoogleApi = new URL("https://maps.googleapis.com/maps/api/geocode/json?address="+logradouro+","+cidade+","+uf+"\n"+"&key=AIzaSyBJEkF2ocUFIxpx-6OclAXlMnfLARE3XuI"); HttpURLConnection connection = (HttpURLConnection) urlGoogleApi.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-type", "application/json"); connection.setDoOutput(true); connection.setConnectTimeout(5000); connection.connect(); BufferedReader rd = new BufferedReader(new InputStreamReader(urlGoogleApi.openStream())); String line; while ((line = rd.readLine()) != null) { results.append(line); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } GoogleGeoCode geoCode = new Gson().fromJson(results.toString(), GoogleGeoCode.class); return geoCode; } }
package algopro.datastr; /** * This class is intended to be an implementation of the data structure heap in * a way more suited to graph search algorithms than the standard java * PriorityQueue. * */ public class Heap { private int heapSize; private Node[] elements; private int[] keyList; private int width; /** * Constructs a fixed size heap. * * @param maxNumberOfNodes the maximal amount of Node objects the heap can contain. * @param width the width of the map searched (used for indexing the nodes based on their coordinates). */ public Heap(int maxNumberOfNodes, int width) { heapSize = 0; elements = new Node[maxNumberOfNodes + 1]; keyList = new int[maxNumberOfNodes + 1]; this.width = width; } /** * Method inserts a given node into the heap. <p> * Time complexity: O(log(n)). * * @param key the node to be inserted. */ public void insert(Node key) { heapSize++; int i = heapSize; int x = key.getX(); int y = key.getY(); keyList[y * width + x] = i; elements[heapSize] = key; while (i > 1 && elements[parent(i)].compareTo(key) > 0) { swap(i, parent(i)); i = parent(i); } } /** * Method removes the smallest element from the heap. <p> * Time complexity: O(log(n)). * * @return the node in the heap with the smallest weight. */ public Node deleteMin() { if (heapSize < 1) { return null; } Node min = elements[1]; elements[1] = elements[heapSize]; heapSize--; heapify(); return min; } /** * Updates the weight of a given node to the new value provided if smaller than previously. <p> * Time complexity: O(log(n)). * * @param key the node to be evaluated. * @param weight the new weight to be updated to. */ public void decreaseWeight(Node key, double weight) { if (weight < key.getWeight()) { key.setWeight(weight); int i = keyList[key.getX() + width * key.getY()]; while (i > 1 && elements[parent(i)].compareTo(key) > 0) { swap(i, parent(i)); i = parent(i); } } } /** * Restores the heap invariant in the heap. <p> * Time complexity: O(log(n)). */ private void heapify() { int k = 1; while (right(k) != -1) { int l = left(k); int r = right(k); int smallest = r; if (elements[l].compareTo(elements[r]) < 0) { smallest = l; } if (elements[k].compareTo(elements[smallest]) > 0) { swap(k, smallest); } k = smallest; } if (left(k) == heapSize && elements[k].compareTo(elements[left(k)]) > 0) { swap(k, left(k)); } } /** * Changes places between nodes in the indexes provided. <p> * Time complexity: O(1). * * @param i the first index. * @param j the second index. */ private void swap(int i, int j) { Node q = elements[i]; int no1 = q.getX() + width * q.getY(); int no2 = elements[j].getX() + width * elements[j].getY(); elements[i] = elements[j]; elements[j] = q; keyList[no1] = j; keyList[no2] = i; } /** * Calculates the left child to the provided index in the heap. <p> * Time complexity: O(1). * @param i * @return */ private int left(int i) { int l = 2 * i; if (l <= heapSize) { return l; } return -1; } /** * Calculates the right child to the provided index in the heap. <p> * Time complexity: O(1). * @param i * @return */ private int right(int i) { int r = 2 * i + 1; if (r <= heapSize) { return r; } return -1; } /** * Calculates the parent to the provided index in the heap. <p> * Time complexity: O(1). * @param i * @return */ private int parent(int i) { return i / 2; } /** * Checks whether there are any nodes in the heap. * * @return true if the heap is empty, else false. */ public boolean isEmpty() { return heapSize < 1; } @Override public String toString() { String output = "["; for (int i = 1; i <= heapSize; i++) { output += elements[i]; if (i < heapSize) { output += ", "; } } output += "]"; return output; } }
/* * 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.dawningsolutions.tasks.pcgui.panels; import com.dawningsolutions.tasks.core.ExportEmail; import com.dawningsolutions.tasks.pcgui.Gui; import com.dawningsolutions.tasks.pcgui.constants.GUIConstants; import com.sun.mail.smtp.SMTPAddressFailedException; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Scanner; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; import javax.mail.AuthenticationFailedException; import javax.mail.MessagingException; import javax.mail.internet.AddressException; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; /** * * @author allon_000 */ public class SendEmailPanel extends TOPanel { private static final Logger logger = LogManager.getLogger(Gui.class); public JTextArea fromAddr, toAddr, ccAddrs, bccAddrs, subject, body; public JPasswordField password; public JLabel fromL, passwordL, toL, ccL, bccL, subjectL, bodyL; public JButton cancel, send; private String currentPath; private volatile boolean flag_sent, flag_sending; public SendEmailPanel(String currentPath) { super(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); this.currentPath = currentPath; fromAddr = new JTextArea(); fromAddr.setRows(1); toAddr = new JTextArea(); ccAddrs = new JTextArea(); bccAddrs = new JTextArea(); subject = new JTextArea(); body = new JTextArea(); cancel = new JButton("Cancel"); cancel.addActionListener(new CancelListener()); send = new JButton("Send"); send.addActionListener(new SendListener()); password = new JPasswordField(); fromL = new JLabel("From"); passwordL = new JLabel("Password"); toL = new JLabel("To"); ccL = new JLabel("CC"); bccL = new JLabel("BCC"); subjectL = new JLabel("Subject"); bodyL = new JLabel("Message"); gbc.gridx = 0; gbc.gridy = 0; gbc.fill = GridBagConstraints.NONE; JPanel p = new STPanel(); p.add(send); p.add(cancel); this.add(p, gbc); gbc.gridx = 0; gbc.gridy = 1; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(fromL, gbc); gbc.gridx = 1; gbc.gridy = 1; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(fromAddr, gbc); gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(passwordL, gbc); gbc.gridx = 1; gbc.gridy = 2; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(password, gbc); gbc.gridx = 0; gbc.gridy = 3; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(toL, gbc); gbc.gridx = 1; gbc.gridy = 3; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(toAddr, gbc); gbc.gridx = 0; gbc.gridy = 4; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(ccL, gbc); gbc.gridx = 1; gbc.gridy = 4; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(ccAddrs, gbc); gbc.gridx = 0; gbc.gridy = 5; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(bccL, gbc); gbc.gridx = 1; gbc.gridy = 5; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(bccAddrs, gbc); gbc.gridx = 0; gbc.gridy = 6; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(subjectL, gbc); gbc.gridx = 1; gbc.gridy = 6; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(subject, gbc); gbc.gridx = 0; gbc.gridy = 7; gbc.fill = GridBagConstraints.HORIZONTAL; this.add(bodyL, gbc); gbc.gridx = 1; gbc.gridy = 7; gbc.fill = GridBagConstraints.BOTH; gbc.gridheight = 5; gbc.weighty = 1; gbc.weightx = 1; this.add(body, gbc); this.setBorder(new EmptyBorder(20, 20, 20, 20)); } public void loadPreferences() throws BackingStoreException { Preferences prefs = Preferences.userNodeForPackage(PreferencesPanel.class); fromAddr.setText(prefs.get(PreferencesPanel.USER_EMAIL, "example@gmail.com")); password.setText(prefs.get(PreferencesPanel.USER_PASSWORD, "")); prefs.flush(); } private void send() { logger.trace("Entering SEND"); String from = fromAddr.getText(); String pass = new String(password.getPassword()); String to = toAddr.getText(); String ccs = ccAddrs.getText(); Scanner scan = new Scanner(ccs); scan.useDelimiter(","); logger.trace("Starting to parse css emails"); Collection<String> ccsss = new ArrayList<String>(); while (scan.hasNext()) { ccsss.add(scan.next()); } String bccs = bccAddrs.getText(); scan = new Scanner(bccs); scan.useDelimiter(","); logger.trace("Starting to parse bcss emails"); Collection<String> bbsss = new ArrayList<String>(); while (scan.hasNext()) { bbsss.add(scan.next()); } String sub = subject.getText(); String bod = body.getText(); MessagingException e = null; logger.trace("entering try catch"); try { flag_sent = false; logger.trace("creating ExportEmail"); ExportEmail ee = new ExportEmail(from, pass, to, ccsss, bbsss, sub, bod, new File(currentPath).getAbsolutePath()); logger.trace("created ExportEmail - setting up server properties"); ee.setUpServerProperties(); logger.trace("finished - now setting up details"); ee.setDetials(); logger.trace("finished - now performing send"); ee.send(); flag_sent = true; } catch (MessagingException ex) { e = ex; logger.error(ex.getCause()); } finally { flag_sending = false; } logger.trace("finished try block"); if (e != null) { logger.error(e.getClass().toString()); if (e instanceof AuthenticationFailedException) { showMessageFailed("Authentication Error, check if the email and password are correct"); } else if (e instanceof AddressException) { showMessageFailed("Address Syntax Error, check if address in the to,bcc and cc fields are correct " + "\n" + " and that multiple addresses are seperated by a ',' "); } else if (e instanceof SMTPAddressFailedException) { showMessageFailed("Invalid Address, check if address in the to,bcc and cc fields are correct " + "\n" + " and that multiple addresses are seperated by a ',' "); } else { showMessageFailed("Failed To Send, " + e.getMessage()); } } System.out.println("Done"); } private class SendListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { boolean cont = true; flag_sending = true; if (subject.getText().isEmpty()) { int i = showWarnMessage("Subject is empty, Do You want to continue?", "Subject Empty"); cont = JOptionPane.YES_OPTION == i; } else if (body.getText().isEmpty()) { int i = showWarnMessage("Body is empty, Do You want to continue?", "Body Empty"); cont = JOptionPane.YES_OPTION == i; } if (cont) { Thread a = new Thread(new Runnable() { @Override public void run() { synchronized (this) { send(); notifyAll(); } } }); a.start(); synchronized (a) { try { while (flag_sending == true) { a.wait(); } } catch (InterruptedException ex) { ex.printStackTrace(); } } System.out.println("Started"); if (flag_sending == false && flag_sent) { GUIConstants.frame.ToMatrixScreen(); } } } } private class CancelListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { GUIConstants.frame.ToMatrixScreen(); } } private void showMessageFailed(final String message) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JOptionPane.showMessageDialog(null, message); //To change body of generated methods, choose Tools | Templates. } }); } private int showWarnMessage(String message, String title) { return JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION); } }
package ru.javaprac.array; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class BubbleSortTest { @Test public void whenArray51273Then12357() { BubbleSort bubbleSort = new BubbleSort(); int[] input = new int[]{5, 1, 2, 7, 3}; int[] result = bubbleSort.BubbleSort(input); int[] excepted = new int[]{1, 2, 3, 5, 7}; assertThat(result, is(excepted)); } }
package com.zpf.dto; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * Created by LoseMyself * on 2017/3/13 13:38 */ @Entity public class girl { @Id @GeneratedValue private Long id; private String cupSize; private Long age; public girl(){ } public Long getId() { return id; } public girl setId(Long id) { this.id = id; return this; } public String getCupSize() { return cupSize; } public girl setCupSize(String cupSize) { this.cupSize = cupSize; return this; } public Long getAge() { return age; } public girl setAge(Long age) { this.age = age; return this; } }
package com.edasaki.rpg.commands.member; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.HashMap; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.edasaki.core.punishments.Punishment; import com.edasaki.core.sql.SQLManager; import com.edasaki.core.utils.RScheduler; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.commands.RPGAbstractCommand; public class LookupCommand extends RPGAbstractCommand { public HashMap<String, Long> lastLookup = new HashMap<String, Long>(); public LookupCommand(String... commandNames) { super(commandNames); } @Override public void execute(CommandSender sender, String[] args) { } @Override public void executePlayer(Player p, PlayerDataRPG pd, String[] args) { if (args.length != 1) { p.sendMessage(ChatColor.RED + "/lookup <name>"); } else { if (lastLookup.containsKey(p.getName()) && System.currentTimeMillis() - lastLookup.get(p.getName()) < 30000) { p.sendMessage(ChatColor.RED + "You can only use /lookup once every 30 seconds."); } else { lastLookup.put(p.getName(), System.currentTimeMillis()); p.sendMessage(ChatColor.GREEN + "Looking up punishment history for " + ChatColor.YELLOW + args[0] + ChatColor.GREEN + ", please wait..."); RScheduler.scheduleAsync(plugin, () -> { AutoCloseable[] ac_dub = SQLManager.prepare("SELECT * FROM punishments WHERE name = ?"); try { PreparedStatement request_punishment_status = (PreparedStatement) ac_dub[0]; request_punishment_status.setString(1, args[0]); AutoCloseable[] ac_trip = SQLManager.executeQuery(request_punishment_status); ResultSet rs = (ResultSet) ac_trip[0]; ArrayList<Punishment> puns = new ArrayList<Punishment>(); String name = args[0]; while (rs.next()) { Punishment pun = new Punishment(); pun.load(rs); puns.add(pun); name = pun.name; } final String fname = name; SQLManager.close(ac_dub); SQLManager.close(ac_trip); RScheduler.schedule(plugin, () -> { if(p == null || !p.isOnline()) return; p.sendMessage(""); p.sendMessage(ChatColor.GREEN + fname + "'s Punishment History"); p.sendMessage(ChatColor.RED + "========================="); for(Punishment pun : puns) { p.sendMessage(""); p.sendMessage(pun.getDisplay()); } }); } catch (Exception e) { e.printStackTrace(); } }); } } } @Override public void executeConsole(CommandSender sender, String[] args) { } }
package controllers.administrator; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import services.ChirpService; import services.ChorbiService; import services.LikeService; import services.ManagerService; import controllers.AbstractController; import domain.Chorbi; @Controller @RequestMapping("/administrator") public class DashboardAdministrator extends AbstractController { // Services --------------------------------------------------------------- @Autowired private ChorbiService chorbiService; @Autowired private LikeService likeService; @Autowired private ChirpService chirpService; @Autowired private ManagerService managerService; // Constructors ----------------------------------------------------------- public DashboardAdministrator() { super(); } // Listing ---------------------------------------------------------------- @RequestMapping(value = "/dashboard", method = RequestMethod.GET) public ModelAndView list() { final ModelAndView result; /////////// Chorbies // C Collection<Object[]> numChorbiesPerCountryAndCity; Object[] minMaxAvgAges; Double ratioInvalidCreditCard; Collection<Object[]> ratioActivitiesLoveFriendship; // B Collection<Chorbi> chorbiesSortedByNumLikes; Object[] minMaxAvgLikesPerChorbi; // A Double[] minMaxAvgReceivedChirps; Double[] minMaxAvgChirpsSentPerChorbi; Collection<Object[]> chorbiWithMostReceivedChirps; Collection<Object[]> chorbiWithMostSentChirps; numChorbiesPerCountryAndCity = this.chorbiService.findGroupByCountryAndCity(); minMaxAvgAges = this.chorbiService.findMinMaxAvgAges(); ratioInvalidCreditCard = this.chorbiService.findRatioInvalidCreditCard(); ratioActivitiesLoveFriendship = this.chorbiService.findRatioActivitiesLoveFriendship(); chorbiesSortedByNumLikes = this.chorbiService.findAllSortedByReceivedLikes(); minMaxAvgLikesPerChorbi = this.likeService.findMinMaxAvgReceivedPerChorbi(); minMaxAvgReceivedChirps = this.chirpService.findMinMaxAvgReceived(); minMaxAvgChirpsSentPerChorbi = this.chirpService.findMinMaxAvgSent(); chorbiWithMostReceivedChirps = this.chorbiService.findChorbiWithMostReceivedChirps(); chorbiWithMostSentChirps = this.chorbiService.findChorbiWithMostSentChirps(); /////////// Chorbies 2.0 // C Collection<Object[]> managersSortedByEvents; Collection<Object[]> managersAndFee; Collection<Object[]> chorbiesSortedByEvents; Collection<Object[]> chorbiesAndFee; // B Object[] minMaxAvgStarsPerChorbi; final Collection<Object[]> chorbiesSortedByAvgStars; managersSortedByEvents = this.managerService.findByNumberEvents(); managersAndFee = this.managerService.findByAmountFee(); chorbiesSortedByEvents = this.chorbiService.findOrderByRegisteredEvents(); chorbiesAndFee = this.chorbiService.findAllWithAmountFee(); minMaxAvgStarsPerChorbi = this.likeService.findMinMaxAvgStarsPerChorbi(); chorbiesSortedByAvgStars = this.chorbiService.findChorbiesSortedByAvgStars(); result = new ModelAndView("administrator/dashboard"); result.addObject("requestURI", "administrator/dashboard.do"); result.addObject("numChorbiesPerCountryAndCity", numChorbiesPerCountryAndCity); result.addObject("minMaxAvgAges", minMaxAvgAges); result.addObject("ratioInvalidCreditCard", ratioInvalidCreditCard); result.addObject("ratioActivitiesLoveFriendship", ratioActivitiesLoveFriendship); result.addObject("chorbiesSortedByNumLikes", chorbiesSortedByNumLikes); result.addObject("minMaxAvgLikesPerChorbi", minMaxAvgLikesPerChorbi); result.addObject("minMaxAvgReceivedChirps", minMaxAvgReceivedChirps); result.addObject("minMaxAvgChirpsSentPerChorbi", minMaxAvgChirpsSentPerChorbi); result.addObject("chorbiWithMostReceivedChirps", chorbiWithMostReceivedChirps); result.addObject("chorbiWithMostSentChirps", chorbiWithMostSentChirps); /////////// Chorbies 2.0 result.addObject("managersSortedByEvents", managersSortedByEvents); result.addObject("managersAndFee", managersAndFee); result.addObject("chorbiesSortedByEvents", chorbiesSortedByEvents); result.addObject("chorbiesAndFee", chorbiesAndFee); result.addObject("minMaxAvgStarsPerChorbi", minMaxAvgStarsPerChorbi); result.addObject("chorbiesSortedByAvgStars", chorbiesSortedByAvgStars); return result; } }
package ua.com.rd.pizzaservice.repository.customer; import org.junit.Before; import org.junit.Test; import ua.com.rd.pizzaservice.domain.address.Address; import ua.com.rd.pizzaservice.domain.customer.Customer; import ua.com.rd.pizzaservice.repository.customer.inmem.InMemCustomerRepository; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class InMemCustomerRepositoryTest { private InMemCustomerRepository repository; @Before public void setUp() { repository = new InMemCustomerRepository(); } @Test public void getCustomerByIdShouldExists() { Customer customer = new Customer(10L, "name", new Address("C", "c", "st", "b")); repository.getCustomers().add(customer); assertEquals(customer, repository.getCustomerById(10L)); } @Test public void getCustomerByIdShouldNotExists() { Customer customer = new Customer(10L, "name", new Address("C", "c", "st", "b")); repository.getCustomers().add(customer); assertNull(repository.getCustomerById(13L)); } }
package org.dimigo.vaiohazard.conversation.parser; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; /** * Created by juwoong on 15. 11. 26.. */ public class ConversationParser { public class ConversationFormat { public String question; public List<String> list; public boolean useName; } private JSONParser parser = new JSONParser(); protected List<ConversationFormat> get(String uri) { List<ConversationFormat> list = new ArrayList<ConversationFormat>(); File file = new File("resources/conversation/" + uri + ".json"); byte[] bytes = new byte[(int)file.length()]; try{ InputStream is = new FileInputStream(file); is.read(bytes); String result = new String(bytes); is.close(); System.out.println(result); JSONObject obj = (JSONObject) parser.parse(result); JSONArray objList = (JSONArray) obj.get("list"); for(int i=0; i<objList.size(); i++) { JSONObject value = (JSONObject) objList.get(i); ConversationFormat format = new ConversationFormat(); if(value.containsKey("answers") == true) { } if(value.containsKey("useName") == true) { format.useName = true; } format.question = (String) value.get("question"); list.add(format); } }catch(IOException e) { e.printStackTrace(); }catch(ParseException e) { e.printStackTrace(); } return list; } }
package com.dian.diabetes.activity.assess; import java.util.Map; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.dian.diabetes.R; import com.dian.diabetes.activity.BaseFragment; import com.dian.diabetes.dialog.NumberDialog; import com.dian.diabetes.dialog.WheelCallBack; import com.dian.diabetes.utils.CheckUtil; import com.dian.diabetes.widget.anotation.ViewInject; /* * 已经废弃 */ public class FirstFragment extends BaseFragment implements OnClickListener { @ViewInject(id = R.id.height) private TextView heightView; @ViewInject(id = R.id.weight) private TextView weightView; @ViewInject(id = R.id.yaowei) private TextView yaoweiView; @ViewInject(id = R.id.strong_content) private TextView strongView; // conroller @ViewInject(id = R.id.height_con) private RelativeLayout heightCon; @ViewInject(id = R.id.weight_con) private RelativeLayout weightCon; @ViewInject(id = R.id.yaowei_con) private RelativeLayout yaoweiCon; @ViewInject(id = R.id.strong_con) private RelativeLayout strongCon; private NumberDialog weightDialog; private NumberDialog heightDialog; private NumberDialog waistDialog; private StrongDialog strongDialog; private AssessActivity activity; public static FirstFragment getInstance() { FirstFragment fragment = new FirstFragment(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = (AssessActivity) getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_assess_normal, container, false); fieldView(view); initView(view); return view; } private void initView(View view) { heightCon.setOnClickListener(this); weightCon.setOnClickListener(this); yaoweiCon.setOnClickListener(this); strongCon.setOnClickListener(this); heightView.setText(activity.getKeyStr("height")); weightView.setText(activity.getKeyStr("weight")); yaoweiView.setText(activity.getKeyStr("yaowei")); strongView.setText(activity.getKeyStr("strong")); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.height_con: if (heightDialog == null) { heightDialog = new NumberDialog(activity, new WheelCallBack() { @Override public void item(int value) { heightView.setText(value + ""); } }, 200, 20, "cm", "身高"); } heightDialog.show(); break; case R.id.weight_con: if (weightDialog == null) { weightDialog = new NumberDialog(activity, new WheelCallBack() { @Override public void item(int value) { weightView.setText(value + ""); } }, 200, 20, "kg", "体重"); } weightDialog.show(); break; case R.id.strong_con: if (strongDialog == null) { strongDialog = new StrongDialog(activity); strongDialog.setCall(new StrongDialog.CallBack() { @Override public void callBack(int position, String model) { strongView.setText(model); } }); } strongDialog.show(); break; case R.id.yaowei_con: if (waistDialog == null) { waistDialog = new NumberDialog(activity, new WheelCallBack() { @Override public void item(int value) { yaoweiView.setText(value + ""); } }, 200, 20, "cm", "腰围"); } waistDialog.show(); break; } } public boolean onBackKeyPressed() { activity.finish(); return true; } public boolean saveCache(Map<String, Object> data) { if (CheckUtil.isNull(heightView.getText())) { Toast.makeText(activity, "身高不能为空", Toast.LENGTH_SHORT).show(); return false; } if (CheckUtil.isNull(weightView.getText())) { Toast.makeText(activity, "体重不能为空", Toast.LENGTH_SHORT).show(); return false; } if (CheckUtil.isNull(yaoweiView.getText())) { Toast.makeText(activity, "腰围不能为空", Toast.LENGTH_SHORT).show(); return false; } if (CheckUtil.isNull(strongView.getText())) { Toast.makeText(activity, "强度不能为空", Toast.LENGTH_SHORT).show(); return false; } data.put("height", heightView.getText()); data.put("weight", weightView.getText()); data.put("yaowei", yaoweiView.getText()); data.put("strong", strongView.getText()); return true; } }
package Java; import java.util.StringTokenizer; class IntegerNode { int id; IntegerNode(int id) { this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IntegerNode that = (IntegerNode) o; return id == that.id; } @Override public int hashCode() { return 1; // return id; } } public class OnlineTest /*implements Runnable*/{ /*int x; int y; @Override public void run() { for (int i = 0; i < 1000; i++) synchronized (this) { x = 12; y = 12; } System.out.print(x + " : " + y); }*/ //group on static int count = 0; public static void getSum(int A[], int key, int sum, int index) { if (index > A.length - 1) { if (sum >= key) { count++; } return; } getSum(A, key, sum + A[index], index + 1); getSum(A, key, sum , index + 1); } public static void findTargetSumSubsets(int[] input, int target, String ramp, int index) { if(index > (input.length - 1)) { if(getSum(ramp) >= target) { System.out.print("Im in"); } return; } //First recursive call going ahead selecting the int at the currenct index value findTargetSumSubsets(input, target, ramp + input[index] + token, index + 1); //Second recursive call going ahead WITHOUT selecting the int at the currenct index value findTargetSumSubsets(input, target, ramp, index + 1); } private static final String token = " "; private static int getSum(String intString) { int sum = 0; StringTokenizer sTokens = new StringTokenizer(intString, token); while (sTokens.hasMoreElements()) { sum += Integer.parseInt((String) sTokens.nextElement()); } return sum; } public static void main(String a[]) { int [] n = {1, 5, 9, 2, 3}; OnlineTest.findTargetSumSubsets(n, 16, "", 0); OnlineTest.getSum(new int[]{1, 5, 9, 2, 3}, 16, 0, 0); System.out.print(count); IntegerNode i1 = new IntegerNode(3); IntegerNode i2 = new IntegerNode(3); System.out.println(i1 == i2); System.out.println(i1.equals(i2)); /*OnlineTest test = new OnlineTest(); Thread t1 = new Thread(test); Thread t2 = new Thread(test); t1.start(); t2.start(); */ } }
package InterfaceDemo; /** * Created by Frank Fang on 8/18/18. */ public class Computer { }
package com.anyuaning.osp.ui.widget; import android.content.Context; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.util.AttributeSet; import android.widget.TextView; import java.text.DecimalFormat; /** * Created by thom on 14-4-2. */ public class Chronometer extends TextView { private static final int TICK_WHAT = 2; private long base; private boolean isVisible; private boolean isStarted; private boolean isRunning; private onChronometerTickListener onChronometerTickListener; public Chronometer(Context context) { this(context, null); } public Chronometer(Context context, AttributeSet attrs) { this(context, attrs, 0); } public Chronometer(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initChronometer(); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); isVisible = false; updateRunning(); } @Override protected void onWindowVisibilityChanged(int visibility) { super.onWindowVisibilityChanged(visibility); isVisible = visibility == VISIBLE; updateRunning(); } public void start() { isStarted = true; updateRunning(); } public void stop() { isStarted = false; updateRunning(); } private void updateRunning() { boolean running = isVisible && isStarted; if (running != isRunning) { if (running) { updateText(SystemClock.elapsedRealtime()); dispatchChronometerTick(); mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), 10); } else { mHandler.removeMessages(TICK_WHAT); } isRunning = running; } } private void dispatchChronometerTick() { if (null != onChronometerTickListener) { onChronometerTickListener.onChrometerTick(this); } } private void initChronometer() { base = SystemClock.elapsedRealtime(); updateText(base); } private synchronized void updateText(long now) { long timeElapsed = now - base; DecimalFormat df = new DecimalFormat("00"); int hours = (int) (timeElapsed / (3600 * 1000)); int remaining = (int) (timeElapsed % (3600 * 1000)); int minutes = remaining / (60 * 1000); remaining = remaining % (60 * 1000); int seconds = remaining / (1000); remaining = remaining % (1000); int millseconds = (((int) timeElapsed % 1000)) / 10; StringBuilder strBuilder = new StringBuilder(); if (hours > 0) { strBuilder.append(df.format(hours) + ":"); } strBuilder.append(df.format(minutes) + ":"); strBuilder.append(df.format(seconds) + ":"); strBuilder.append(millseconds); setText(strBuilder.toString()); } public void setBase(long base) { this.base = base; dispatchChronometerTick(); updateText(SystemClock.elapsedRealtime()); } public void setStarted(boolean isStarted) { this.isStarted = isStarted; updateRunning(); } private Handler mHandler = new Handler() { public void handleMessage(Message msg) { if (isRunning) { updateText(SystemClock.elapsedRealtime()); dispatchChronometerTick(); sendMessageDelayed(Message.obtain(this, TICK_WHAT), 10); } } }; public interface onChronometerTickListener { void onChrometerTick(Chronometer chronometer); } }
package ua.siemens.dbtool.dao; import ua.siemens.dbtool.model.entities.Activity; import ua.siemens.dbtool.model.entities.User; import ua.siemens.dbtool.model.timesheet.DayEntry; import java.time.LocalDate; import java.util.Collection; /** * The DAO interface for {@link DayEntry} * * @author Perevoznyk Pavlo * creation date 05 September 2017 * @version 1.0 */ public interface DayEntryDAO extends GenericDAO<DayEntry, Long> { Collection<DayEntry> findByYearMonthUser(int intYear, int intMonth, User user); Collection<DayEntry> findByPeriod(LocalDate fromDate, LocalDate toDate); Collection<DayEntry> findByActivity(Activity activity); }
package com.webstore.shoppingcart.domain.entity; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import lombok.Getter; import lombok.Setter; @Setter @Getter @Document public class User { @Id private String id; private String name; private String email; }
package com.weishengming.clientservice.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @Controller @Api(description = "首页控制层接口") public class IndexController { Logger logger = LoggerFactory.getLogger(IndexController.class); /** * 默认进入到首页 * @param model * @return */ @ApiOperation(value = "跳转到首页", notes = "跳转到首页") @RequestMapping(value = "/test", method = { RequestMethod.POST, RequestMethod.GET }) public String indexPage() { return "test/test"; } }
package com.itheima.mapper; import com.itheima.domain.User; import org.apache.ibatis.annotations.Many; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import java.util.List; public interface UserMapper { @Select("select * from `sys_user`") @Results({ @Result(property = "id", column = "id", id = true), @Result(property = "username", column = "username"), @Result(property = "password", column = "password"), @Result(property = "orderList", column = "id", javaType = List.class, many = @Many(select = "com.itheima.mapper.OrderMapper.listByUid")) }) List<User> listAll(); @Select("select * from `sys_user` where id=#{id}") User getById(Long id); @Select("<script>" + "select * from `sys_user`" + " <where>" + " <if test='id != null and id != 0'>" + " and id=#{id}" + " </if>" + " <if test='username!=null'>" + " and username=#{username}" + " </if>" + " <if test='password != null'>" + " and password=#{password}" + " </if>" + " </where>" + "</script>") List<User> listByCondition(User user); @Select("SELECT * FROM `sys_user`") @Results({ @Result(id = true, column = "id", property = "id"), @Result(column = "username", property = "username"), @Result(column = "password", property = "password"), @Result( property = "roles", column = "id", javaType = List.class, many = @Many(select = "com.itheima.mapper.RoleMapper.listByUid") ) }) List<User> listUserAndRoleAll(); }
package net.kkolyan.elements.engine.core.templates; import net.kkolyan.elements.engine.core.graphics.Text; import java.util.Arrays; import java.util.List; /** * @author nplekhanov */ public class SimpleText extends Object2d implements Text { private String text; private String color; public SimpleText(String text, String color, double x, double y) { this.text = text; this.color = color; set(x, y); } @Override public List<String> getLines() { return Arrays.asList(text.split("\\n")); } @Override public String getColor() { return color; } @Override public String toString() { return "SimpleText{" + "text='" + text + '\'' + ", color='" + color + '\'' + "} " + super.toString(); } }
/* * Copyright Verizon Media, Licensed under the terms of the Apache License, Version 2.0. See LICENSE file in project root for terms. */ package com.yahoo.cubed.source; import java.io.IOException; import org.testng.Assert; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import com.yahoo.cubed.settings.CLISettings; /** * Test configuration loader. */ public class ConfigurationLoaderTest { /** * Setup database. */ @BeforeClass public static void initialize() throws Exception { CLISettings.DB_CONFIG_FILE = "src/test/resources/database-configuration.properties"; } /** * Configuration load test. */ @Test public void testConfigurationLoad() { // property file in test resources try { ConfigurationLoader.load(); } catch (IOException e) { Assert.fail("exception", e); } } }
package com.test; import com.test.dynamic.EditDistance; import com.test.dynamic.Knapsack; import com.test.dynamic.Knapsack2; import com.test.dynamic.ShortestPath; import junit.framework.TestCase; public class DynamicSample extends TestCase { // 莱文斯距离 public void testLevenDistance() { EditDistance.levenDistance("mitcmu", "mtacnu", 3); EditDistance.levenDistance("Then why do we buy", "We should", 14); EditDistance.levenDistance("Then why do we buy albums", "We should just spend all our money on gifts", 34); } // 最长公共字符串 public void testLongestLength() { EditDistance.longestLength("mitcmu", "mtacnu", 4); EditDistance.longestLength("Then why do we buy", "We should", 5); EditDistance.longestLength("Then why do we buy albums", "We should just spend all our money on gifts", 12); } // 最短路径 public void testShortestPath() { int[][] arrayA = {{1, 2, 3}, {1, 2, 3}}; assertShortestPath(arrayA, 7); int[][] arrayB = {{0, 2, 3, 5, 6, 7, 8}, {2, 5, 3, 1, 2, 2, 2} , {2, 5, 3, 1, 2, 2, 2}, {2, 5, 3, 1, 2, 2, 2}, {2, 5, 3, 1, 2, 2, 2} , {2, 1, 3, 1, 2, 2, 2}, {2, 0, 3, 1, 2, 2, 2}, {2, 5, 3, 1, 2, 9, 2}}; assertShortestPath(arrayB, 22); int[][] arrayC = {{0, 2, 3, 5, 6, 7, -20}, {2, 5, 3, 1, 2, 2, 2}, {2, 5, 3, 1, 2, 2, 2}, {2, 5, 3, 1, 2, 2, 2}, {2, 5, 3, 1, 2, 2, 2}, {2, 1, 3, 1, 2, 2, 2}, {2, 0, 3, 1, 2, 2, 2}, {2, 5, 3, 1, 2, 9, 2}}; assertShortestPath(arrayC, 17); } /** * 最短路径 * @param array 二维 * @param result 最短路径的结果值 */ private void assertShortestPath(int[][] array, int result) { int backtrack = ShortestPath.backtrack(array); int dynamic = ShortestPath.dynamic(array); assertEquals(backtrack, result); assertEquals(dynamic, result); } /** * 01背包问题,仅重量,无价值变量 */ public void testKnapsack() { int[] valueArrayA = {1, 2, 3, 4, 5, 6, 7, 8, 9}; assertEquals(9, Knapsack.dynamic(valueArrayA, 9)); assertEquals(45, Knapsack.dynamic(valueArrayA, 45)); assertEquals(45, Knapsack.dynamic(valueArrayA, 100)); } /** * 01背包问题,有重量,有价值变量 */ public void testknapsack() { int[] heavyArrayA = {1, 2, 3, 4, 5, 6, 7, 8, 9}; float[] valueArrayA = {0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f}; assertEquals(0.9f, Knapsack2.dynamic(heavyArrayA, valueArrayA, 9)); assertEquals(4.5f, Knapsack2.dynamic(heavyArrayA, valueArrayA, 45)); assertEquals(4.5f, Knapsack2.dynamic(heavyArrayA, valueArrayA, 100)); int[] heavyArrayB = {10, 15, 34, 46, 1, 50}; float[] valueArrayB = {3, 4, 7, 77, 10, 19}; assertEquals(87f, Knapsack2.dynamic(heavyArrayB, valueArrayB, 50)); assertEquals(87f, Knapsack2.dynamic(heavyArrayB, valueArrayB, 51)); assertEquals(87f, Knapsack2.dynamic(heavyArrayB, valueArrayB, 56)); assertEquals(90f, Knapsack2.dynamic(heavyArrayB, valueArrayB, 57)); assertEquals(106f, Knapsack2.dynamic(heavyArrayB, valueArrayB, 97)); } }
package com.sinoway.sinowayCrawer.entitys; import java.util.Date; public class ToShow { //订单号 姓名 身份证号码 访问时间(最早) 注册完成时间 申请完成时间(最近) 生成报告时间 流程完成时间 String ordercode; String oname; String ocardid; String createtime; String registerfinishtime; String applytime; String getreporttime; String finishtime; public ToShow(String ordercode, String oname, String ocardid, String registerfinishtime, String applytime, String getreporttime, String finishtime) { this.ordercode = ordercode; this.oname = oname; this.ocardid = ocardid; //this.createtime = createtime; this.registerfinishtime = registerfinishtime; this.applytime = applytime; this.getreporttime = getreporttime; this.finishtime = finishtime; } public String getOrdercode() { return ordercode; } public void setOrdercode(String ordercode) { this.ordercode = ordercode; } public String getOname() { return oname; } public void setOname(String oname) { this.oname = oname; } public String getOcardid() { return ocardid; } public void setOcardid(String ocardid) { this.ocardid = ocardid; } public String getCreatetime() { return createtime; } public void setCreatetime(String string) { this.createtime = string; } public String getRegisterfinishtime() { return registerfinishtime; } public void setRegisterfinishtime(String registerfinishtime) { this.registerfinishtime = registerfinishtime; } public String getApplytime() { return applytime; } public void setApplytime(String applytime) { this.applytime = applytime; } public String getGetreporttime() { return getreporttime; } public void setGetreporttime(String getreporttime) { this.getreporttime = getreporttime; } public String getFinishtime() { return finishtime; } public void setFinishtime(String finishtime) { this.finishtime = finishtime; } }
package org.wso2.carbon.identity.user.endpoint.factories; import org.wso2.carbon.identity.user.endpoint.ValidateCodeApiService; import org.wso2.carbon.identity.user.endpoint.impl.ValidateCodeApiServiceImpl; public class ValidateCodeApiServiceFactory { private final static ValidateCodeApiService service = new ValidateCodeApiServiceImpl(); public static ValidateCodeApiService getValidateCodeApi() { return service; } }
class Solution {    public int getSum(int a, int b) {        while((a&b) != 0){            //if we have a carry            int carry = a&b;// puts 1 on exactly where the carry exists            int sum = a^b; // does the sum without carry            carry = carry << 1;// puts the carry to step to the left to be added            a = sum;//our sum without carray becomes a to be added on the next iteration            b = carry;//our carry will become b to be added on the next iteration       }        return a|b;   } }
package dao; import java.util.List; import entity.IsDone; public interface IsDoneDao extends CrudDao<Long, IsDone> { public List<IsDone> findAll(); public List<IsDone> findByName(String name); public List<IsDone> findByUserId(Long id); void deleteByUserId(Long id); }
/* ------------------------------------------------------------------------------ * 软件名称:美播手机版 * 公司名称:多宝科技 * 开发作者:Yongchao.Yang * 开发时间:2014年10月11日/2014 * All Rights Reserved 2012-2015 * ------------------------------------------------------------------------------ * 注意:本内容均来自乐多科技,仅限内部交流使用,未经过公司许可 禁止转发 * ------------------------------------------------------------------------------ * prj-name:com.rednovo.ace.communication * fileName:LocalMessageCache.java * ------------------------------------------------------------------------------- */ package com.rednovo.ace.communication.server; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import org.apache.log4j.Logger; import com.rednovo.ace.entity.Message; /** * 消息缓存 * * @author yongchao.Yang/2014年10月11日 */ public class LocalMessageCache { Logger log = Logger.getLogger(LocalMessageCache.class); private static HashMap<String, LinkedList<Message>> sendMsg = new HashMap<String, LinkedList<Message>>(), receiveMsg = new HashMap<String, LinkedList<Message>>(); private static LocalMessageCache cache; public static LocalMessageCache getInstance() { if (cache == null) { cache = new LocalMessageCache(); } return cache; } private LocalMessageCache() { log.info("[LocalMessageCache][初始化]"); } /** * 获取下一条缓存数据 * * @return * @author Yongchao.Yang * @since 2014年10月18日下午2:09:19 */ public HashMap<String, LinkedList<Message>> getReceiveMsg() { HashMap<String, LinkedList<Message>> msgs = new HashMap<String, LinkedList<Message>>(); synchronized (receiveMsg) { Iterator<String> keys = receiveMsg.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); msgs.put(key, receiveMsg.get(key)); keys.remove(); } } return msgs; } /** * 接受消息增加消息 * * @param msg * @author Yongchao.Yang * @since 2014年10月18日下午2:10:46 */ public void addReceiveMsg(String sessionId, Message msg) { synchronized (receiveMsg) { LinkedList<Message> list = receiveMsg.get(sessionId); if (list == null) { list = new LinkedList<Message>(); receiveMsg.put(sessionId, list); } list.add(msg); } } /** * 向缓存中压入消息 * * @param isSend boolean true 待发消息 false 待收消息 * @param msg * @author Yongchao.Yang * @since 2014年10月14日上午11:11:11 */ public void addSendMsg(String sessionId, Message msg) { synchronized (sendMsg) { LinkedList<Message> msgList = sendMsg.get(sessionId); if (msgList == null) { msgList = new LinkedList<Message>(); sendMsg.put(sessionId, msgList); } msgList.add(msg); } } /** * 获取下一个待发消息 * * @return * @author Yongchao.Yang * @since 2014年10月14日上午11:13:28 */ public LinkedList<Message> getSendMsg(String sessionId) { LinkedList<Message> list = new LinkedList<Message>(); synchronized (sendMsg) { LinkedList<Message> msgList = sendMsg.get(sessionId); while (!msgList.isEmpty()) { list.add(msgList.remove()); } } return list; } /** * 获取待发消息条数 * * @return * @author Yongchao.Yang * @since 2014年10月14日上午11:19:29 */ public int getSendMsgCnt(String sessionId) { synchronized (sendMsg) { LinkedList<Message> msgList = sendMsg.get(sessionId); if (msgList != null) { return msgList.size(); } return 0; } } /** * 获取未读消息片段个数 * * @param clientId * @return * @author Yongchao.Yang * @since 2014年10月16日下午9:55:40 */ public int getReceiveMsgCnt() { synchronized (receiveMsg) { return receiveMsg.size(); } } }
package com.tsuro.action.actionpat; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.tsuro.board.ColorString; import com.tsuro.board.Token; import com.tsuro.tile.ITile; import java.lang.reflect.Type; import lombok.NonNull; /** * Deserializes an action-pat as defined https://ccs.neu.edu/home/matthias/4500-f19/4.html#%28tech._action._pat%29 * into an {@link ActionPat}. */ public class ActionPatDeserializer implements JsonDeserializer<ActionPat> { @Override public ActionPat deserialize(@NonNull JsonElement jsonElement, @NonNull Type type, @NonNull JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { if (jsonElement.isJsonArray()) { JsonArray ja = jsonElement.getAsJsonArray(); if (ja.size() == 2) { Token token = new Token( jsonDeserializationContext.deserialize(ja.get(0), ColorString.class)); ITile tile = jsonDeserializationContext.deserialize(ja.get(1), ITile.class); return new ActionPat(token, tile); } } throw new JsonParseException("Not an action-pat"); } }
import java.util.Random; public class CreateTrain implements Runnable { private int trainNumGen; private int trainNum; private String trainType; private int trainSpeed; public CreateTrain(int trainNumGen, int trainNum, String trainType,int trainSpeed) { this.trainNumGen = trainNumGen; this.trainNum = trainNum; this.trainType = trainType; this.trainSpeed = trainSpeed; } @Override public void run() { /* * As the train creation should continue * indefinitely it becomes very difficult * to see what is happening to slow it * thread is made to sleep for 2 second * so a new train is created every 2 seconds. */ while(true) { try { Thread.sleep(2000); }catch(InterruptedException e) {}; // Random number is generated to provide // random selection of train category and // Characteristics like speed and trainid number Random r = new Random(); // The probability of train being of either // category is equal, If random number is // greater then 10 it is express train with // 100 speed else local train with 10 speed trainNumGen = r.nextInt(20); if (trainNumGen < 10) {trainType = "Local";trainSpeed = 10;trainNum = trainNumGen; }else { trainType = "Express";trainSpeed = 100;trainNum = trainNumGen; } // create new train every two seconds // and run it on its own thread. final Train train = new Train(trainType,trainSpeed ,trainNum); Thread trainThread = new Thread(train); trainThread.start(); } } }
package com.ipartek.ejercicios.listas; import com.ipartek.pojo.Carta; import java.util.ArrayList; import java.util.Scanner; public class Ejercicio4 { static final String PALOS_NOMBRES[] = {"Bastos","Copas","Espadas","Oros"}; static final String CARTAS_NOMBRES[] = {"As","Dos","Tres","Cuatro","Cinco","Seis","Siete","Sota","Caballo","Rey"}; static ArrayList<Carta> listaCartas = new ArrayList<Carta>(); public static void main(String[] arg) { //static ArrayList<Jugador> listaJugadores = new ArrayList<Jugador>(); crearBaraja(); barajar(); } private static void barajar() { int i = 0; int contador = 0; Carta carta = new Carta(); do { i = (int) Math.floor(Math.random()*(0-(listaCartas.size())+1)+(listaCartas.size())); carta = listaCartas.get(i-1); contador++; System.out.println("Carta " + contador + " : " + CARTAS_NOMBRES[carta.getNumero()] + " de " + carta.getPalo()); listaCartas.remove(i-1); }while (!listaCartas.isEmpty()); System.out.println("Final"); } private static void crearBaraja() { for (int palo = 0 ; palo < PALOS_NOMBRES.length ; palo++) { System.out.println(PALOS_NOMBRES[palo]); System.out.println( "-----------------"); for (int numero = 0 ; numero < CARTAS_NOMBRES.length ; numero ++) { Carta carta = new Carta(numero, PALOS_NOMBRES[palo]); listaCartas.add(carta); System.out.println(CARTAS_NOMBRES[numero] + " de " + PALOS_NOMBRES[palo]); } System.out.println( "======================================================="); System.out.println( " "); } } }
package cn.chay; import cn.chay.filters.pre.PreRequestLogFilter; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; @SpringBootApplication /** * zuul整合了Hystrix,整合了容错 * * zuul与spring boot actuator配合使用时,zuul会暴露两个端点: * /route和filters。借助这些端点,可方便、直观地查看以及管理zuul。 * * zuul已包含actuator监控功能 */ @EnableZuulProxy public class ZuulApplication { @Bean public PreRequestLogFilter preRequestLogFilter() { return new PreRequestLogFilter(); } public static void main(String[] args) { SpringApplication.run(ZuulApplication.class, args); } }
package com.raymon.api.demo.leetcodedemo; import java.util.Arrays; /** * @author :raymon * @date :Created in 2019/7/19 9:13 * @description:给定一个 n × n 的二维矩阵表示一个图像。将图像顺时针旋转 90 度。 * 给定 matrix = * [ * [1,2,3], * [4,5,6], * [7,8,9] * ], * & 原地旋转输入矩阵,使其变为: * [ * [7,4,1], * [8,5,2], * [9,6,3] * ] * @modified By: * @version: 1.0$ */ public class RotateArray { public static void rotateArray(int[][] matrix) { int n = matrix.length; if (n <= 1) { return; } //旋转次数 int count = n * n / 4; int x = 0; int y = 0; int z = 0; int x1, y1, x2, y2; for (int i = 0; i < count; i++) { if (z >= (n - 1) - 2 * x) { x += 1; z = 0; } y = z + x; z += 1; x1 = x; y1 = y; for (int j = 0; j < 3; j++) { x2 = n - 1 - y1; y2 = x1; matrix[x1][y1] = matrix[x2][y2] ^ matrix[x1][y1]; matrix[x2][y2] = matrix[x1][y1] ^ matrix[x2][y2]; matrix[x1][y1] = matrix[x1][y1] ^ matrix[x2][y2]; x1 = x2; y1 = y2; } } System.out.println(Arrays.deepToString(matrix)); } public static void main(String[] args) { int[][] matrix = { {1,2,3}, {4,5,6}, {7,8,9} }; System.out.println(Arrays.deepToString(matrix)); rotateArray(matrix); } }
package io.report.modules.ser.service.impl; import org.springframework.stereotype.Service; import java.util.Map; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import io.report.common.utils.PageUtils; import io.report.common.utils.Query; import io.report.modules.ser.dao.DtTableRsDao; import io.report.modules.ser.entity.DtTableRsEntity; import io.report.modules.ser.service.DtTableRsService; @Service("dtTableRsService") public class DtTableRsServiceImpl extends ServiceImpl<DtTableRsDao, DtTableRsEntity> implements DtTableRsService { @Override public PageUtils queryPage(Map<String, Object> params) { Page<DtTableRsEntity> page = this.selectPage( new Query<DtTableRsEntity>(params).getPage(), new EntityWrapper<DtTableRsEntity>() ); return new PageUtils(page); } }
package com.actitime.businessLib; import org.openqa.selenium.By; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.Select; import com.actitime.genericLib.Driver; import com.actitime.genericLib.WebDriverCommomLib; import com.actitime.pageObjrepository.ActiveProjectAndCust; import com.actitime.pageObjrepository.AddNewCustomer; import com.actitime.pageObjrepository.CommomPage; import com.actitime.pageObjrepository.Login; import com.actitime.pageObjrepository.OpenTasks; public class ProjectAndCustomerLib extends WebDriverCommomLib{ Login loginPage = PageFactory.initElements(Driver.driver, Login.class); OpenTasks openTaskPage = PageFactory.initElements(Driver.driver, OpenTasks.class); ActiveProjectAndCust actProAndCustPage = PageFactory.initElements(Driver.driver, ActiveProjectAndCust.class); AddNewCustomer addnewCustPage= PageFactory.initElements(Driver.driver, AddNewCustomer.class); CommomPage comonPage = PageFactory.initElements(Driver.driver, CommomPage.class); public void loginToAPP(String username , String password){ Driver.driver.get("http://susanta-pc/login.do"); loginPage.getUserNameEdt().sendKeys(username); loginPage.getPasswordEdt().sendKeys(password); loginPage.getLoginBtn().click(); waitForPageToLoad(); } public void navigateToProAndCustPage(){ openTaskPage.getProAndCustLnk().click(); waitForPageToLoad(); } public void createCustomer(String customerName){ actProAndCustPage.getAddNewCustBtn().click(); waitForPageToLoad(); addnewCustPage.getCustNameEdt().sendKeys(customerName); addnewCustPage.getCreateCustomerBtn().click(); waitForPageToLoad(); } public void navigateCustomerDetailsPage(String customerName){ select(actProAndCustPage.getSelectAllCustLst(), "100"); waitForwbLinkTextPresent(customerName); Driver.driver.findElement(By.linkText(customerName)).click(); waitForPageToLoad(); } public void logout(){ comonPage.getLogOutImg().click(); waitForPageToLoad(); } }
package dominio.participantes; import java.util.Date; import dominio.endereco.Endereco; import dominio.evento.EntidadeDominio; public abstract class Pessoa extends EntidadeDominio { private String nome; private int genero; private Date dtNascimento; private String cpf; private String telefone; private Endereco endereco; public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public int getGenero() { return genero; } public void setGenero(int genero) { this.genero = genero; } public Date getDtNascimento() { return dtNascimento; } public void setDtNascimento(Date dtNascimento) { this.dtNascimento = dtNascimento; } public String getCpf() { return cpf; } public void setCpf(String cpf) { this.cpf = cpf; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public Endereco getEndereco() { return endereco; } public void setEndereco(Endereco endereco) { this.endereco = endereco; } }
package com.krt.gov.strategy.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.metadata.IPage; import com.krt.common.annotation.KrtLog; import com.krt.common.base.BaseController; import com.krt.common.bean.DataTable; import com.krt.common.bean.ReturnBean; import com.krt.common.session.SessionUser; import com.krt.common.util.ShiroUtils; import com.krt.gov.strategy.entity.GovPush; import com.krt.gov.strategy.entity.GovPushStaff; import com.krt.gov.strategy.entity.GovPushStrategy; import com.krt.gov.strategy.service.IGovPushService; import com.krt.gov.strategy.service.IGovPushStaffService; import com.krt.gov.strategy.service.IGovPushStrategyService; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import javax.validation.constraints.NotNull; import java.util.Arrays; import java.util.List; import java.util.Map; /** * 推送规则设置控制层 * * @author 郭明德 * @version 1.0 * @date 2019年07月13日 */ @Controller public class GovPushController extends BaseController { @Autowired private IGovPushService govPushService; @Autowired private IGovPushStaffService govPushStaffService; @Autowired private IGovPushStrategyService govPushStrategyService; /** * 推送规则设置管理页 * * @return {@link String} */ @RequiresPermissions("GovPush:govPush:list") @GetMapping("gov/strategy/govPush/list") public String list() { return "strategy/govPush/list"; } /** * 推送规则设置管理 * * @param para 搜索参数 * @return {@link DataTable} */ @RequiresPermissions("GovPush:govPush:list") @PostMapping("gov/strategy/govPush/list") @ResponseBody public DataTable list(@RequestParam Map para) { SessionUser sessionUser = ShiroUtils.getSessionUser(); if (sessionUser.isAdmin()) { IPage page = govPushService.selectPageList(para); return DataTable.ok(page); } else { para.put("area", sessionUser.getArea()); IPage page = govPushService.selectPageList(para); return DataTable.ok(page); } } /** * 新增推送规则设置页 * * @return {@link String} */ @RequiresPermissions("GovPush:govPush:insert") @GetMapping("gov/strategy/govPush/insert") public String insert() { return "strategy/govPush/insert"; } /** * 添加推送规则设置 * * @param govPush 推送规则设置 * @return {@link ReturnBean} */ @KrtLog("添加推送规则设置") @RequiresPermissions("GovPush:govPush:insert") @PostMapping("gov/strategy/govPush/insert") @ResponseBody public ReturnBean insert(GovPush govPush) { SessionUser sessionUser = ShiroUtils.getSessionUser(); if (sessionUser.isAdmin()) { govPushService.insert(govPush); } else { govPush.setArea(sessionUser.getArea()); govPushService.insert(govPush); } return ReturnBean.ok(); } /** * 修改推送规则设置页 * * @param id 推送规则设置id * @return {@link String} */ @RequiresPermissions("GovPush:govPush:update") @GetMapping("gov/strategy/govPush/update") public String update(Integer id) { GovPush govPush = govPushService.selectById(id); request.setAttribute("govPush", govPush); return "strategy/govPush/update"; } /** * 修改推送规则设置 * * @param govPush 推送规则设置 * @return {@link ReturnBean} */ @KrtLog("修改推送规则设置") @RequiresPermissions("GovPush:govPush:update") @PostMapping("gov/strategy/govPush/update") @ResponseBody public ReturnBean update(GovPush govPush) { govPushService.updateById(govPush); return ReturnBean.ok(); } /** * 推送规则设置页 * * @param id 推送规则设置id * @return {@link String} */ @RequiresPermissions("GovPush:govPush:setting") @GetMapping("gov/strategy/govPush/setting") public String setting(String id) { // 查询所有的关联策略 List<GovPushStrategy> govStrategys = govPushService.selectPushStrategyById(id); JSONArray jsonArray1 = JSONArray.parseArray(JSON.toJSONString(govStrategys)); String strategyJsonStr = jsonArray1.toJSONString(); // 查询所有的关联推送人员 List<GovPushStaff> govStaffs = govPushService.selectPushStaffById(id); JSONArray jsonArray2 = JSONArray.parseArray(JSON.toJSONString(govStaffs)); String pushManJsonStr = jsonArray2.toJSONString(); request.setAttribute("strategyJsonStr", strategyJsonStr); request.setAttribute("pushManJsonStr", pushManJsonStr); request.setAttribute("pushId", id); return "strategy/govPush/setting"; } /** * 策略规则设置 * * @param pushId * @param strategyJsonStr * @param pushManJsonStr * @return */ @KrtLog("推送规则设置") @RequiresPermissions("GovPush:govPush:setting") @PostMapping("gov/strategy/govPush/setting") @ResponseBody public ReturnBean setting(String pushId, String strategyJsonStr, String pushManJsonStr) { //删除所有关联策略和推送人 govPushStaffService.deleteStaffByPushId(pushId); govPushStrategyService.deleteStrategyByPushId(pushId); //添加策略推送人 if (!"".equals(pushManJsonStr)) { JSONArray pushManJsonArray = JSON.parseArray(StringEscapeUtils.unescapeHtml4(pushManJsonStr)); List<GovPushStaff> govPushStaffs = JSONObject.parseArray(pushManJsonArray.toJSONString(), GovPushStaff.class); for (GovPushStaff govPushStaff : govPushStaffs) { govPushStaff.setPushId(Integer.parseInt(pushId)); govPushStaffService.insert(govPushStaff); } } //添加关联策略 if (!"".equals(strategyJsonStr)) { JSONArray strategyJsonArray = JSON.parseArray(StringEscapeUtils.unescapeHtml4(strategyJsonStr)); List<GovPushStrategy> govPushStrategies = JSONObject.parseArray(strategyJsonArray.toJSONString(), GovPushStrategy.class); for (GovPushStrategy govPushStrategy : govPushStrategies) { govPushStrategy.setPushId(Integer.parseInt(pushId)); govPushStrategyService.insert(govPushStrategy); } } return ReturnBean.ok(); } /** * 推送规则启用禁用设置 * * @param id 推送规则设置id */ @KrtLog("推送规则启用禁用设置") @RequiresPermissions("GovPush:govPush:status") @PostMapping("gov/strategy/govPush/status") @ResponseBody public ReturnBean status(@NotNull String status, @NotNull String id) { govPushService.updateStatusById(status, id); return ReturnBean.ok(); } /** * 删除推送规则设置 * * @param id 推送规则设置id * @return {@link ReturnBean} */ @KrtLog("删除推送规则设置") @RequiresPermissions("GovPush:govPush:delete") @PostMapping("gov/strategy/govPush/delete") @ResponseBody public ReturnBean delete(Integer id) { govPushService.deleteById(id); return ReturnBean.ok(); } /** * 批量删除推送规则设置 * * @param ids 推送规则设置ids * @return {@link ReturnBean} */ @KrtLog("批量删除推送规则设置") @RequiresPermissions("GovPush:govPush:delete") @PostMapping("gov/strategy/govPush/deleteByIds") @ResponseBody public ReturnBean deleteByIds(Integer[] ids) { govPushService.deleteByIds(Arrays.asList(ids)); return ReturnBean.ok(); } /** * 保存策略名称和推送人员名字 */ @KrtLog("保存策略名称和推送人员名字") @PostMapping("gov/strategy/govPush/saveStrategyAndStaff") @ResponseBody public ReturnBean saveStrategyAndStaff(String strategyName, String staffName, String pushId) { govPushService.saveStrategyAndStaff(strategyName, staffName, pushId); return ReturnBean.ok(); } }
package kr.or.ddit.profile_file.service; import java.util.List; import java.util.Map; import kr.or.ddit.profile_file.dao.IProfileFileDao; import kr.or.ddit.vo.ProfileFileVO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.support.DaoSupport; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; @Service public class ProfileFileServiceImpl implements IProfileFileService { @Autowired private IProfileFileDao profileFileDao; @Transactional(propagation=Propagation.REQUIRED, readOnly=true) @Override public ProfileFileVO selectProfileFileInfo(Map<String, String> params) throws Exception { return profileFileDao.selectProfileFileInfo(params); } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class}) @Override public void insertProfileFileInfo(ProfileFileVO profileInfo) throws Exception { profileFileDao.insertProfileFileInfo(profileInfo); } @Transactional(propagation=Propagation.REQUIRED, rollbackFor={Exception.class}) @Override public void insertMypageFileInfo(List<ProfileFileVO> fileitemList) throws Exception { profileFileDao.insertMypageFileInfo(fileitemList); } }
package answers; import org.junit.*; public class GuitarTest { @Test public void testInstrumentInfo_ShouldReturnCorrectDescription() { // ARRANGE - Create a new Guitar object Guitar guitar = new Guitar(); // ACT - Call the getInstrumentInfo() method and store the result in a String variable String instrumentInfo = guitar.getInstrumentInfo(); // ASSERT - Check that the info equals 'This black guitar has 6 strings and costs 1000 dollars' Assert.assertEquals( "This black guitar has 6 strings and costs 1000 dollars", instrumentInfo ); } }
package kh.baseball; public class WrongInputException extends Exception { public WrongInputException() { System.out.println("You have input incorrect number, please input numbers from 1~9."); } }
package com.distributie.listeners; import com.distributie.enums.EnumOperatiiAdresa; public interface OperatiiAdresaListener { void opAdresaComplete(EnumOperatiiAdresa methodName, String result); }
package com.karya.dao.impl; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.karya.dao.IStockReportDao; import com.karya.model.StkRepAgeing001MB; import com.karya.model.StkRepLedger001MB; import com.karya.model.StkRepProjected001MB; import com.karya.model.StockRepBalance001MB; @Repository @Transactional public class StockReportDaoImpl implements IStockReportDao{ @PersistenceContext private EntityManager entityManager; public void addstkrepledger(StkRepLedger001MB stkrepledger001MB) { entityManager.merge(stkrepledger001MB); } @SuppressWarnings("unchecked") public List<StkRepLedger001MB> liststkrepledger() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<StkRepLedger001MB> cq = builder.createQuery(StkRepLedger001MB.class); Root<StkRepLedger001MB> root = cq.from(StkRepLedger001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public StkRepLedger001MB getstkrepledger(int stledId) { StkRepLedger001MB stkrepledger001MB = entityManager.find(StkRepLedger001MB.class, stledId); return stkrepledger001MB; } public void deletestkrepledger(int stledId) { StkRepLedger001MB stkrepledger001MB = entityManager.find(StkRepLedger001MB.class, stledId); entityManager.remove(stkrepledger001MB); } //Stock report balance public void addstkrepbalance(StockRepBalance001MB stkrepbalance001MB) { entityManager.merge(stkrepbalance001MB); } @SuppressWarnings("unchecked") public List<StockRepBalance001MB> liststkrepbalance() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<StockRepBalance001MB> cq = builder.createQuery(StockRepBalance001MB.class); Root<StockRepBalance001MB> root = cq.from(StockRepBalance001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public StockRepBalance001MB getstkrepbalance(int stbalId) { StockRepBalance001MB stkrepbalance001MB = entityManager.find(StockRepBalance001MB.class, stbalId); return stkrepbalance001MB; } public void deletestkrepbalance(int stbalId) { StockRepBalance001MB stkrepbalance001MB = entityManager.find(StockRepBalance001MB.class, stbalId); entityManager.remove(stkrepbalance001MB); } //Stock report projected public void addstkrepprojected(StkRepProjected001MB stkrepprojected001MB) { entityManager.merge(stkrepprojected001MB); } @SuppressWarnings("unchecked") public List<StkRepProjected001MB> liststkrepprojected() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<StkRepProjected001MB> cq = builder.createQuery(StkRepProjected001MB.class); Root<StkRepProjected001MB> root = cq.from(StkRepProjected001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public StkRepProjected001MB getstkrepprojected(int stprojId) { StkRepProjected001MB stkrepprojected001MB = entityManager.find(StkRepProjected001MB.class, stprojId); return stkrepprojected001MB; } public void deletestkrepprojected(int stprojId) { StkRepProjected001MB stkrepprojected001MB = entityManager.find(StkRepProjected001MB.class, stprojId); entityManager.remove(stkrepprojected001MB); } //Stock Report Ageing public void addstkrepageing(StkRepAgeing001MB stkrepageing001MB) { entityManager.merge(stkrepageing001MB); } @SuppressWarnings("unchecked") public List<StkRepAgeing001MB> liststkrepageing() { CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<StkRepAgeing001MB> cq = builder.createQuery(StkRepAgeing001MB.class); Root<StkRepAgeing001MB> root = cq.from(StkRepAgeing001MB.class); cq.select(root); return entityManager.createQuery(cq).getResultList(); } public StkRepAgeing001MB getstkrepageing(int stageId) { StkRepAgeing001MB stkrepageing001MB = entityManager.find(StkRepAgeing001MB.class, stageId); return stkrepageing001MB; } public void deletestkrepageing(int stageId) { StkRepAgeing001MB stkrepageing001MB = entityManager.find(StkRepAgeing001MB.class, stageId); entityManager.remove(stkrepageing001MB); } }
package 多线程.生产者和消费者; /** * Created by 陆英杰 * 2018/9/7 14:36 */ public class 生产者和消费者 { }
/* * Created on 19/08/2008 * * To change the template for this generated file go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ package com.citibank.ods.modules.product.prodassettype.functionality; import java.math.BigInteger; import org.apache.struts.action.ActionForm; import com.citibank.ods.common.functionality.BaseFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.modules.product.prodassettype.form.BaseProdAssetTypeListForm; import com.citibank.ods.modules.product.prodassettype.functionality.valueobject.BaseProdAssetTypeListFncVO; /** * @author rcoelho * * To change the template for this generated type comment go to * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments */ public abstract class BaseProdAssetTypeListFnc extends BaseFnc{ /* * (non-Javadoc) * @see com.citibank.ods.common.functionality.BaseFnc#updateFncVOFromForm(org.apache.struts.action.ActionForm, * com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void updateFncVOFromForm( ActionForm form_, BaseFncVO fncVO_ ) { BaseProdAssetTypeListForm baseProdAssetTypeListForm = ( BaseProdAssetTypeListForm ) form_; BaseProdAssetTypeListFncVO baseProdAssetTypeListFncVO = ( BaseProdAssetTypeListFncVO ) fncVO_; if ( baseProdAssetTypeListForm.getProdAssetTypeCodeSrc() != null && !"".equals( baseProdAssetTypeListForm.getProdAssetTypeCodeSrc() ) ) { baseProdAssetTypeListFncVO.setProdAssetTypeCodeSrc( new BigInteger( baseProdAssetTypeListForm.getProdAssetTypeCodeSrc() ) ); } else { baseProdAssetTypeListFncVO.setProdAssetTypeCodeSrc( null ); } baseProdAssetTypeListFncVO.setProdAssetTypeTextSrc( baseProdAssetTypeListForm.getProdAssetTypeTextSrc() ); } /* * (non-Javadoc) * @see com.citibank.ods.common.functionality.BaseFnc#updateFormFromFncVO(org.apache.struts.action.ActionForm, * com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void updateFormFromFncVO( ActionForm form_, BaseFncVO fncVO_ ) { BaseProdAssetTypeListForm baseProdAssetTypeListForm = ( BaseProdAssetTypeListForm ) form_; BaseProdAssetTypeListFncVO baseProdAssetTypeListFncVO = ( BaseProdAssetTypeListFncVO ) fncVO_; if ( baseProdAssetTypeListFncVO.getProdAssetTypeCodeSrc() != null ) { baseProdAssetTypeListForm.setProdAssetTypeCodeSrc( baseProdAssetTypeListFncVO.getProdAssetTypeCodeSrc().toString() ); } baseProdAssetTypeListForm.setProdAssetTypeTextSrc( baseProdAssetTypeListFncVO.getProdAssetTypeTextSrc() ); baseProdAssetTypeListForm.setResults( baseProdAssetTypeListFncVO.getResults() ); } }
package Area4; /** * Created by james on 30/11/2018. */ public class File1Area4 { int i = 0; }
import java.util.ArrayList; import java.util.List; /* 悲观gc ——parallel scavenge https://blog.csdn.net/liuxiao723846/article/details/72808495/ 1、在YGC执行前,min(目前新生代已使用的大小,之前平均晋升到old的大小中的较小值) > 旧生代剩余空间大小 ? 不执行YGC,直接执行Full GC : 执行YGC; 2、在YGC执行后,平均晋升到old的大小 > 旧生代剩余空间大小 ? 触发Full GC : 什么都不做。 Sun JDK之所以要有悲观策略,我猜想理由是程序最终是会以一个较为稳态的状况执行的,此时每次YGC后晋升到old的对象大小应该是差不多的,在YGC时做好检查,避免等YGC后晋升到Old的对象导致old空间不足,因此还不如干脆就直接执行FGC,正因为悲观策略的存在,大家有些时候可能会看到old空间没满但full gc执行的状况。 Xmx和Xms不一致的时候,会导致gc次数增多 G1GC退化 GCeasy.io */ public class PessimismGC { public static void main(String[] args) { //-Xms30m -Xmx30m -Xmn10m -XX:+UseParallelGC List<byte[]> arrayList = new ArrayList<>(); for (int i = 0; i < 7; i++) { byte[] bytes = new byte[1024*1024*3];//3M arrayList.add(bytes); } arrayList.clear(); for (int i = 0; i < 2; i++) { byte[] bytes = new byte[1024*1024*3];//3M arrayList.add(bytes); } } }
import java.util.Scanner; public class List1 { public static void main(String[] args) { TextMenu menu = new TextMenu(); menu.textMenu(); } }
package com.acme.impl; import com.acme.DataProvider; import com.acme.impl.DataFile; import com.google.common.base.Charsets; import com.google.common.io.Files; import com.google.inject.Inject; import java.io.File; import java.util.List; import org.eclipse.xtext.xbase.lib.Exceptions; import org.eclipse.xtext.xbase.lib.IterableExtensions; @SuppressWarnings("all") public class FileDataProvider implements DataProvider { @Inject @DataFile private String dataFile; public String getData() { try { File _file = new File(this.dataFile); List<String> _readLines = Files.readLines(_file, Charsets.UTF_8); String _join = IterableExtensions.join(_readLines, "\n"); return _join; } catch (Exception _e) { throw Exceptions.sneakyThrow(_e); } } }
package cn.edu.njnu.nnu_creative_cloud; import android.view.View; public abstract class FunctionActivity extends BaseActivity { public void return_back(View view) { if (super.setting) { SettingFragment settingfragment = (SettingFragment) getFragmentManager() .findFragmentById(setting_container_id); getFragmentManager().beginTransaction().remove(settingfragment) .commit(); super.setting = false; } } }
package com.hdy.myhxc.controller; import com.hdy.myhxc.entity.FormInfo; import com.hdy.myhxc.entity.ResultData; import com.hdy.myhxc.model.Menu; import com.hdy.myhxc.service.MenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author m760384371 * @date 2019/8/26 */ @RestController @RequestMapping(value = "/m0003") public class MenuController { @Autowired private MenuService menuServiceImpl; /** * 获取所有菜单列表 * @param info * @return */ @RequestMapping("list") public ResponseEntity<ResultData> showMenuList(@ModelAttribute FormInfo info) { return new ResponseEntity<>(menuServiceImpl.getMenuList(info.getPage(), info.getLimit()), HttpStatus.OK); } /** * 根据id删除菜单信息 * @param uuid * @return */ @RequestMapping("delete/{uuid}") public ResponseEntity<ResultData> delMenu(@PathVariable String uuid) { ResultData resultData = new ResultData(); resultData.setData(menuServiceImpl.delMenu(uuid)); return new ResponseEntity<>(resultData, HttpStatus.OK); } /** * 根据id获取菜单信息 * @param uuid * @return */ @RequestMapping("get/{uuid}") public ResponseEntity<ResultData> getMenu(@PathVariable String uuid) { return new ResponseEntity<>(menuServiceImpl.getMenu(uuid), HttpStatus.OK); } /** * 编辑或新增菜单 * @param menu * @return */ @RequestMapping("edit") public ResponseEntity<ResultData> editMenu(@ModelAttribute Menu menu) { ResultData resultData = new ResultData(); resultData.setData(menuServiceImpl.editMenu(menu)); return new ResponseEntity<>(resultData, HttpStatus.OK); } }
package nl.kolkos.photoGallery.services; import java.io.File; import java.nio.file.Path; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import nl.kolkos.photoGallery.entities.Photo; import nl.kolkos.photoGallery.entities.PhotoGallery; import nl.kolkos.photoGallery.entities.User; import nl.kolkos.photoGallery.repositories.PhotoRepository; @Service public class PhotoServiceImpl implements PhotoService{ @Autowired private PhotoRepository photoRepository; @Autowired private UserService userService; @Autowired private PhotoGalleryACLService photoGalleryACLService; @Autowired private FileStorageService fileStorageService; private static final Logger logger = LoggerFactory.getLogger(PhotoServiceImpl.class); @Override public Photo save(Photo photo) { return photoRepository.save(photo); } @Override public Photo save(String fileName, String fileDownloadUrl, long size) { // get the user Authentication auth = SecurityContextHolder.getContext().getAuthentication(); User currentUser = userService.findByEmail(auth.getName()); Path uploadFolder = fileStorageService.getFileStorageLocation(); // find the default gallery for this user PhotoGallery gallery = photoGalleryACLService.findDefaultGalleryForUser(currentUser).getPhotoGallery(); Photo photo = new Photo(); photo.setName(fileName); photo.setFileDownloadUrl(fileDownloadUrl); photo.setSize(size); photo.setFileLocation(uploadFolder.toString() + "/" + fileName); photo.setPhotoGallery(gallery); photo.setUploadDate(new Date()); photo.setUploader(currentUser); return this.save(photo); } @Override public void uploadsCleaner() { Path uploadFolder = fileStorageService.getFileStorageLocation(); File folder = new File(uploadFolder.toString()); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { if(! listOfFiles[i].isHidden()) { String filePath = listOfFiles[i].getAbsolutePath(); // check if the photo is registered in the database Photo photo = this.findByFileLocation(filePath); if(photo == null) { logger.info("Could not find file '{}' in the database. Deleting file..."); File file = new File(filePath); file.delete(); } } } } } @Override public Photo findByFileLocation(String fileLocation) { return photoRepository.findByFileLocation(fileLocation); } }
package com.uit.huydaoduc.hieu.chi.hhapp.Model.Passenger; public enum PassengerRequestState { FINDING_DRIVER, FOUND_DRIVER, PAUSE, TIME_OUT }
package cn.plusman.poc.mybatis.plus.explore.mapper; import cn.plusman.poc.mybatis.plus.explore.entity.Blog; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.ResultMap; import java.util.List; /** * cn.plusman.mybatis.mapper * * @author plusman * @since 12/17/20 */ public interface BlogMapper extends BaseMapper<Blog> { /** * 根据 id 获取博客内容 * @param id * @return */ Blog selectBlog( int id ); /** * 获取博客列表 * @return */ List<Blog> selectList(); }
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import bean.ClassInfoBean; public class ClassInfoDao { String CLASSFORNAME="com.mysql.jdbc.Driver"; String SERVANDDB="jdbc:mysql://localhost:3306/studentsystem?useSSL=false"; String USER="root"; String PWD="root"; public void addClassInfo(ClassInfoBean bean) { Connection conn = null; Statement stmt = null; String cid,cname; try { Class.forName(CLASSFORNAME); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { // 获取数据库连接 conn = DriverManager .getConnection(SERVANDDB,USER,PWD); // 整理一条SQL语句 // System.out.println(bean.getCid()); cid=bean.getCid().toString(); cname=bean.getCname(); String sql = "INSERT INTO class_info (cid,cname) VALUES ('"+cid+"','" + cname + "')"; // 创建SQL执行对象 stmt = conn.createStatement(); // 执行sql语句 int row = stmt.executeUpdate(sql); if (row != 1) { throw new RuntimeException("新增班级失败!"); } } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } } public List<ClassInfoBean> findAll() { Connection conn = null; Statement stmt = null; List<ClassInfoBean> classList= new ArrayList<ClassInfoBean>(); try { Class.forName(CLASSFORNAME); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { // 获取连接 conn = DriverManager .getConnection(SERVANDDB,USER,PWD); // 整理一条SQL语句 String sql = "select cid,cname from class_info"; // 创建执行sql的对象 stmt = conn.createStatement(); //执行sql语句 ResultSet rs =stmt.executeQuery(sql); //遍历结果集 while(rs.next()){ int cid =rs.getInt("cid"); String cname=rs.getString("cname"); ClassInfoBean bean = new ClassInfoBean(); bean.setCid(cid); bean.setCname(cname); classList.add(bean); } } catch (SQLException e) { e.printStackTrace(); } return classList; } }
public class Main { public static void main(String[] args) { String filename = "C:\\Users\\abac\\Desktop\\Facultate\\flcd\\FLCD\\lab4\\src\\main\\java\\data\\fa.txt"; FiniteAutomata fa = new FiniteAutomata(); FAReader controller = new FAReader(fa, filename); UI userInterface = new UI(controller); userInterface.run(); } }
package com.test.base; import java.util.List; import com.test.SolutionA; import junit.framework.TestCase; public class Example extends TestCase { private SolutionA solution; @Override protected void setUp() throws Exception { super.setUp(); } public void testSolutionA() { solution = new SolutionA(); assertSolution(); } private void assertSolution() { List<List<String>> resultA = solution.partition("aab"); ListUtils.print(resultA); List<List<String>> resultB = solution.partition("aaab"); ListUtils.print(resultB); List<List<String>> resultC = solution.partition("cbbbcc"); ListUtils.print(resultC); /*List<List<String>> resultC = solution.partition("aaabbbbccccddd"); ListUtils.print(resultC);*/ } @Override protected void tearDown() throws Exception { super.tearDown(); } }
package com.SearchHouse.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.SearchHouse.pojo.Collect; public interface CollectMapper { // 新增收藏; public void addClollect(@Param("houseId") Integer houseId, @Param("userId") String userId); // 删除收藏 public void deleteCollect(@Param("houseId") Integer houseId, @Param("userId") String userId); // 修改收藏 public void updateCollect(Collect collect); // 通过ID查询 public Collect getCollectById(@Param("houseId") Integer houseId, @Param("userId") String userId); // 查询所有的收藏 public List<Collect> listAllCollect(); }
package com.burst.message; /** * Lookup services registered for a `name`. {@link BindingsMessage} will be sent to * `sender()`. */ public class LookupMessage { public final String name; public LookupMessage (String name) { this.name = name; } }
package org.opal; public class incorrect { public String $a_clumsy__String; }
package com.bookdataanalyzer; import java.io.*; import java.util.*; /** * Metrics collected for every author * @author nirav99 * */ public class CollectiveMetrics { private HashMap<String, AuthorMetrics> authorMetricsMap; public CollectiveMetrics() { authorMetricsMap = new HashMap<String, AuthorMetrics>(); } public void processFile(File inputDir, String fileName) { System.out.println("Processing file : " + fileName); // Assumption is that file name starts with author name followed by underscore int indexOfUnderscore = fileName.indexOf("_"); String authorName = (indexOfUnderscore >= 0) ? fileName.substring(0, indexOfUnderscore) : null; File inputFile = new File(inputDir.getAbsolutePath() + File.separator + fileName); try { FileDataAnalyzer fileDataAnalyzer = new FileDataAnalyzer(inputFile); FileDataStats fileDataStats = fileDataAnalyzer.fileDataStats(); if(authorName != null) { AuthorMetrics authorMetrics = authorMetricsMap.get(authorName); if(authorMetrics == null) authorMetrics = new AuthorMetrics(authorName); authorMetrics.updateMetrics(fileDataStats); authorMetricsMap.put(authorName, authorMetrics); } } catch (IOException e) { System.out.println("Error while processing file : " + fileName + "\n" + e.getMessage()); e.printStackTrace(); } } /** * Write a file that contains the summary of the percentage of different types of words per author * @param summaryFile */ public void writeSummary(File summaryFile) { try { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(summaryFile), "UTF-8")); writer.write("Author,PercentNouns,PercentVerbs,PercentAdjactives"); writer.newLine(); Set<String> keySet = authorMetricsMap.keySet(); AuthorMetrics authorMetrics; double percentNouns; double percentVerbs; double percentAdjectives; for(String key : keySet) { authorMetrics = authorMetricsMap.get(key); percentNouns = 1.0 * authorMetrics.totalNouns() / authorMetrics.totalWords() * 100; percentVerbs = 1.0 * authorMetrics.totalVerbs() / authorMetrics.totalWords() * 100; percentAdjectives = 1.0 * authorMetrics.totalAdjectives() / authorMetrics.totalWords() * 100; writer.write(key + "," + String.format("%.2f", percentNouns) + "," + String.format("%.2f", percentVerbs) + "," + String.format("%.2f", percentAdjectives)); writer.newLine(); } writer.close(); } catch(Exception e) { e.printStackTrace(); } } /** * Generate a file per author that contains more detailed information about the data collected for that author. * @param outputDir */ public void writeDetailedInformation(File outputDir) { File outputFile = null; Set<String> keySet = authorMetricsMap.keySet(); for(String key : keySet) { try { outputFile = new File(outputDir.getAbsolutePath() + File.separator + key + "_analysis.txt"); System.out.println("Writing file : " + outputFile.getAbsolutePath()); if(false == outputFile.createNewFile()) { outputFile.delete(); outputFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(outputFile); PrintStream ps = new PrintStream(fos); AuthorMetrics authorMetrics = authorMetricsMap.get(key); authorMetrics.truncateLowFrequencyValues(); authorMetrics.printInfo(ps); ps.flush(); ps.close(); } catch(Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } } } }
package com.gs.tablasco.spark; import com.gs.tablasco.spark.avro.AvroDataSupplier; import org.apache.avro.Schema; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumWriter; import org.apache.commons.io.FileUtils; import org.apache.hadoop.fs.Path; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; import org.junit.Assert; import org.junit.Rule; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestName; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class AbstractSparkVerifierTest { private static final boolean REBASE = false; static GenericRecord row(Schema schema, Object... values) { GenericRecord record = new GenericData.Record(schema); for (int i = 0; i < schema.getFields().size(); i++) { record.put(schema.getFields().get(i).name(), values[i]); } return record; } private static final JavaSparkContext JAVA_SPARK_CONTEXT = new JavaSparkContext("local[4]", AbstractSparkVerifierTest.class.getSimpleName(), new SparkConf() .set("spark.ui.enabled", "false") .set("spark.logLineage", "true") .set("spark.sql.shuffle.partitions", "10") .set("spark.task.maxFailures", "1") .set("spark.io.compression.codec", "org.apache.spark.io.LZ4CompressionCodec")); @Rule public final TestName testName = new TestName(); @Rule public final TemporaryFolder temporaryFolder = new TemporaryFolder(); protected void runTest(List<GenericRecord> actual, List<GenericRecord> expected, boolean passed, SparkVerifier sparkVerifier) throws IOException { File actualData = this.temporaryFolder.newFile("actual.avro"); writeAvroData(actual, actualData); File expectedDate = this.temporaryFolder.newFile("expected.avro"); writeAvroData(expected, expectedDate); SparkResult sparkResult = sparkVerifier.verify("data", new AvroDataSupplier(JAVA_SPARK_CONTEXT, new Path(actualData.toURI().toString())), new AvroDataSupplier(JAVA_SPARK_CONTEXT, new Path(expectedDate.toURI().toString()))); String html = sparkResult.getHtml(); java.nio.file.Path baselineFile = Paths.get("src", "test", "resources", this.getClass().getSimpleName(), this.testName.getMethodName() + ".html"); if (REBASE) { baselineFile.toFile().getParentFile().mkdirs(); Files.write(baselineFile, html.getBytes()); Assert.fail("REBASE SUCCESSFUL - " + baselineFile); } Assert.assertEquals(passed, sparkResult.isPassed()); Assert.assertEquals( replaceValuesThatMayAppearInNonDeterministicRowOrder(new String(Files.readAllBytes(baselineFile))), replaceValuesThatMayAppearInNonDeterministicRowOrder(html)); } private static String replaceValuesThatMayAppearInNonDeterministicRowOrder(String value) { return value // mask all test values because output order is non-deterministic (test values start with 1230) .replaceAll(">1,?2,?3,?0,?\\S*?([ <])", ">###$1") // mask variance percentages .replaceAll("/ [\\d\\.-]+%", "###%"); } private static void writeAvroData(List<GenericRecord> data, File avroFile) throws IOException { FileUtils.forceMkdir(avroFile.getParentFile()); Schema schema = data.get(0).getSchema(); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter); dataFileWriter.create(schema, avroFile); for (GenericRecord genericRecord : data) { dataFileWriter.append(genericRecord); } dataFileWriter.close(); } }
package com.artauction.service; import java.util.List; import com.artauction.domain.GoodsVO; import com.artauction.domain.ImageVO; import com.artauction.domain.ListVO; import com.artauction.domain.UserVO; public interface RegisterService { public void insert(GoodsVO gVo); public List<ImageVO> findImageByGno(int gno); public void checkUserAccount(UserVO uVo); // main화면에서 추천 리스트 public List<ListVO> recommandList(); // 유저의 정보에 계좌정보가있으면 get public UserVO getUserAccount(UserVO uVo); }