text
stringlengths 10
2.72M
|
|---|
package com.smxknife.java2.lock.producer_consumer.reentrantlock;
import com.smxknife.java2.lock.producer_consumer.Repository;
import java.util.Objects;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author smxknife
* 2019/9/13
*/
public class ReentrantLockRepository<E> implements Repository<E> {
private final Lock lock = new ReentrantLock();
private final Condition consumeCond = lock.newCondition();
private final Condition produceCond = lock.newCondition();
private final Object[] items;
private int tail, head, count;
public ReentrantLockRepository(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("capacity must be gather 0");
}
this.items = new Object[capacity];
}
@Override
public void produce(E e) {
Objects.requireNonNull(e);
lock.lock();
try {
while (count >= items.length) {
produceCond.await();
}
items[tail++] = e;
count++;
if (tail == items.length) {
tail = 0;
}
this.consumeCond.signal();
} catch (InterruptedException th) {
th.printStackTrace();
} finally {
lock.unlock();
}
}
@Override
public E consume() {
lock.lock();
try {
while (this.count <= 0) {
this.count = 0;
this.consumeCond.await();
}
E e = (E) this.items[head];
this.items[head++] = null;
this.count--;
if (this.head == this.items.length) {
this.head = 0;
}
this.produceCond.signal();
return e;
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return null;
}
}
|
package newgame;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import mainmenu.ButtonOneHandlerObject;
import matches.MatchOpponents;
import java.io.FileInputStream;
public class ButtonHandlerPreviousGame extends ButtonsNewGame {
private Stage primaryStage;
void buttonNewPreviousGame(){
try{
PreviousGroup previousGroup = new PreviousGroup();
button6();
raffleStyle();
groupStyle();
// when button is pressed
button6.setOnAction(event6);
groups.setOnAction(eventSimulate);
raffle.setOnAction(eventRaffleGroups);
Pane root = new Pane();
root.getChildren().addAll(button6, groups, raffle,
previousGroup.printGroup(),previousGroup.printGroupSecond(),previousGroup.printGroupThird(),
previousGroup.printGroupFourth(),previousGroup.printGroupFivth(),previousGroup.printGroupSixth(),
previousGroup.printGroupSeventh(),previousGroup.printGroupEighth());
// create a scene
Scene scene = new Scene(root, 1650, 928);
FileInputStream inputBackground = new FileInputStream("C:\\Users\\Asus\\WorldCupSimulator\\src\\main\\resources\\groups.jpg");
// create a image
Image image = new Image(inputBackground);
// create a background image
BackgroundImage backgroundimage = new BackgroundImage(image,
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.CENTER,
BackgroundSize.DEFAULT);
// create Background
Background background = new Background(backgroundimage);
// set background
root.setBackground(background);
//set the scene
primaryStage.setScene(scene);
primaryStage.show();
}catch(Exception r){
r.printStackTrace();
}
}
private EventHandler<ActionEvent> event6 = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e)
{
ButtonOneHandlerObject boho = new ButtonOneHandlerObject();
boho.setScene(primaryStage);
boho.buttonOneObject();
}
};
private EventHandler<ActionEvent> eventSimulate = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
MatchOpponents matchOpponents = new MatchOpponents();
matchOpponents.setArrayList(GroupStageRand.teamsMainList);
matchOpponents.chooseWinner();
GroupSimulated.teamsMainList = matchOpponents.teamsMainList;
ButtonHandlerSimulateGame bhsg = new ButtonHandlerSimulateGame();
bhsg.setScene(primaryStage);
bhsg.buttonSimulateObject();
}
};
private EventHandler<ActionEvent> eventRaffleGroups = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
ButtonHandlerNewGameShuffle bhnwgs = new ButtonHandlerNewGameShuffle();
bhnwgs.setScene(primaryStage);
bhnwgs.buttonNewGameObjectShuffle();
}
};
public void setScene(Stage primaryStage){
this.primaryStage = primaryStage;
}
}
|
package miniMipSim.pipeline;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;
import miniMipSim.pipeline.parts.RegisterToken;
public class RegisterFile {
private LinkedList<RegisterToken> temporary;
private LinkedList<RegisterToken> finalized;
private final Path fFilePath;
private final Charset ENCODING = StandardCharsets.UTF_8;
/**
* Constructor.
*
* @param fileName - the register file
* @throws IOException
*/
public RegisterFile(String fileName) throws IOException {
temporary = new LinkedList<RegisterToken>();
finalized = new LinkedList<RegisterToken>();
fFilePath = Paths.get(fileName);
try (Scanner scanner = new Scanner(fFilePath, ENCODING.name())) {
while (scanner.hasNextLine()) {
processLine(scanner.nextLine());
}
}
}
/**
* Takes a line from the register file provided and adds it to the register file object.
*
* @param aLine - string from register file
*/
private void processLine(String aLine) {
String tempName = null;
String tempValue = null;
int name;
int value;
aLine.trim();
Scanner scanner = new Scanner(aLine.substring(2, aLine.length()-1));
scanner.useDelimiter(",");
if (scanner.hasNext()) {
tempName = scanner.next();
tempValue = scanner.next();
}
name = Integer.parseInt(tempName);
value = Integer.parseInt(tempValue);
// temporary.add(new RegisterToken(name, value));
finalized.add(new RegisterToken(name, value));
scanner.close();
}
/**
* Given a register, it will return the token of that register.
*
* @param registerName - the integer value of the register
* @return
*/
public RegisterToken getToken(int registerName) {
for (int i = 0; i < finalized.size(); i++) {
if(finalized.get(i).registerName == registerName) {
return finalized.get(i);
}
}
return null;
}
/**
* Adds a register token to the register file.
*
* @param t - the register token to be added
*/
public void putToken (RegisterToken t) {
for (int i = 0; i < finalized.size(); i++) {
if (t.registerName == finalized.get(i).registerName) {
if (t.registerValue == finalized.get(i).registerValue) {
return;
}
else {
finalized.get(i).registerValue = t.registerValue;
return;
}
}
}
temporary.add(t);
}
/**
* Syncs the two internal buffers.
*/
public void sync() {
while(!temporary.isEmpty()) {
finalized.add(temporary.removeFirst());
}
temporary.clear();
}
/**
* Writes the contents of the RegisterFile to a buffer.
*
* @param out - the buffer to be written
* @throws IOException
*/
public void printContents(BufferedWriter out) throws IOException {
Collections.sort(finalized);
out.write("RF:");
if (finalized.isEmpty()) {
out.write("\n");
return;
}
for (int i = 0; i < finalized.size() - 1; i++) {
out.write(finalized.get(i).toString() + ",");
}
out.write(finalized.get(finalized.size()-1).toString() + "\n");
}
/**
* Prints the contents of the RegisterFile
*/
public void printContents() {
Collections.sort(finalized);
System.out.print("RF:");
if (finalized.isEmpty()) {
System.out.print("\n");
return;
}
for (int i = 0; i < finalized.size() - 1; i++) {
System.out.print(finalized.get(i).toString() + ",");
}
System.out.print(finalized.get(finalized.size()-1).toString() + "\n");
}
}
|
import br.com.unialfa.ia.core.heuristic.SolucaoCtx;
import br.com.unialfa.ia.core.heuristic.impl.BuscaEmProfundidade;
import br.com.unialfa.ia.core.model.Grafo;
import br.com.unialfa.ia.core.model.Vertice;
public class Teste {
public static void main(String[] args) {
Vertice goiania = new Vertice("Goiania");
Vertice belaVista = new Vertice("Bela Vista de Goiás");
Vertice caldasNovas = new Vertice("Caldas Novas");
Vertice morrinhos = new Vertice("Morrinhos");
Vertice edeia = new Vertice("Edeia");
Vertice hidrolandia = new Vertice("Hidrolandia");
Vertice silvania = new Vertice("Silvania");
Vertice vianapolis = new Vertice("Vianapolis");
Vertice ipameri = new Vertice("Ipameri");
Vertice pontalina = new Vertice("Pontalina");
Vertice piracanjuba = new Vertice("Piracanjuba");
Vertice orizona = new Vertice("Orizona");
Vertice[] cidades = { goiania, belaVista, caldasNovas, morrinhos, edeia, hidrolandia, silvania, vianapolis,
ipameri, pontalina, piracanjuba, orizona };
goiania.adicionarDestino(belaVista, 481);
goiania.adicionarDestino(edeia, 124);
goiania.adicionarDestino(hidrolandia, 33);
goiania.adicionarDestino(silvania, 67);
belaVista.adicionarDestino(caldasNovas, 117);
edeia.adicionarDestino(pontalina, 69);
pontalina.adicionarDestino(morrinhos, 124);
morrinhos.adicionarDestino(caldasNovas, 57);
hidrolandia.adicionarDestino(piracanjuba, 70);
hidrolandia.adicionarDestino(morrinhos, 90);
silvania.adicionarDestino(vianapolis, 18);
vianapolis.adicionarDestino(orizona, 46);
orizona.adicionarDestino(ipameri, 95);
ipameri.adicionarDestino(caldasNovas, 61);
Grafo grafo = new Grafo();
grafo.adicionarVertice(goiania);
grafo.adicionarVertice(belaVista);
grafo.adicionarVertice(caldasNovas);
grafo.adicionarVertice(hidrolandia);
grafo.adicionarVertice(pontalina);
grafo.adicionarVertice(orizona);
grafo.adicionarVertice(morrinhos);
grafo.adicionarVertice(edeia);
grafo.adicionarVertice(silvania);
grafo.adicionarVertice(vianapolis);
grafo.adicionarVertice(piracanjuba);
grafo.adicionarVertice(ipameri);
grafo.listarVertices();
SolucaoCtx.buscaCega = new BuscaEmProfundidade();
Grafo solucao = SolucaoCtx.processarGrafo(grafo, goiania);
System.out.println("=============================================");
//
SolucaoCtx.processarSolucao(solucao, caldasNovas);
}
}
|
package com.guli.ucenter.controller;
import com.google.gson.Gson;
import com.guli.ucenter.entity.Member;
import com.guli.ucenter.service.MemberService;
import com.guli.ucenter.untils.HttpClientUtils;
import com.guli.ucenter.untils.WxUntils;
import com.guli.utils.GuliException;
import com.guli.utils.JwtUtils;
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.RequestMapping;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
@Controller
@RequestMapping("/ucenter/wx")
public class WxApiController {
@Autowired
private MemberService memberService;
@GetMapping("callback")
public String callback(String code,String state){
try {
String baseurl="https://api.weixin.qq.com/sns/oauth2/access_token"+
"?appid=%s" +
"&secret=%s" +
"&code=%s" +
"&grant_type=authorization_code";
String url = String.format(
baseurl,
WxUntils.APP_ID,
WxUntils.APP_SECRET,
code);
System.out.println(code+state);
String s = HttpClientUtils.get(url);
Gson gson=new Gson();
HashMap hashMap = gson.fromJson(s, HashMap.class);
String access_token = (String) hashMap.get("access_token");
String openid = (String) hashMap.get("openid");
Member member = memberService.getByOpenId(openid);
String token="";
if (member==null){
String info="https://api.weixin.qq.com/sns/userinfo"+
"?access_token=%s" +
"&openid=%s";
String urlinfo = String.format(
info,
access_token,
openid);
String s1 = HttpClientUtils.get(urlinfo);
HashMap hashMap1 = gson.fromJson(s1, HashMap.class);
String nickname = (String) hashMap1.get("nickname");
String headimgurl = (String) hashMap1.get("headimgurl");
Member members=new Member();
members.setOpenid(openid);
members.setNickname(nickname);
members.setAvatar(headimgurl);
members.setGmtCreate(new Date());
members.setGmtModified(new Date());
memberService.save(member);
token= JwtUtils.getJwtToken(members.getId(),members.getNickname());
}
return "redirect:http://localhost:3000?token="+token;
} catch (Exception e) {
e.printStackTrace();
throw new GuliException(20001,"登陆失败");
}
}
@GetMapping("wchatlogin")
public String WChatLogin() throws UnsupportedEncodingException {
String baseurl="https://open.weixin.qq.com/connect/qrconnect"+
"?appid=%s" +
"&redirect_uri=%s" +
"&response_type=code" +
"&scope=snsapi_login" +
"&state=%s" +
"#wechat_redirect";
String redirect=WxUntils.REDIRECT_URL;
redirect=URLEncoder.encode(redirect, StandardCharsets.UTF_8);
String url = String.format(
baseurl,
WxUntils.APP_ID,
redirect,
"guli");
return "redirect:"+url;
}
}
|
package xdpm.nhom11.angrybirdsproject.bird;
import java.util.Random;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import xdpm.nhom11.angrybirdsproject.entities.Bird;
import xdpm.nhom11.angrybirdsproject.manager.EffectManager;
import xdpm.nhom11.angrybirdsproject.manager.Game;
import xdpm.nhom11.angrybirdsproject.manager.SceneManager;
import xdpm.nhom11.angrybirdsproject.physicseditor.PhysicsEditorShapeLibrary;
import xdpm.nhom11.angrybirdsproject.resourcemanager.SoundHelper;
import xdpm.nhom11.angrybirdsproject.resourcemanager.TexturePackerHelper;
/**
* Chim đỏ
*
* @author Hoa Phat
*
*/
public class RedBird extends Bird {
/**
* @param pX
* vị trí x
* @param pY
* vị trí y
* @param fixturedef
* fixture
*/
public RedBird(float pX, float pY, FixtureDef fixturedef) {
super(pX, pY, fixturedef);
}
/*
* (non-Javadoc)
*
* @see xdpm.nhom11.angrybirdsproject.entities.GameEntity#loadResource()
*/
@Override
public void loadResource() {
mSprite = new AnimatedSprite(mPosition.x, mPosition.y,
TexturePackerHelper.RED_BIRD_TILEDTEXTURE,
Game.getInstance().vbom);
}
/*
* (non-Javadoc)
*
* @see xdpm.nhom11.angrybirdsproject.entities.Bird#loadBody(xdpm.nhom11.
* angrybirdsproject.physicseditor.PhysicsEditorShapeLibrary,
* org.andengine.extension.physics.box2d.PhysicsWorld)
*/
@Override
public void loadBody(PhysicsEditorShapeLibrary physicseditor,
PhysicsWorld physicsworld) {
this.mBody = physicseditor.createBody("RED BIRD", this.mSprite,
physicsworld, this.mFixture);
super.loadBody(physicseditor, physicsworld);
}
/*
* (non-Javadoc)
*
* @see xdpm.nhom11.angrybirdsproject.entities.Bird#collide(float)
*/
@Override
public void collide(float force) {
super.collide(force);
if (force > 700) {
EffectManager eff = new EffectManager();
EffectManager.getInstance().showBirdFeather(this.mSprite.getX(),
this.mSprite.getY(), "red");
SoundHelper.redbird_collision.play();
this.mSprite.setCurrentTileIndex(4);
}
}
/*
* (non-Javadoc)
*
* @see xdpm.nhom11.angrybirdsproject.entities.Bird#checkState()
*/
@Override
public void checkState() {
super.checkState();
this.mSprite.setCurrentTileIndex(new Random().nextInt(2));
}
@Override
public void destroy() {
super.destroy();
EffectManager.getInstance().showBirdFeather(this.mSprite.getX(),
this.mSprite.getY(), "red");
}
@Override
public void UseSkill() {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see
* xdpm.nhom11.angrybirdsproject.entities.Bird#Shoot(com.badlogic.gdx.math
* .Vector2)
*/
@Override
public void Shoot(Vector2 force) {
// TODO Auto-generated method stub
super.Shoot(force);
this.mSprite.setCurrentTileIndex(3);
}
}
|
package video;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.player.MediaPlayerFactory;
import uk.co.caprica.vlcj.player.embedded.EmbeddedMediaPlayer;
import uk.co.caprica.vlcj.player.embedded.windows.Win32FullScreenStrategy;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import uk.co.caprica.vlcj.runtime.x.LibXUtil;
public class MediaPanel {
public static void main (final String [] args) {
SwingUtilities.invokeLater (new Runnable () {
@Override
public void run ()
{
chargerLibrairie ();
new MediaPanel (args);
}
});
}
static void chargerLibrairie () {
NativeLibrary.addSearchPath (
RuntimeUtil.getLibVlcLibraryName (), "C: / Program Files / VideoLAN / VLC");
Native.loadLibrary (RuntimeUtil.getLibVlcLibraryName (), LibVlc.class);
LibXUtil.initialise ();
}
private MediaPanel (String [] args) {
JFrame frame = new JFrame ("Tutorial vlcj");
frame.setLocation (100, 100);
frame.setSize (1050, 600);
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setVisible (true);
// Create an instance of Canvas
Canvas c = new Canvas ();
// The background of the video is black by default
c.setBackground (Color.black);
JPanel p = new JPanel ();
p.setLayout (new BorderLayout ());
// The video takes up the whole surface
p.add (c, BorderLayout.CENTER);
frame.add (p, BorderLayout.CENTER);
// Create a factory instance
MediaPlayerFactory mediaPlayerFactory = new MediaPlayerFactory ();
// Create a media player instance
EmbeddedMediaPlayer mediaPlayer = mediaPlayerFactory.newEmbeddedMediaPlayer (new Win32FullScreenStrategy (frame));
mediaPlayer.setVideoSurface (mediaPlayerFactory.newVideoSurface (c));
//Full screen
mediaPlayer.toggleFullScreen ();
// Hide the mouse cursor inside JFrame
mediaPlayer.setEnableMouseInputHandling (false);
// Disable the keyboard inside JFrame
mediaPlayer.setEnableKeyInputHandling (true);
// Prepare the file
mediaPlayer.prepareMedia ( "video.mp4");
// read the file
mediaPlayer.play ();
}
}
|
package gdut.ff.controller;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
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.RestController;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import gdut.ff.domain.Category;
import gdut.ff.domain.Message;
import gdut.ff.exception.LoginException;
import gdut.ff.service.CategoryServiceImpl;
import gdut.ff.utils.Constant;
import gdut.ff.utils.JsonUtil;
import gdut.ff.utils.NodeUtil;
/**
* 文章分类
* @author liuffei
* @date 2018-07-05
*/
@RestController
public class CategoryController extends CommController{
@Autowired
private CategoryServiceImpl categoryServiceImpl;
/**
* 添加文章分类记录
* @return
* @throws Exception
*/
@PostMapping(value = "/category")
public JSONObject insertCategory(@RequestBody Category category,HttpServletRequest request) throws Exception {
requireAuth(request);
//添加categoryId的值
if(0 != category.getId()) {
categoryServiceImpl.updateCategory(category);
}else {
categoryServiceImpl.insertCategory(category);
}
//服务端推送消息
JSONObject categoryJson = new JSONObject();
categoryJson.put("category", category);
return JsonUtil.successJson();
}
/**
*
* @param id
* @return
*/
@GetMapping(value = "/category/{id}")
public JSONObject findCategoryById(@PathVariable Integer id, HttpServletRequest request, HttpServletResponse response) {
Category category = categoryServiceImpl.fingCategoryById(id);
JSONObject result = JsonUtil.successJson();
result.put("content", category);
return result;
}
/**
* 查询指定的文章分类记录
* @param id
* @return
*/
@PutMapping(value = "/category/{id}")
public JSONObject updateCategoryById(@PathVariable String id, @RequestBody Category category, HttpServletRequest request) {
categoryServiceImpl.updateCategory(category);
return JsonUtil.successJson();
}
/**
* 删除文章分类记录
* @param id
* @return
* @throws Exception
*/
@DeleteMapping(value = "/category/{id}")
public JSONObject deleteCategoryById(@PathVariable Integer id, HttpServletRequest request) throws Exception {
requireAuth(request);
categoryServiceImpl.deleteCategoryById(id);
return JsonUtil.successJson();
}
/**
* 查询全部文章分类
* @param id
* @return
*/
@GetMapping(value = "/categorys")
public JSONObject findAllCategorys(Category category) {
List<Category> categorys = categoryServiceImpl.findAllCategory(category);
JSONObject result = JsonUtil.successJson();
result.put("categorys", categorys);
return result;
}
}
|
package com.petersoft.mgl.model;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;
@Entity
public class Location {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int locationId;
private String locationName;
@OneToMany(mappedBy = "location")
private List<Lepcso> lepcsoList;
@CreationTimestamp
private LocalDateTime creationDateTime;
@UpdateTimestamp
private LocalDateTime updateDateTime;
public Location() {
}
public Location(String location) {
this.locationName = location;
}
public int getLocationId() {
return locationId;
}
public void setLocationId(int locationId) {
this.locationId = locationId;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public List<Lepcso> getLepcsoList() {
return lepcsoList;
}
public void setLepcsoList(List<Lepcso> lepcsoList) {
this.lepcsoList = lepcsoList;
}
@Override
public String toString() {
return locationName;
}
public LocalDateTime getCreationDateTime() {
return creationDateTime;
}
public void setCreationDateTime(LocalDateTime creationDateTime) {
this.creationDateTime = creationDateTime;
}
public LocalDateTime getUpdateDateTime() {
return updateDateTime;
}
public void setUpdateDateTime(LocalDateTime updateDateTime) {
this.updateDateTime = updateDateTime;
}
}
|
package com.hs.doubaobao.bean;
/**
* 作者:zhanghaitao on 2017/9/25 14:20
* 邮箱:820159571@qq.com
*
* @describe:审批返回的BEAN
*/
public class ApprovalBean {
/**
* resCode : 1
* resMsg :
* resData : {}
*/
private int resCode;
private String resMsg;
private ResDataBean resData;
public int getResCode() {
return resCode;
}
public void setResCode(int resCode) {
this.resCode = resCode;
}
public String getResMsg() {
return resMsg;
}
public void setResMsg(String resMsg) {
this.resMsg = resMsg;
}
public ResDataBean getResData() {
return resData;
}
public void setResData(ResDataBean resData) {
this.resData = resData;
}
public static class ResDataBean {
}
}
|
package com.yorkwang.model;
import com.jfinal.plugin.activerecord.Model;
import com.yorkwang.service.UploadImageService;
import com.yorkwang.utils.Utils;
public class Design extends Model<Design>{
public static final Design dao = new Design().dao();
private String paths = "";
private String[] pathArray = null;
public String getPaths() {
return paths;
}
public void setPaths(String paths) {
this.paths = paths;
pathArray = paths!=null && paths.length() != 0 ? paths.split(",") : null;
}
public String[] getPathArray() {
return pathArray;
}
public void generatePaths() {
String ids = this.getStr("pic_ids");
String paths = Utils.getArrayString(UploadImageService.getCompanyImagesString(ids));
System.out.println("paths:" + paths);
this.setPaths(paths);
}
}
|
package gameLogic.goal;
import java.util.Random;
import Util.Tuple;
import gameLogic.map.Station;
import gameLogic.resource.Cargo;
import gameLogic.resource.Train;
import gameLogic.resource.Cargo.trainCargo;
public class Goal {
private Station origin;
private Station via;
private Station destination;
private int turnIssued;
private boolean complete = false;
private int reward;
//constraints
private String trainName = null;
//goal cosmetic
private trainCargo cargo;
private String cargoString;
private Random random = new Random();
public Goal(Station argOrigin, Station argDestination, Station via, int turn, int score) {
this.origin = argOrigin;
this.via = via;
this.destination = argDestination;
this.turnIssued = turn;
this.reward = score; //current score
int ranNum = random.nextInt(trainCargo.values().length);
this.cargo = Cargo.getCargo(ranNum);
}
/**
* Add a train constraint to the goal
* @param name - pass "train" to add a train constraint
* @param value - train to add to goal as constraint.
*/
public void addConstraint(String name, String value) {
if(name.equals("train")) {
trainName = value;
} else {
throw new RuntimeException(name + " is not a valid goal constraint");
}
}
/**
* Checks if the goal is complete
* @param train that may have completed the goal
* @return true if goal is completed, else false
*/
public boolean isComplete(Train train) {
boolean passedOrigin = false;
boolean passedVia = false;
for(Tuple<String, Integer> history : train.getHistory()) {
if(history.getFirst().equals(origin.getName()) && history.getSecond() >= turnIssued) {
passedOrigin = true;
}
}
if (via != null){
for (Tuple<String, Integer> history : train.getHistory()){
if (history.getFirst().equals(via.getName()) && history.getSecond() >= turnIssued){
passedVia = true;
}
}
if(train.getFinalDestination() == destination && passedOrigin && passedVia) {
if(trainName == null || trainName.equals(train.getName())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
else {
if(train.getFinalDestination() == destination && passedOrigin) {
if(trainName == null || trainName.equals(train.getName())) {
return true;
} else {
return false;
}
} else {
return false;
}
}
}
/**
* Returns a text description of the goal
*/
public String toString() {
String goalString;
String trainString = "train";
if(trainName != null) {
trainString = trainName;
}
goalString = "Send a " + trainString + " carrying a " + cargo.toString().toLowerCase() + " from " + origin.getName();
if (via != null){
goalString += " via " + via.getName();
}
goalString += " to " + destination.getName();
goalString += " - " + reward + " points";
return goalString;
}
/** get the string of the filepath for the goal's cargo image
*
* @return
*/
public String getImgFile() {
String imgFilePath = "animal/";
switch (cargo) {
case SNAKE:
imgFilePath += "snake.png";
break;
case BEAR:
imgFilePath += "bear.png";
break;
case MONKEY:
imgFilePath += "monkey.png";
break;
case GIRAFFE:
imgFilePath += "giraffe.png";
break;
case PENGUIN:
imgFilePath += "penguin.png";
break;
case SHEEP:
imgFilePath += "sheep.png";
break;
case ELEPHANT:
imgFilePath += "elephant.png";
break;
case OCTOPUS:
imgFilePath += "octopus.png";
break;
case ZEBRA:
imgFilePath += "zebra.png";
break;
case LION:
imgFilePath += "lion.png";
break;
case PIG:
imgFilePath += "pig.png";
break;
case DRAGON:
imgFilePath += "dragon.png";
break;
case YETI:
imgFilePath += "yeti.png";
break;
default:
imgFilePath += "lion.png";
break;
}
return imgFilePath;
}
public void setComplete() {
complete = true;
}
public boolean getComplete() {
return complete;
}
public int getReward() {
return reward;
}
public trainCargo getCargo() {
return cargo;
}
public Station getOrigin() {
return origin;
}
public Station getDestination() {
return destination;
}
}
|
package com.steatoda.commons.fields.demo.model.person;
import com.steatoda.commons.fields.service.async.FieldsAsyncService;
public interface PersonAsyncService extends FieldsAsyncService<String, Person, Person.Field> {
@Override
default Person instance() {
return new Person();
}
}
|
package com.byxy.student.action;
import javax.annotation.Resource;
import com.byxy.student.entity.Student;
import com.byxy.student.service.StudentService;
import com.byxy.student.util.Pager;
import com.opensymphony.xwork2.ActionSupport;
public class StudentListAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
@Resource
StudentService studentService;
// 当前页
private String curPage;
// 行数
private String pageCount;
// 列表集合
private Pager<Student> pager;
/*
* 列表Action
*/
public String list() {
pager = studentService.getPage(curPage, pageCount);
System.out.println(pager);
return SUCCESS;
}
public Pager<Student> getPager() {
return pager;
}
public void setPager(Pager<Student> pager) {
this.pager = pager;
}
public String getCurPage() {
return curPage;
}
public void setCurPage(String curPage) {
this.curPage = curPage;
}
public String getPageCount() {
return pageCount;
}
public void setPageCount(String pageCount) {
this.pageCount = pageCount;
}
}
|
package com.tuitaking.everyDay;
import org.junit.Assert;
import org.junit.Test;
public class EraseOverlapIntervalsT {
@Test
public void test(){
int[][] arrays= new int[][]{ {1,2}, {2,3}, {3,4}, {1,3} };
int[][] arrays1= new int[][]{{1,100},{11,22},{1,11},{2,12}};
EraseOverlapIntervals eraseOverlapIntervals=new EraseOverlapIntervals();
Assert.assertEquals(eraseOverlapIntervals.eraseOverlapIntervals(arrays),1);
Assert.assertEquals(eraseOverlapIntervals.eraseOverlapIntervals(arrays1),2);
}
}
|
package ui;
import input.KeyInput;
import input.MouseInput;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
public class TextInput implements UiElement {
private String text = "";
private KeyInput keyInput;
private MouseInput mouseInput;
private Rectangle hitbox;
private boolean texting = false;
public TextInput(int x, int y,int size, KeyInput keyInput, MouseInput mouseInput) {
this.hitbox = new Rectangle(x, y, size, size / 4);
this.mouseInput = mouseInput;
this.keyInput = keyInput;
}
@Override
public void init() {
}
@Override
public void onInteract() {
if(hitbox.contains(mouseInput.getX(), mouseInput.getY()) && mouseInput.isLeftMouse()){
texting = true;
}
if(texting){
boolean[] keys = keyInput.getKeysReleased();
for (int i = 0; i < keys.length; i++) {
if(keys[i]){
if(keys[KeyEvent.VK_SPACE]){
text += " ";
keys[i] = false;
return;
}
if(keys[KeyEvent.VK_BACK_SPACE]){
text = text.substring(0, text.length() - 1);
keys[i] = false;
return;
}
if(keys[KeyEvent.VK_ENTER]){
texting = false;
keys[i] = false;
return;
}
text += KeyEvent.getKeyText(i);
keys[i] = false;
}
}
}
}
@Override
public void render(Graphics g) {
g.drawRect(hitbox.x, hitbox.y, hitbox.width, hitbox.height);
g.drawString(text,hitbox.x, hitbox.y + 25);
}
public String getText() {
return text;
}
}
|
package de.ybroeker.assertions.json;
import org.assertj.core.api.AbstractCharSequenceAssert;
import org.assertj.core.util.CheckReturnValue;
/**
* @author ybroeker
*/
public class JsonStringAssert extends AbstractCharSequenceAssert<JsonStringAssert, String> implements JsonElementAssert {
private JsonAssert parent;
@CheckReturnValue
public JsonStringAssert(final JsonAssert parent, final String actual) {
super(actual, JsonStringAssert.class);
this.parent = parent;
}
@CheckReturnValue
@Override
public JsonAssert and() {
return parent;
}
}
|
package at.fhj.swd.service;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import at.fhj.swd.data.entity.Document;
import at.fhj.swd.data.entity.User;
/**
* Interface to service which handles all requests to documents.
*
* @author Group1
* editet Group3
* */
public interface DocumentService {
public List<Document> getGlobalDocuments();
//Global
public void uploadGlobalDocument(InputStream source, final String name) throws IOException;
public void deleteGlobalDocument(final String name);
public void deleteGlobalDocuments();
public InputStream downloadGlobalDocument(final String name) throws IOException;
//Community
public List<Document> getCommunityDocuments(final String community);
public void uploadCommunityDocument(final String community, InputStream source, final String name) throws IOException;
public InputStream downloadCommunityDocument(final String community, final String name) throws IOException;
public void deleteCommunityDocument(final String community, final String name);
//User
public List<Document> getUserDocuments(final String user);
public void uploadUserDocument(final String user, InputStream source, final String name) throws IOException;
public InputStream downloadUserDocument(final String user, final String name) throws IOException;
public void deleteUserDocument(final String user, final String name);
//User
public List<Document> getAdminDocuments();
public void uploadAdminDocument(InputStream source, final String name) throws IOException;
public InputStream downloadAdminDocument(final String name) throws IOException;
public void deleteAdminDocument(final String name);
/**
* checks if user is logged in.
*
* @param token
* @return
*/
public boolean getAdministrationAllowed(String token);
public User getUserByToken(String token);
boolean getUserAdministrationAllowed(String token);
public boolean getIsAdministrator(String token);
}
|
package com.cloudogu.smeagol.repository.domain;
/**
* Repository to query branches.
*/
@SuppressWarnings("squid:S1609") // ignore FunctionalInterface warning
public interface BranchRepository {
/**
* Find all branches of the repository with the given repository id.
*
* @param repositoryId id of repository
*
* @return all branches of the repository
*/
Iterable<Branch> findByRepositoryId(RepositoryId repositoryId);
}
|
package day30_wrapperClass;
public class boxing {
public static void main(String[] args) {
Integer num1= 1234;
int n=2;
Integer num2=n;
Double d1 = new Double(4.25);
double d2=d1;
Integer num3 =Integer.valueOf(345);
//Double d3= num3; // casting not possible for wrapper class which could be possible for normal primitive
}
}
|
package com.prokarma.reference.architecture.di;
import com.prokarma.reference.architecture.feature.details.DetailsViewModel;
import com.prokarma.reference.architecture.feature.home.HomeViewModel;
import com.prokarma.reference.architecture.feature.search.list.ListViewModel;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class TestModule extends AppModule {
@Provides
@Singleton
HomeViewModel provideHomeViewModel() {
return new HomeViewModel();
}
@Provides
@Singleton
ListViewModel provideListViewModel() {
return new ListViewModel();
}
@Provides
@Singleton
DetailsViewModel provideDetailsViewModel() {
return new DetailsViewModel();
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.audio;
import android.os.Parcel;
import android.os.Parcelable.Creator;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.appbrand.compat.a.d;
import com.tencent.mm.plugin.appbrand.ipc.MainProcessTask;
import com.tencent.mm.plugin.appbrand.jsapi.e;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.sdk.platformtools.ah;
import java.util.HashMap;
import java.util.Map;
class JsApiStartPlayVoice$StartPlayVoice extends MainProcessTask {
public static final Creator<JsApiStartPlayVoice$StartPlayVoice> CREATOR = new 2();
public String bNH;
private e fFF;
private l fFa;
private int fFd;
public boolean fHX = false;
public String filePath;
public JsApiStartPlayVoice$StartPlayVoice(e eVar, l lVar, int i) {
this.fFF = eVar;
this.fFa = lVar;
this.fFd = i;
}
public JsApiStartPlayVoice$StartPlayVoice(Parcel parcel) {
g(parcel);
}
public final void aai() {
ah.A(new Runnable() {
public final void run() {
((d) g.l(d.class)).a(JsApiStartPlayVoice$StartPlayVoice.this.filePath, new 1(this), new 2(this));
}
});
}
public final void aaj() {
Map hashMap = new HashMap();
hashMap.put("localId", this.bNH);
this.fFa.E(this.fFd, this.fFF.f(this.fHX ? "fail" : "ok", hashMap));
JsApiStartPlayVoice.fIW = null;
}
public final void g(Parcel parcel) {
this.bNH = parcel.readString();
this.filePath = parcel.readString();
this.fHX = parcel.readByte() != (byte) 0;
}
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(this.bNH);
parcel.writeString(this.filePath);
parcel.writeByte(this.fHX ? (byte) 1 : (byte) 0);
}
}
|
package top.wangruns.nowcoder.sword2offer;
/**
*
* Randomly linked list
*
*/
public class RandomListNode {
int val;
RandomListNode next=null;
RandomListNode random=null;
RandomListNode(int val) {
this.val = val;
}
}
|
package com.smartwerkz.bytecode.tutorial2;
import static org.junit.Assert.assertEquals;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtNewMethod;
import org.junit.Test;
import com.smartwerkz.bytecode.controlflow.FrameExit;
import com.smartwerkz.bytecode.primitives.JavaInteger;
import com.smartwerkz.bytecode.primitives.JavaObject;
import com.smartwerkz.bytecode.vm.ByteArrayResourceLoader;
import com.smartwerkz.bytecode.vm.Classpath;
import com.smartwerkz.bytecode.vm.HostVMResourceLoader;
import com.smartwerkz.bytecode.vm.VirtualMachine;
/**
* This tutorial shows that with a bytecode interpreter, we can intercept at
* instruction level and stop an endlessly running program.
*
* @author mhaller
*/
public class Tutorial2Test {
@Test
public void testDetectEndlessLoops() throws Exception {
// Step 1: Dynamically generate a bogus class for demo purposes
ClassPool cp = new ClassPool(true);
// CtClass objClazz = cp.makeClass("java.lang.Object");
// objClazz.addConstructor(CtNewConstructor.defaultConstructor(objClazz));
CtClass cc = cp.makeClass("org.example.Blocking");
StringBuilder src = new StringBuilder();
src.append("public static void blocking() {");
src.append(" new java.util.concurrent.ArrayBlockingQueue(1).take();");
src.append("}");
cc.addMethod(CtNewMethod.make(src.toString(), cc));
byte[] b = cc.toBytecode();
// Step 2: Now let's start up the Virtual Java Virtual Machine.
VirtualMachine vm = new VirtualMachine();
vm.start();
vm.initSunJDK();
Classpath classpath = new Classpath();
classpath.addLoader(new ByteArrayResourceLoader(b));
classpath.addLoader(new HostVMResourceLoader());
vm.setClasspath(classpath);
// Step 3: Execute the endless loop
FrameExit result = vm.execute("org/example/Blocking", "blocking", new JavaObject[] { new JavaInteger(1),
new JavaInteger(2) });
assertEquals("", result.getResult().asStringValue());
}
}
|
/*
* Copyright (C) 2018 Ilya Lebedev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.ilya_lebedev.worldmeal.utilities;
import android.content.Context;
import io.github.ilya_lebedev.worldmeal.AppExecutors;
import io.github.ilya_lebedev.worldmeal.data.WorldMealRepository;
import io.github.ilya_lebedev.worldmeal.data.database.WorldMealDatabase;
import io.github.ilya_lebedev.worldmeal.data.network.WorldMealNetworkDataSource;
import io.github.ilya_lebedev.worldmeal.ui.classification.area.AreaViewModelFactory;
import io.github.ilya_lebedev.worldmeal.ui.classification.category.CategoryViewModelFactory;
import io.github.ilya_lebedev.worldmeal.ui.classification.ingredient.IngredientViewModelFactory;
import io.github.ilya_lebedev.worldmeal.ui.detail.MealViewModelFactory;
import io.github.ilya_lebedev.worldmeal.ui.list.area.AreaMealViewModelFactory;
import io.github.ilya_lebedev.worldmeal.ui.list.category.CategoryMealViewModelFactory;
import io.github.ilya_lebedev.worldmeal.ui.list.ingredient.IngredientMealViewModelFactory;
/**
* WorldMealInjectorUtils provides static methods to inject
* the various classes needed for WorldMeal app
*/
public class WorldMealInjectorUtils {
public static WorldMealRepository provideRepository(Context context) {
WorldMealDatabase database = WorldMealDatabase.getInstance(context.getApplicationContext());
AppExecutors appExecutors = AppExecutors.getInstance();
WorldMealNetworkDataSource networkDataSource =
WorldMealNetworkDataSource.getInstance(context.getApplicationContext(), appExecutors);
return WorldMealRepository.getInstance(database.worldMealDao(), networkDataSource, appExecutors);
}
public static WorldMealNetworkDataSource provideNetworkDataSource(Context context) {
// This call to provide repository is necessary if the app starts from a service - in this
// case the repository will not exist unless it is specifically created.
provideRepository(context.getApplicationContext());
AppExecutors appExecutors = AppExecutors.getInstance();
return WorldMealNetworkDataSource.getInstance(context.getApplicationContext(), appExecutors);
}
public static AreaViewModelFactory provideAreaViewModelFactory(Context context) {
WorldMealRepository repository = provideRepository(context);
return new AreaViewModelFactory(repository);
}
public static CategoryViewModelFactory provideCategoryViewModelFactory(Context context) {
WorldMealRepository repository = provideRepository(context);
return new CategoryViewModelFactory(repository);
}
public static IngredientViewModelFactory provideIngredientViewModelFactory(Context context) {
WorldMealRepository repository = provideRepository(context);
return new IngredientViewModelFactory(repository);
}
public static AreaMealViewModelFactory provideAreaMealViewModelFactory(Context context,
String areaName) {
WorldMealRepository repository = provideRepository(context);
return new AreaMealViewModelFactory(repository, areaName);
}
public static CategoryMealViewModelFactory provideCategoryMealViewModelFactory(Context context,
String categoryName) {
WorldMealRepository repository = provideRepository(context);
return new CategoryMealViewModelFactory(repository, categoryName);
}
public static IngredientMealViewModelFactory provideIngredientMealViewModelFactory
(Context context, String ingredientName) {
WorldMealRepository repository = provideRepository(context);
return new IngredientMealViewModelFactory(repository, ingredientName);
}
public static MealViewModelFactory provideMealViewModelFactory(Context context, long mealId) {
WorldMealRepository repository = provideRepository(context);
return new MealViewModelFactory(repository, mealId);
}
}
|
/*
* Copyright (c) 2010 Felipe Priuli
*
* This file is part of OpenSutils-Br4J.
*
* OpenSutils-Br4J is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, any later version.
*
* OpenSutils-Br4J is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opensutils;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import org.junit.Before;
import org.junit.Test;
public class CpfCnpjUtilsTest {
@Before
public void setUp() throws Exception {
}
@Test
public void testCnpjToStringLong() {
String resp = CpfCnpjUtils.cnpjToString(245526522L);
assertTrue( resp.equals("00000245526522") );
resp = CpfCnpjUtils.cnpjToString(526522L);
assertTrue( resp.equals("00000000526522") );
}
@Test
public void testCnpjToStringString() {
String resp = CpfCnpjUtils.cnpjToString("00245526522");
assertTrue( resp.equals("00000245526522") );
resp = CpfCnpjUtils.cnpjToString("526522");
assertTrue( resp.equals("00000000526522") );
}
@Test
public void testCpfToStringLong() {
String resp = CpfCnpjUtils.cpfToString(245526522L);
assertTrue( resp.equals("00245526522") );
resp = CpfCnpjUtils.cpfToString("554444");
assertTrue( resp.equals("00000554444") );
}
@Test
public void testCpfToStringString() {
String resp = CpfCnpjUtils.cpfToString("00245526522");
assertTrue( resp.equals("00245526522") );
resp = CpfCnpjUtils.cpfToString("554444");
assertTrue( resp.equals("00000554444") );
}
@Test
public void testCpfCnpjToStringLong() {
String resp = CpfCnpjUtils.cpfCnpjToString(245526522L);
assertTrue( resp.equals("00000245526522") );
resp = CpfCnpjUtils.cpfCnpjToString(689165234L);
assertTrue( resp.equals("00689165234") );
resp = CpfCnpjUtils.cpfCnpjToString(245526522L);
assertTrue( resp.equals("00000245526522") );
resp = CpfCnpjUtils.cpfCnpjToString(526522L);
assertTrue( resp.equals("00000000526522") );
}
@Test
public void testCpfCnpjToStringString() {
String resp = CpfCnpjUtils.cpfCnpjToString("00245526522");
assertTrue( resp.equals("00000245526522") );
resp = CpfCnpjUtils.cpfCnpjToString("689165234");
assertTrue( resp.equals("00689165234") );
resp = CpfCnpjUtils.cpfCnpjToString("00245526522");
assertTrue( resp.equals("00000245526522") );
resp = CpfCnpjUtils.cpfCnpjToString("526522");
assertTrue( resp.equals("00000000526522") );
}
@Test
public void testFormatCnpjString() {
String resp = CpfCnpjUtils.formatCnpj("00245526522");
assertTrue( resp.equals("00.000.245/5265-22") );
resp = CpfCnpjUtils.formatCnpj("23320245526522");
assertTrue( resp.equals("23.320.245/5265-22") );
resp = CpfCnpjUtils.formatCnpj("526522");
assertTrue( resp.equals("00.000.000/5265-22") );
resp = CpfCnpjUtils.formatCnpj("5222232222222222233333336522");
assertTrue( resp.equals("5222232222222222233333336522") );
}
@Test
public void testFormatCnpjLong() {
String resp = CpfCnpjUtils.formatCnpj(245526522L);
assertTrue( resp.equals("00.000.245/5265-22") );
resp = CpfCnpjUtils.formatCnpj(23320245526522L);
assertTrue( resp.equals("23.320.245/5265-22") );
resp = CpfCnpjUtils.formatCnpj(526522L);
assertTrue( resp.equals("00.000.000/5265-22") );
resp = CpfCnpjUtils.formatCnpj(322222222222333332L);
assertTrue( resp.equals("322222222222333332") );
}
@Test
public void testFormatCpfString() {
String resp = CpfCnpjUtils.formatCpf("00245526522");
assertTrue( resp.equals("002.455.265-22") );
resp = CpfCnpjUtils.formatCpf("554444");
assertTrue( resp.equals("000.005.544-44") );
resp = CpfCnpjUtils.formatCpf("124244");
assertTrue( resp.equals("000.001.242-44") );
resp = CpfCnpjUtils.formatCpf("5222232222222222233333336522");
assertTrue( resp.equals("5222232222222222233333336522") );
}
@Test
public void testFormatCpfLong() {
String resp = CpfCnpjUtils.formatCpf(245526522L);
assertTrue( resp.equals("002.455.265-22") );
resp = CpfCnpjUtils.formatCpf(554444L);
assertTrue( resp.equals("000.005.544-44") );
resp = CpfCnpjUtils.formatCpf(124244L);
assertTrue( resp.equals("000.001.242-44") );
resp = CpfCnpjUtils.formatCpf(52222322233332323L);
assertTrue( resp.equals("52222322233332323") );
}
@Test
public void testFormatCpfOrCnpj() {
String resp = CpfCnpjUtils.formatCpf(245526522L);
assertTrue( resp.equals("002.455.265-22") );
resp = CpfCnpjUtils.formatCpf(554444L);
assertTrue( resp.equals("000.005.544-44") );
resp = CpfCnpjUtils.formatCnpj(526522L);
assertTrue( resp.equals("00.000.000/5265-22") );
resp = CpfCnpjUtils.formatCnpj(322222222222333332L);
assertTrue( resp.equals("322222222222333332") );
resp = CpfCnpjUtils.formatCnpj(23320245526522L);
assertTrue( resp.equals("23.320.245/5265-22") );
}
@Test
public void testValidaCpfString() {
boolean resp = CpfCnpjUtils.isValidCpf("03359643895");//Cpf valido
if(resp == false)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpf("33596438950");//Cpf valido
if(resp == false)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpf("00689165234");//CPF valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpf("00000689165234");//Cpf invalido
if(resp == true)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpf("3359643895"); //Cpf valido
if(resp == false)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpf("33596438951");//Cpf invalido
if(resp == true)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpf("33blabla51");//Cpf invalido
if(resp == true)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpf("335964389500000");//Cpf invalido
if(resp == true)
fail("Resultado invalido para validacao de CPF");
}
@Test
public void testIsValidCpfLong() {
boolean resp = CpfCnpjUtils.isValidCpf(3359643895L);//Cpf valido
if(resp == false){
fail("Resultado invalido para validacao de CPF");
}
resp = CpfCnpjUtils.isValidCpf(33596438950L);//Cpf valido
if(resp == false){
fail("Resultado invalido para validacao de CPF");
}
resp = CpfCnpjUtils.isValidCpf(689165234L);//Cpf valido (00689165234)
if(resp == false){
fail("Resultado invalido para validacao de CPF");
}
resp = CpfCnpjUtils.isValidCpf(33596438950000000L);//Cpf invalido
if(resp == true){
fail("Resultado invalido para validacao de CPF");
}
resp = CpfCnpjUtils.isValidCpf(33596438925L);//Cpf invalido
if(resp == true){
fail("Resultado invalido para validacao de CPF");
}
}
@Test
public void testValidaCnpjString() {
boolean resp = CpfCnpjUtils.isValidCnpj("04312419000130");//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCnpj("04312419000131");//CNPJ invalido
if(resp == true)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCnpj("043blabla131");//CNPJ invalido
if(resp == true)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCnpj("4312419000130");//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCnpj("00000689165234");//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCnpj("335964389500000");//Cpf invalido
if(resp == true)
fail("Resultado invalido para validacao de CPF");
}
@Test
public void testIsValidCnpjLong() {
boolean resp = CpfCnpjUtils.isValidCnpj(689165234L);//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCnpj(4312419000130L);//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCnpj(4312419000131L);//CNPJ invalido
if(resp == true)
fail("Resultado invalido");
}
@Test
public void testIsValidCpfOrCnpjString() {
boolean resp = CpfCnpjUtils.isValidCpfOrCnpj("03359643895");//Cpf valido
if(resp == false)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpfOrCnpj("33596438950");//Cpf valido
if(resp == false)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpfOrCnpj("33596438959");//Cpf invalido
if(resp == true)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpfOrCnpj("3359643895");//Cpf valido
if(resp == false)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpfOrCnpj("33596438951");//Cpf invalido
if(resp == true)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpfOrCnpj("33blabla51");//Cpf invalido
if(resp == true)
fail("Resultado invalido para validacao de CPF");
resp = CpfCnpjUtils.isValidCpfOrCnpj("04312419000130");//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj("00000689165234");//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj("04312419000131");//CNPJ invalido
if(resp == true)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj("043blabla131");//CNPJ invalido
if(resp == true)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj("4312419000130");//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj("4312419000138");//CNPJ invalido
if(resp == true)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj("335964389500000");//Cpf invalido
if(resp == true)
fail("Resultado invalido para validacao de CPF");
}
@Test
public void testIsValidCpfOrCnpjLong() {
boolean resp = CpfCnpjUtils.isValidCpfOrCnpj(3359643895L);//Cpf valido
if(resp == false){
fail("Resultado invalido para validacao de CPF");
}
resp = CpfCnpjUtils.isValidCpfOrCnpj(33596438950L);//Cpf valido
if(resp == false){
fail("Resultado invalido para validacao de CPF");
}
resp = CpfCnpjUtils.isValidCpfOrCnpj(689165234L);//Cpf valido (00689165234)
if(resp == false){
fail("Resultado invalido para validacao de CPF");
}
resp = CpfCnpjUtils.isValidCpfOrCnpj(33596438925L);//Cpf invalido
if(resp == true){
fail("Resultado invalido para validacao de CPF");
}
resp = CpfCnpjUtils.isValidCpfOrCnpj(689165234L);//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj(4312419000130L);//CNPJ valido
if(resp == false)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj(4312419000131L);//CNPJ invalido
if(resp == true)
fail("Resultado invalido");
resp = CpfCnpjUtils.isValidCpfOrCnpj(4312419000130000000L);//CNPJ invalido
if(resp == true)
fail("Resultado invalido");
}
@Test
public void testCpfLongZerado() {
boolean resp = CpfCnpjUtils.isValidCpf(0L);
if(resp != false)
fail("CpfCnpj = 0 Resultado inválido");
}
@Test
public void testCpfStringZerado() {
boolean resp = CpfCnpjUtils.isValidCpf("00000000000");
if(resp != false)
fail("CpfCnpj = 00000000000Resultado inválido");
}
@Test
public void testCnpjLongZerado() {
boolean resp = CpfCnpjUtils.isValidCnpj(0L);
if(resp != false)
fail("CpfCnpj = 0 Resultado inválido");
}
@Test
public void testValidaCnpjStringQuandoValorZerado() {
boolean resp = CpfCnpjUtils.isValidCnpj("00000000000000");
if(resp != false)
fail("CpfCnpj = 00000000000 Resultado inválido");
}
@Test
public void testCpfCnpjZerado(){
boolean resp = CpfCnpjUtils.isValidCpfOrCnpj(0L);
if(resp != false)
fail("CpfCnpj = 00000000000 Resultado inválido");
}
}
|
package plp.expressions2;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import java.util.LinkedList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
import plp.expressions2.declaration.DecVariavel;
import plp.expressions2.expression.ExpDeclaracao;
import plp.expressions2.expression.ExpSoma;
import plp.expressions2.expression.Id;
import plp.expressions2.expression.ValorInteiro;
import plp.expressions2.memory.VariavelJaDeclaradaException;
import plp.expressions2.memory.VariavelNaoDeclaradaException;
public class ExemplosTest {
@Test(expected = VariavelJaDeclaradaException.class)
public void verificarVariavelJaDeclaradaException()
throws VariavelJaDeclaradaException, VariavelNaoDeclaradaException {
// let var x = 3, var x = 2 in x
Id idX = new Id("x");
Id idX2 = new Id("x");
DecVariavel decX1 = new DecVariavel(idX, new ValorInteiro(3));
DecVariavel decX2 = new DecVariavel(idX2, new ValorInteiro(2));
List<DecVariavel> list1 = new LinkedList<DecVariavel>();
list1.add(decX1);
list1.add(decX2);
ExpDeclaracao exp1 = new ExpDeclaracao(list1, idX);
Programa prg = new Programa(exp1);
assertThat(prg.checaTipo(), is(false));
prg.executar();
}
@Test(expected = VariavelNaoDeclaradaException.class)
public void verificarVariavelNaoDeclaradaException()
throws VariavelJaDeclaradaException, VariavelNaoDeclaradaException {
// let var x = 3 in y
Id idX = new Id("x");
Id idX2 = new Id("y");
DecVariavel decX1 = new DecVariavel(idX, new ValorInteiro(3));
List<DecVariavel> list1 = new LinkedList<DecVariavel>();
list1.add(decX1);
ExpDeclaracao exp1 = new ExpDeclaracao(list1, idX2);
Programa prg = new Programa(exp1);
assertThat(prg.checaTipo(), is(false));
prg.executar();
}
@Test
public void verificarEscopo() throws VariavelJaDeclaradaException,
VariavelNaoDeclaradaException {
// let var x = 3 in
// let var y = x + 1 in
// let var x = 5 in
// y
Id idX = new Id("x");
Id idY = new Id("y");
DecVariavel decX2 = new DecVariavel(idX, new ValorInteiro(5));
List<DecVariavel> list3 = new LinkedList<DecVariavel>();
list3.add(decX2);
ExpDeclaracao exp3 = new ExpDeclaracao(list3, idY);
DecVariavel decY = new DecVariavel(idY, new ExpSoma(idX,
new ValorInteiro(1)));
List<DecVariavel> list2 = new LinkedList<DecVariavel>();
list2.add(decY);
ExpDeclaracao exp2 = new ExpDeclaracao(list2, exp3);
DecVariavel decX1 = new DecVariavel(idX, new ValorInteiro(3));
List<DecVariavel> list1 = new LinkedList<DecVariavel>();
list1.add(decX1);
ExpDeclaracao exp1 = new ExpDeclaracao(list1, exp2);
Programa prg = new Programa(exp1);
assertThat(prg.checaTipo(), is(true));
assertThat(prg.executar().toString(), is("4"));
}
@Test
public void verificarDeclaracaoColateral()
throws VariavelJaDeclaradaException, VariavelNaoDeclaradaException {
// let var x = 3 in
// let var x = x + 1, var y = x in
// x + y
//
Id idX = new Id("x");
Id idY = new Id("y");
DecVariavel decVar1 = new DecVariavel(idX, new ValorInteiro(3));
DecVariavel decVar2 = new DecVariavel(idX, new ExpSoma(idX,
new ValorInteiro(1)));
DecVariavel decVar3 = new DecVariavel(idY, idX);
List<DecVariavel> list1 = new LinkedList<DecVariavel>();
list1.add(decVar2);
list1.add(decVar3);
ExpDeclaracao expDeclara2 = new ExpDeclaracao(list1, new ExpSoma(idX,
idY));
List<DecVariavel> list01 = new LinkedList<DecVariavel>();
list01.add(decVar1);
ExpDeclaracao expDeclara = new ExpDeclaracao(list01, expDeclara2);
Programa prg = new Programa(expDeclara);
assertThat(prg.checaTipo(), is(true));
assertThat(prg.executar().toString(), is("7"));
}
@Test
@Ignore(value = "So passa quando temos a avaliacao da declaracao de forma sequencial")
public void verificarDeclaracaoSequencial()
throws VariavelJaDeclaradaException, VariavelNaoDeclaradaException {
// let var x = 3 in
// let var x = x + 1, var y = x in
// x + y
//
Id idX = new Id("x");
Id idY = new Id("y");
DecVariavel decVar1 = new DecVariavel(idX, new ValorInteiro(3));
DecVariavel decVar2 = new DecVariavel(idX, new ExpSoma(idX,
new ValorInteiro(1)));
DecVariavel decVar3 = new DecVariavel(idY, idX);
List<DecVariavel> list1 = new LinkedList<DecVariavel>();
list1.add(decVar2);
list1.add(decVar3);
ExpDeclaracao expDeclara2 = new ExpDeclaracao(list1, new ExpSoma(idX,
idY));
List<DecVariavel> list01 = new LinkedList<DecVariavel>();
list01.add(decVar1);
ExpDeclaracao expDeclara = new ExpDeclaracao(list01, expDeclara2);
Programa prg = new Programa(expDeclara);
assertThat(prg.checaTipo(), is(true));
assertThat(prg.executar().toString(), is("8"));
}
}
|
package com.yaochen.address.dto;
public class SystemFunction {
private Integer FunctionOID;
private Integer UserOID;
private String UserName;
private Integer RoleOID;
private String FunctionName;
public Integer getFunctionOID() {
return FunctionOID;
}
public void setFunctionOID(Integer functionOID) {
FunctionOID = functionOID;
}
public Integer getUserOID() {
return UserOID;
}
public void setUserOID(Integer userOID) {
UserOID = userOID;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Integer getRoleOID() {
return RoleOID;
}
public void setRoleOID(Integer roleOID) {
RoleOID = roleOID;
}
public String getFunctionName() {
return FunctionName;
}
public void setFunctionName(String functionName) {
FunctionName = functionName;
}
}
|
package tij.concurrents.part7;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
public class Test1 {
public static void main(String[] args) {
System.out.println(UUID.randomUUID());
System.out.println(LocalDate.now());
System.out.println(LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")));
System.out.println(f());
}
static String f(){
int j = 1/0;
try{
int i = 0;
return "try";
}catch(Exception e){
return "caught";
} finally {
return "finnaly";
}
}
}
|
package com.rekoe.ioc.resource.imp;
import org.apache.poi.ss.usermodel.Workbook;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import com.rekoe.ioc.resource.IResourceLoader;
import com.rekoe.mvc.RkMvcContext;
import com.rekoe.mvc.config.GameConfig;
/**
* @author 科技㊣²º¹³
* Feb 18, 2013 6:09:05 PM
* http://www.rekoe.com
* QQ:5382211
*/
public class XlsResourceLoader implements IResourceLoader {
private final static Log log = Logs.get();
private Class<?> classType = Workbook.class;
public XlsResourceLoader(GameConfig config) {
}
@Override
public void load() {
Workbook item = getWorkbookByName("item.xls");
log.infof("xls resource load %s",item);
}
@Override
public void check() {
//throw new ResourceLoadException("测试一下哈 %s",123);
}
@SuppressWarnings("unchecked")
private <T>T getWorkbookByName(String name)
{
return (T)RkMvcContext.me().getResourceAttributeAs(classType, name);
}
}
|
package bootcamp.test;
import org.testng.Assert;
import org.testng.annotations.Test;
public class DependsOn {
@Test
public void a() {
System.out.println("running a");
}
@Test(dependsOnMethods = "a")
public void b() {
System.out.println("running b");
Assert.assertTrue(false);
}
@Test(dependsOnMethods = { "a", "b" })
public void c() {
System.out.println("running c");
}
}
|
package hackerrank;
import java.util.HashSet;
import java.util.Set;
/**
*
* @author Bohdan Skrypnyk
*/
public class SmallesPpositiveInteger {
public static int solution(int[] A) {
int num = A.length;
Set<Integer> arr = new HashSet<>();
for (Integer a : A) {
if (a > 0) {
arr.add(a);
}
}
int ret = 0;
for (int i = 1; i <= num + 1; i++) {
if (!arr.contains(i)) {
return i;
}
}
return ret;
}
public static void main(String args[]) {
int num[] = {1, 3, 6, 4, 1, 2}; // should return 5
System.out.println(solution(num));
int num1[] = {1, 2, 3}; // should return 4
System.out.println(solution(num1));
int num2[] = {-1, -3}; // should return 1
System.out.println(solution(num2));
}
}
|
package exceptions;
// Referenced classes of package exceptions:
// SyntacticException
public class MissingRightParenthesisException extends SyntacticException
{
public MissingRightParenthesisException()
{
this("Missing Right Parenthesis Exception.");
}
public MissingRightParenthesisException(String s)
{
super(s);
}
}
|
public class empl {
public static void disp()
{
System.out.println("am from disp");
}
}
|
package com.duanxr.yith.easy;
/**
* @author 段然 2021/3/8
*/
public class LongestUncommonSubsequenceI {
/**
* Given two strings a and b, find the length of the longest uncommon subsequence between them.
*
* A subsequence of a string s is a string that can be obtained after deleting any number of characters from s. For example, "abc" is a subsequence of "aebdc" because you can delete the underlined characters in "aebdc" to get "abc". Other subsequences of "aebdc" include "aebdc", "aeb", and "" (empty string).
*
* An uncommon subsequence between two strings is a string that is a subsequence of one but not the other.
*
* Return the length of the longest uncommon subsequence between a and b. If the longest uncommon subsequence doesn't exist, return -1.
*
*
*
* Example 1:
*
* Input: a = "aba", b = "cdc"
* Output: 3
* Explanation: One longest uncommon subsequence is "aba" because "aba" is a subsequence of "aba" but not "cdc".
* Note that "cdc" is also a longest uncommon subsequence.
* Example 2:
*
* Input: a = "aaa", b = "bbb"
* Output: 3
* Explanation: The longest uncommon subsequences are "aaa" and "bbb".
* Example 3:
*
* Input: a = "aaa", b = "aaa"
* Output: -1
* Explanation: Every subsequence of string a is also a subsequence of string b. Similarly, every subsequence of string b is also a subsequence of string a.
*
*
* Constraints:
*
* 1 <= a.length, b.length <= 100
* a and b consist of lower-case English letters.
*
* 给你两个字符串,请你从这两个字符串中找出最长的特殊序列。
*
* 「最长特殊序列」定义如下:该序列为某字符串独有的最长子序列(即不能是其他字符串的子序列)。
*
* 子序列 可以通过删去字符串中的某些字符实现,但不能改变剩余字符的相对顺序。空序列为所有字符串的子序列,任何字符串为其自身的子序列。
*
* 输入为两个字符串,输出最长特殊序列的长度。如果不存在,则返回 -1。
*
*
*
* 示例 1:
*
* 输入: "aba", "cdc"
* 输出: 3
* 解释: 最长特殊序列可为 "aba" (或 "cdc"),两者均为自身的子序列且不是对方的子序列。
* 示例 2:
*
* 输入:a = "aaa", b = "bbb"
* 输出:3
* 示例 3:
*
* 输入:a = "aaa", b = "aaa"
* 输出:-1
*
*
* 提示:
*
* 两个字符串长度均处于区间 [1 - 100] 。
* 字符串中的字符仅含有 'a'~'z' 。
*
*/
class Solution {
public int findLUSlength(String a, String b) {
if (a.equals(b)) {
return -1;
}
return Math.max(a.length(), b.length());
}
}
}
|
package com.itheima.redbaby.bean;
public class CartItem {
private Product product;
private String prodNum;
private boolean isCheck = true;
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public String getProdNum() {
return prodNum;
}
public void setProdNum(String prodNum) {
this.prodNum = prodNum;
}
}
|
package com.marchuck.androidinterview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.Log;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.marchuck.NetworkResponse;
import com.marchuck.androidinterview.di.HasComponent;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class MainActivity extends AppCompatActivity implements HasComponent<ProgressBar>, MainView {
public static final String TAG = MainActivity.class.getSimpleName();
@OnClick(R.id.activity_main_button_fetch) void buttonFetchClicked() {
presenter.requestData();
}
@BindView(R.id.activity_main_progressbar) ProgressBar progressbar;
@BindView(R.id.activity_main_textview_) TextView textview;
@Inject MainPresenter presenter;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
App.getApp(this).createActivityComponent(this).inject(this);
}
@Override public ProgressBar getComponent() {
return progressbar;
}
@Override public void onResponse(NetworkResponse response) {
Log.i(TAG, "onResponse: ");
textview.setText(Html.fromHtml(response.getResponse()));
}
@Override public void showError(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
|
package tech.adrianohrl.stile.control.bean;
import tech.adrianohrl.util.Calendars;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
*
* @author Adriano Henrique Rossette Leite (contact@adrianohrl.tech)
*/
public abstract class PeriodSearch implements Serializable {
private final Date maxDate = new Date();
protected Date startDate;
private Date startTime = new GregorianCalendar(0, 0, 0).getTime();
protected Date endDate;
private Date endTime = new GregorianCalendar(0, 0, 0, 23, 59, 59).getTime();
protected abstract void reset();
public abstract void search();
public Date getMaxDate() {
return maxDate;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Calendar getStart() {
return Calendars.combine(startDate, startTime);
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public Calendar getEnd() {
return Calendars.combine(endDate, endTime);
}
}
|
package Test;
import static org.junit.jupiter.api.Assertions.*;
import java.util.ArrayList;
import org.junit.jupiter.api.Test;
import BLL.RegisterNewBookCopyController;
import BLL.SearchBookController;
import DAL.BookInfo;
public class WhiteBoxNewCopyTest {
private ArrayList<BookInfo> book_lists = new ArrayList<>();
private void setBook_list (){
book_lists.clear();
BookInfo book = new BookInfo("NV0167", "To kill a mocking bird", "Harper Lee",
50000, 1, "9788373015470", "Borrowable", "Grand Central", "Available");
book_lists.add(book);
book = new BookInfo("NV0167", "To kill a mocking bird", "Harper Lee",
50000, 2, "9788373015470", "Borrowable", "Grand Central", "Available");
book_lists.add(book);
book = new BookInfo("NV0167", "To kill a mocking bird", "Harper Lee",
50000, 3, "9788373015470", "Borrowable", "Grand Central", "Available");
book_lists.add(book);
book = new BookInfo("NV0167", "To kill a mocking bird", "Harper Lee",
50000, 5, "9788373015470", "Borrowable", "Grand Central", "Available");
book_lists.add(book);
book = new BookInfo("NV0167", "To kill a mocking bird", "Harper Lee",
50000, 6, "9788373015470", "Borrowable", "Grand Central", "Available");
book_lists.add(book);
}
@Test
void getBookNull() {
SearchBookController controller = new SearchBookController();
assertEquals(null, controller.getBookInfo("qwerty", "title"));
}
@Test
void getBookList(){
SearchBookController controller = new SearchBookController();
setBook_list();
ArrayList<BookInfo> result = controller.getBookInfo("mock", "title");
for (int i = 0; i < 5; i++){
assertEquals(book_lists.get(i).getBookID(), result.get(i).getBookID());
assertEquals(book_lists.get(i).getAuthor(), result.get(i).getAuthor());
assertEquals(book_lists.get(i).getSequenceNumber(), result.get(i).getSequenceNumber());
assertEquals(book_lists.get(i).getISBN(), result.get(i).getISBN());
assertEquals(book_lists.get(i).getPrice(), result.get(i).getPrice(),0);
assertEquals(book_lists.get(i).getStatus(), result.get(i).getStatus());
assertEquals(book_lists.get(i).getType(), result.get(i).getType());
assertEquals(book_lists.get(i).getPublisher(), result.get(i).getPublisher());
assertEquals(book_lists.get(i).getTitle(), result.get(i).getTitle() );
}
}
@Test
void checkSuccessInformation() {
RegisterNewBookCopyController controller = new RegisterNewBookCopyController();
BookInfo book = new BookInfo();
book.setBookID("PH1000");
book.setSequenceNumber(10);
assertEquals(true, controller.checkNewCopyInformation(book.getBookID(),book.getSequenceNumber()));
}
@Test
void checkInformation1() {
RegisterNewBookCopyController controller = new RegisterNewBookCopyController();
BookInfo book = new BookInfo();
book.setBookID("PHYSICS01");
book.setSequenceNumber(10);
assertEquals(false, controller.checkNewCopyInformation(book.getBookID(),book.getSequenceNumber()));
}
@Test
void checkInformation2() {
RegisterNewBookCopyController controller = new RegisterNewBookCopyController();
BookInfo book = new BookInfo();
book.setBookID("PH1000");
book.setSequenceNumber(-5);
assertEquals(false, controller.checkNewCopyInformation(book.getBookID(),book.getSequenceNumber()));
}
}
|
package net.razorvine.pyro;
import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.SortedMap;
import java.util.TreeMap;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* Pyro wire protocol message.
*/
public class Message
{
private final static int CHECKSUM_MAGIC = 0x34E9;
public final static int HEADER_SIZE = 24;
public final static int MSG_CONNECT = 1;
public final static int MSG_CONNECTOK = 2;
public final static int MSG_CONNECTFAIL = 3;
public final static int MSG_INVOKE = 4;
public final static int MSG_RESULT = 5;
public final static int MSG_PING = 6;
public final static int FLAGS_EXCEPTION = 1<<0;
public final static int FLAGS_COMPRESSED = 1<<1;
public final static int FLAGS_ONEWAY = 1<<2;
public final static int FLAGS_BATCH = 1<<3;
public final static int FLAGS_META_ON_CONNECT = 1<<4;
public final static int SERIALIZER_SERPENT = 1;
public final static int SERIALIZER_JSON = 2;
public final static int SERIALIZER_MARSHAL = 3;
public final static int SERIALIZER_PICKLE = 4;
public int type;
public int flags;
public byte[] data;
public int data_size;
public int annotations_size;
public int serializer_id;
public int seq;
public SortedMap<String, byte[]> annotations;
/**
* construct a header-type message, without data and annotations payload.
*/
public Message(int msgType, int serializer_id, int flags, int seq)
{
this.type = msgType;
this.flags = flags;
this.seq = seq;
this.serializer_id = serializer_id;
}
/**
* construct a full wire message including data and annotations payloads.
*/
public Message(int msgType, byte[] databytes, int serializer_id, int flags, int seq, SortedMap<String, byte[]> annotations, byte[] hmac)
{
this(msgType, serializer_id, flags, seq);
this.data = databytes;
this.data_size = databytes.length;
this.annotations = annotations;
if(null==annotations)
this.annotations = new TreeMap<String, byte[]>();
if(hmac!=null)
this.annotations.put("HMAC", this.hmac(hmac)); // do this last because it hmacs the other annotation chunks
this.annotations_size = 0;
for(Entry<String, byte[]> a: this.annotations.entrySet())
this.annotations_size += a.getValue().length+6;
}
/**
* returns the hmac of the data and the annotation chunk values (except HMAC chunk itself)
*/
public byte[] hmac(byte[] key)
{
try {
Key secretKey = new SecretKeySpec(key, "HmacSHA1");
Mac hmac_algo = Mac.getInstance("HmacSHA1");
hmac_algo.init(secretKey);
hmac_algo.update(this.data);
for(Entry<String, byte[]> a: this.annotations.entrySet()) // this is in a fixed order because it is a SortedMap
{
if(!a.getKey().equals("HMAC"))
hmac_algo.update(a.getValue());
}
return hmac_algo.doFinal();
} catch (NoSuchAlgorithmException e) {
throw new PyroException("invalid hmac algorithm",e);
} catch (InvalidKeyException e) {
throw new PyroException("invalid hmac key",e);
}
}
/**
* creates a byte stream containing the header followed by annotations (if any) followed by the data
*/
public byte[] to_bytes()
{
byte[] header_bytes = get_header_bytes();
byte[] annotations_bytes = get_annotations_bytes();
byte[] result = new byte[header_bytes.length + annotations_bytes.length + data.length];
System.arraycopy(header_bytes, 0, result, 0, header_bytes.length);
System.arraycopy(annotations_bytes, 0, result, header_bytes.length, annotations_bytes.length);
System.arraycopy(data, 0, result, header_bytes.length+annotations_bytes.length, data.length);
return result;
}
public byte[] get_header_bytes()
{
int checksum = (type+Config.PROTOCOL_VERSION+data_size+annotations_size+serializer_id+flags+seq+CHECKSUM_MAGIC)&0xffff;
byte[] header = new byte[HEADER_SIZE];
/*
header format: '!4sHHHHiHHHH' (24 bytes)
4 id ('PYRO')
2 protocol version
2 message type
2 message flags
2 sequence number
4 data length
2 data serialization format (serializer id)
2 annotations length (total of all chunks, 0 if no annotation chunks present)
2 (reserved)
2 checksum
followed by annotations: 4 bytes type, annotations bytes.
*/
header[0]=(byte)'P';
header[1]=(byte)'Y';
header[2]=(byte)'R';
header[3]=(byte)'O';
header[4]=(byte) (Config.PROTOCOL_VERSION>>8);
header[5]=(byte) (Config.PROTOCOL_VERSION&0xff);
header[6]=(byte) (type>>8);
header[7]=(byte) (type&0xff);
header[8]=(byte) (flags>>8);
header[9]=(byte) (flags&0xff);
header[10]=(byte)(seq>>8);
header[11]=(byte)(seq&0xff);
header[12]=(byte)((data_size>>24)&0xff);
header[13]=(byte)((data_size>>16)&0xff);
header[14]=(byte)((data_size>>8)&0xff);
header[15]=(byte)(data_size&0xff);
header[16]=(byte)(serializer_id>>8);
header[17]=(byte)(serializer_id&0xff);
header[18]=(byte)((annotations_size>>8)&0xff);
header[19]=(byte)(annotations_size&0xff);
header[20]=0; // reserved
header[21]=0; // reserved
header[22]=(byte)((checksum>>8)&0xff);
header[23]=(byte)(checksum&0xff);
return header;
}
public byte[] get_annotations_bytes()
{
ArrayList<byte[]> chunks = new ArrayList<byte[]>();
int total_size = 0;
for(Entry<String, byte[]> ann: annotations.entrySet())
{
String key = ann.getKey();
byte[] value = ann.getValue();
if(key.length()!=4)
throw new IllegalArgumentException("annotation key must be length 4");
chunks.add(key.getBytes());
byte[] size_bytes = new byte[] { (byte)((value.length>>8)&0xff), (byte)(value.length&0xff) };
chunks.add(size_bytes);
chunks.add(value);
total_size += 4+2+value.length;
}
byte[] result = new byte[total_size];
int index=0;
for(byte[] chunk: chunks)
{
System.arraycopy(chunk, 0, result, index, chunk.length);
index+=chunk.length;
}
return result;
}
/**
* Parses a message header. Does not yet process the annotations chunks and message data.
*/
public static Message from_header(byte[] header)
{
if(header==null || header.length!=HEADER_SIZE)
throw new PyroException("header data size mismatch");
if(header[0]!='P'||header[1]!='Y'||header[2]!='R'||header[3]!='O')
throw new PyroException("invalid message");
int version = ((header[4]&0xff) << 8)|(header[5]&0xff);
if(version!=Config.PROTOCOL_VERSION)
throw new PyroException("invalid protocol version: "+version);
int msg_type = ((header[6]&0xff) << 8)|(header[7]&0xff);
int flags = ((header[8]&0xff) << 8)|(header[9]&0xff);
int seq = ((header[10]&0xff) << 8)|(header[11]&0xff);
int data_size=header[12]&0xff;
data_size<<=8;
data_size|=header[13]&0xff;
data_size<<=8;
data_size|=header[14]&0xff;
data_size<<=8;
data_size|=header[15]&0xff;
int serializer_id = ((header[16]&0xff) << 8)|(header[17]&0xff);
int annotations_size = ((header[18]&0xff) <<8)|(header[19]&0xff);
// byte 20 and 21 are reserved.
int checksum = ((header[22]&0xff) << 8)|(header[23]&0xff);
int actual_checksum = (msg_type+version+data_size+annotations_size+flags+serializer_id+seq+CHECKSUM_MAGIC)&0xffff;
if(checksum!=actual_checksum)
throw new PyroException("header checksum mismatch");
Message msg = new Message(msg_type, serializer_id, flags, seq);
msg.data_size = data_size;
msg.annotations_size = annotations_size;
return msg;
}
// Note: this 'chunked' way of sending is not used because it triggers Nagle's algorithm
// on some systems (linux). This causes massive delays, unless you change the socket option
// TCP_NODELAY to disable the algorithm. What also works, is sending all the message bytes
// in one go: connection.send(message.to_bytes())
// public void send(Stream connection)
// {
// // send the message as bytes over the connection
// IOUtil.send(connection, get_header_bytes());
// if(annotations_size>0)
// IOUtil.send(connection, get_annotations_bytes());
// IOUtil.send(connection, data);
// }
/**
* Receives a pyro message from a given connection.
* Accepts the given message types (None=any, or pass a sequence).
* Also reads annotation chunks and the actual payload data.
* Validates a HMAC chunk if present.
*/
public static Message recv(InputStream connection, int[] requiredMsgTypes, byte[] hmac) throws IOException
{
byte[] header_data = IOUtil.recv(connection, HEADER_SIZE);
Message msg = from_header(header_data);
if(requiredMsgTypes!=null)
{
boolean found=false;
for(int req: requiredMsgTypes)
{
if(req==msg.type)
{
found=true;
break;
}
}
if(!found)
throw new PyroException(String.format("invalid msg type %d received", msg.type));
}
byte[] annotations_data = null;
msg.annotations = new TreeMap<String, byte[]>();
if(msg.annotations_size>0)
{
// read annotation chunks
annotations_data = IOUtil.recv(connection, msg.annotations_size);
int i=0;
while(i<msg.annotations_size)
{
String anno = new String(annotations_data, i, 4);
int length = (annotations_data[i+4]<<8) | annotations_data[i+5];
byte[] annotations_bytes = new byte[length];
System.arraycopy(annotations_data, i+6, annotations_bytes, 0, length);
msg.annotations.put(anno, annotations_bytes);
i += 6+length;
}
}
// read data
msg.data = IOUtil.recv(connection, msg.data_size);
if(Config.MSG_TRACE_DIR!=null) {
TraceMessageRecv(msg.seq, header_data, annotations_data, msg.data);
}
if(msg.annotations.containsKey("HMAC") && hmac!=null)
{
if(!Arrays.equals(msg.annotations.get("HMAC"), msg.hmac(hmac)))
throw new PyroException("message hmac mismatch");
}
else if (msg.annotations.containsKey("HMAC") != (hmac!=null))
{
// Message contains hmac and local HMAC_KEY not set, or vice versa. This is not allowed.
throw new PyroException("hmac key config not symmetric");
}
return msg;
}
public static void TraceMessageSend(int sequenceNr, byte[] headerdata, byte[] annotations, byte[] data) throws IOException {
String filename=String.format("%s%s%05d-a-send-header.dat", Config.MSG_TRACE_DIR, File.separator, sequenceNr);
FileOutputStream fos=new FileOutputStream(filename);
fos.write(headerdata);
if(annotations!=null) fos.write(annotations);
fos.close();
filename=String.format("%s%s%05d-a-send-message.dat", Config.MSG_TRACE_DIR, File.separator, sequenceNr);
fos=new FileOutputStream(filename);
fos.write(data);
fos.close();
}
public static void TraceMessageRecv(int sequenceNr, byte[] headerdata, byte[] annotations, byte[] data) throws IOException {
String filename=String.format("%s%s%05d-b-recv-header.dat", Config.MSG_TRACE_DIR, File.separator, sequenceNr);
FileOutputStream fos=new FileOutputStream(filename);
fos.write(headerdata);
if(annotations!=null) fos.write(annotations);
fos.close();
filename=String.format("%s%s%05d-b-recv-message.dat", Config.MSG_TRACE_DIR, File.separator, sequenceNr);
fos=new FileOutputStream(filename);
fos.write(data);
fos.close();
}
}
|
package dao.stubs;
import models.BaseModel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class StubDao<T extends BaseModel> {
private int nextId;
private Map<Integer, T> map;
public StubDao() {
map = new HashMap<Integer, T>();
nextId = 1;
}
public void update(T t) {
throw new StubNotImplementedException();
}
public T create(T t) {
if (t.id == 0) {
t.id = nextId;
nextId += 1;
}
map.put(t.id, t);
return t;
}
public T findById(int id) {
return map.get(id);
}
public List<T> findAll() {
return new ArrayList<T>(map.values());
}
}
|
package com.microsilver.mrcard.basicservice.model;
import java.util.ArrayList;
import java.util.List;
public class FxAttributeExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public FxAttributeExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Integer value) {
addCriterion("id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Integer value) {
addCriterion("id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Integer value) {
addCriterion("id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Integer value) {
addCriterion("id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Integer value) {
addCriterion("id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Integer value) {
addCriterion("id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Integer> values) {
addCriterion("id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Integer> values) {
addCriterion("id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Integer value1, Integer value2) {
addCriterion("id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Integer value1, Integer value2) {
addCriterion("id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andNameIsNull() {
addCriterion("name is null");
return (Criteria) this;
}
public Criteria andNameIsNotNull() {
addCriterion("name is not null");
return (Criteria) this;
}
public Criteria andNameEqualTo(String value) {
addCriterion("name =", value, "name");
return (Criteria) this;
}
public Criteria andNameNotEqualTo(String value) {
addCriterion("name <>", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThan(String value) {
addCriterion("name >", value, "name");
return (Criteria) this;
}
public Criteria andNameGreaterThanOrEqualTo(String value) {
addCriterion("name >=", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThan(String value) {
addCriterion("name <", value, "name");
return (Criteria) this;
}
public Criteria andNameLessThanOrEqualTo(String value) {
addCriterion("name <=", value, "name");
return (Criteria) this;
}
public Criteria andNameLike(String value) {
addCriterion("name like", value, "name");
return (Criteria) this;
}
public Criteria andNameNotLike(String value) {
addCriterion("name not like", value, "name");
return (Criteria) this;
}
public Criteria andNameIn(List<String> values) {
addCriterion("name in", values, "name");
return (Criteria) this;
}
public Criteria andNameNotIn(List<String> values) {
addCriterion("name not in", values, "name");
return (Criteria) this;
}
public Criteria andNameBetween(String value1, String value2) {
addCriterion("name between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andNameNotBetween(String value1, String value2) {
addCriterion("name not between", value1, value2, "name");
return (Criteria) this;
}
public Criteria andTitleIsNull() {
addCriterion("title is null");
return (Criteria) this;
}
public Criteria andTitleIsNotNull() {
addCriterion("title is not null");
return (Criteria) this;
}
public Criteria andTitleEqualTo(String value) {
addCriterion("title =", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotEqualTo(String value) {
addCriterion("title <>", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThan(String value) {
addCriterion("title >", value, "title");
return (Criteria) this;
}
public Criteria andTitleGreaterThanOrEqualTo(String value) {
addCriterion("title >=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThan(String value) {
addCriterion("title <", value, "title");
return (Criteria) this;
}
public Criteria andTitleLessThanOrEqualTo(String value) {
addCriterion("title <=", value, "title");
return (Criteria) this;
}
public Criteria andTitleLike(String value) {
addCriterion("title like", value, "title");
return (Criteria) this;
}
public Criteria andTitleNotLike(String value) {
addCriterion("title not like", value, "title");
return (Criteria) this;
}
public Criteria andTitleIn(List<String> values) {
addCriterion("title in", values, "title");
return (Criteria) this;
}
public Criteria andTitleNotIn(List<String> values) {
addCriterion("title not in", values, "title");
return (Criteria) this;
}
public Criteria andTitleBetween(String value1, String value2) {
addCriterion("title between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andTitleNotBetween(String value1, String value2) {
addCriterion("title not between", value1, value2, "title");
return (Criteria) this;
}
public Criteria andFieldIsNull() {
addCriterion("field is null");
return (Criteria) this;
}
public Criteria andFieldIsNotNull() {
addCriterion("field is not null");
return (Criteria) this;
}
public Criteria andFieldEqualTo(String value) {
addCriterion("field =", value, "field");
return (Criteria) this;
}
public Criteria andFieldNotEqualTo(String value) {
addCriterion("field <>", value, "field");
return (Criteria) this;
}
public Criteria andFieldGreaterThan(String value) {
addCriterion("field >", value, "field");
return (Criteria) this;
}
public Criteria andFieldGreaterThanOrEqualTo(String value) {
addCriterion("field >=", value, "field");
return (Criteria) this;
}
public Criteria andFieldLessThan(String value) {
addCriterion("field <", value, "field");
return (Criteria) this;
}
public Criteria andFieldLessThanOrEqualTo(String value) {
addCriterion("field <=", value, "field");
return (Criteria) this;
}
public Criteria andFieldLike(String value) {
addCriterion("field like", value, "field");
return (Criteria) this;
}
public Criteria andFieldNotLike(String value) {
addCriterion("field not like", value, "field");
return (Criteria) this;
}
public Criteria andFieldIn(List<String> values) {
addCriterion("field in", values, "field");
return (Criteria) this;
}
public Criteria andFieldNotIn(List<String> values) {
addCriterion("field not in", values, "field");
return (Criteria) this;
}
public Criteria andFieldBetween(String value1, String value2) {
addCriterion("field between", value1, value2, "field");
return (Criteria) this;
}
public Criteria andFieldNotBetween(String value1, String value2) {
addCriterion("field not between", value1, value2, "field");
return (Criteria) this;
}
public Criteria andTypeIsNull() {
addCriterion("type is null");
return (Criteria) this;
}
public Criteria andTypeIsNotNull() {
addCriterion("type is not null");
return (Criteria) this;
}
public Criteria andTypeEqualTo(String value) {
addCriterion("type =", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotEqualTo(String value) {
addCriterion("type <>", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThan(String value) {
addCriterion("type >", value, "type");
return (Criteria) this;
}
public Criteria andTypeGreaterThanOrEqualTo(String value) {
addCriterion("type >=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThan(String value) {
addCriterion("type <", value, "type");
return (Criteria) this;
}
public Criteria andTypeLessThanOrEqualTo(String value) {
addCriterion("type <=", value, "type");
return (Criteria) this;
}
public Criteria andTypeLike(String value) {
addCriterion("type like", value, "type");
return (Criteria) this;
}
public Criteria andTypeNotLike(String value) {
addCriterion("type not like", value, "type");
return (Criteria) this;
}
public Criteria andTypeIn(List<String> values) {
addCriterion("type in", values, "type");
return (Criteria) this;
}
public Criteria andTypeNotIn(List<String> values) {
addCriterion("type not in", values, "type");
return (Criteria) this;
}
public Criteria andTypeBetween(String value1, String value2) {
addCriterion("type between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andTypeNotBetween(String value1, String value2) {
addCriterion("type not between", value1, value2, "type");
return (Criteria) this;
}
public Criteria andValueIsNull() {
addCriterion("value is null");
return (Criteria) this;
}
public Criteria andValueIsNotNull() {
addCriterion("value is not null");
return (Criteria) this;
}
public Criteria andValueEqualTo(String value) {
addCriterion("value =", value, "value");
return (Criteria) this;
}
public Criteria andValueNotEqualTo(String value) {
addCriterion("value <>", value, "value");
return (Criteria) this;
}
public Criteria andValueGreaterThan(String value) {
addCriterion("value >", value, "value");
return (Criteria) this;
}
public Criteria andValueGreaterThanOrEqualTo(String value) {
addCriterion("value >=", value, "value");
return (Criteria) this;
}
public Criteria andValueLessThan(String value) {
addCriterion("value <", value, "value");
return (Criteria) this;
}
public Criteria andValueLessThanOrEqualTo(String value) {
addCriterion("value <=", value, "value");
return (Criteria) this;
}
public Criteria andValueLike(String value) {
addCriterion("value like", value, "value");
return (Criteria) this;
}
public Criteria andValueNotLike(String value) {
addCriterion("value not like", value, "value");
return (Criteria) this;
}
public Criteria andValueIn(List<String> values) {
addCriterion("value in", values, "value");
return (Criteria) this;
}
public Criteria andValueNotIn(List<String> values) {
addCriterion("value not in", values, "value");
return (Criteria) this;
}
public Criteria andValueBetween(String value1, String value2) {
addCriterion("value between", value1, value2, "value");
return (Criteria) this;
}
public Criteria andValueNotBetween(String value1, String value2) {
addCriterion("value not between", value1, value2, "value");
return (Criteria) this;
}
public Criteria andRemarkIsNull() {
addCriterion("remark is null");
return (Criteria) this;
}
public Criteria andRemarkIsNotNull() {
addCriterion("remark is not null");
return (Criteria) this;
}
public Criteria andRemarkEqualTo(String value) {
addCriterion("remark =", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotEqualTo(String value) {
addCriterion("remark <>", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThan(String value) {
addCriterion("remark >", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkGreaterThanOrEqualTo(String value) {
addCriterion("remark >=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThan(String value) {
addCriterion("remark <", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLessThanOrEqualTo(String value) {
addCriterion("remark <=", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkLike(String value) {
addCriterion("remark like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotLike(String value) {
addCriterion("remark not like", value, "remark");
return (Criteria) this;
}
public Criteria andRemarkIn(List<String> values) {
addCriterion("remark in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotIn(List<String> values) {
addCriterion("remark not in", values, "remark");
return (Criteria) this;
}
public Criteria andRemarkBetween(String value1, String value2) {
addCriterion("remark between", value1, value2, "remark");
return (Criteria) this;
}
public Criteria andRemarkNotBetween(String value1, String value2) {
addCriterion("remark not between", value1, value2, "remark");
return (Criteria) this;
}
public Criteria andIsShowIsNull() {
addCriterion("is_show is null");
return (Criteria) this;
}
public Criteria andIsShowIsNotNull() {
addCriterion("is_show is not null");
return (Criteria) this;
}
public Criteria andIsShowEqualTo(Boolean value) {
addCriterion("is_show =", value, "isShow");
return (Criteria) this;
}
public Criteria andIsShowNotEqualTo(Boolean value) {
addCriterion("is_show <>", value, "isShow");
return (Criteria) this;
}
public Criteria andIsShowGreaterThan(Boolean value) {
addCriterion("is_show >", value, "isShow");
return (Criteria) this;
}
public Criteria andIsShowGreaterThanOrEqualTo(Boolean value) {
addCriterion("is_show >=", value, "isShow");
return (Criteria) this;
}
public Criteria andIsShowLessThan(Boolean value) {
addCriterion("is_show <", value, "isShow");
return (Criteria) this;
}
public Criteria andIsShowLessThanOrEqualTo(Boolean value) {
addCriterion("is_show <=", value, "isShow");
return (Criteria) this;
}
public Criteria andIsShowIn(List<Boolean> values) {
addCriterion("is_show in", values, "isShow");
return (Criteria) this;
}
public Criteria andIsShowNotIn(List<Boolean> values) {
addCriterion("is_show not in", values, "isShow");
return (Criteria) this;
}
public Criteria andIsShowBetween(Boolean value1, Boolean value2) {
addCriterion("is_show between", value1, value2, "isShow");
return (Criteria) this;
}
public Criteria andIsShowNotBetween(Boolean value1, Boolean value2) {
addCriterion("is_show not between", value1, value2, "isShow");
return (Criteria) this;
}
public Criteria andExtraIsNull() {
addCriterion("extra is null");
return (Criteria) this;
}
public Criteria andExtraIsNotNull() {
addCriterion("extra is not null");
return (Criteria) this;
}
public Criteria andExtraEqualTo(String value) {
addCriterion("extra =", value, "extra");
return (Criteria) this;
}
public Criteria andExtraNotEqualTo(String value) {
addCriterion("extra <>", value, "extra");
return (Criteria) this;
}
public Criteria andExtraGreaterThan(String value) {
addCriterion("extra >", value, "extra");
return (Criteria) this;
}
public Criteria andExtraGreaterThanOrEqualTo(String value) {
addCriterion("extra >=", value, "extra");
return (Criteria) this;
}
public Criteria andExtraLessThan(String value) {
addCriterion("extra <", value, "extra");
return (Criteria) this;
}
public Criteria andExtraLessThanOrEqualTo(String value) {
addCriterion("extra <=", value, "extra");
return (Criteria) this;
}
public Criteria andExtraLike(String value) {
addCriterion("extra like", value, "extra");
return (Criteria) this;
}
public Criteria andExtraNotLike(String value) {
addCriterion("extra not like", value, "extra");
return (Criteria) this;
}
public Criteria andExtraIn(List<String> values) {
addCriterion("extra in", values, "extra");
return (Criteria) this;
}
public Criteria andExtraNotIn(List<String> values) {
addCriterion("extra not in", values, "extra");
return (Criteria) this;
}
public Criteria andExtraBetween(String value1, String value2) {
addCriterion("extra between", value1, value2, "extra");
return (Criteria) this;
}
public Criteria andExtraNotBetween(String value1, String value2) {
addCriterion("extra not between", value1, value2, "extra");
return (Criteria) this;
}
public Criteria andModelIdIsNull() {
addCriterion("model_id is null");
return (Criteria) this;
}
public Criteria andModelIdIsNotNull() {
addCriterion("model_id is not null");
return (Criteria) this;
}
public Criteria andModelIdEqualTo(Integer value) {
addCriterion("model_id =", value, "modelId");
return (Criteria) this;
}
public Criteria andModelIdNotEqualTo(Integer value) {
addCriterion("model_id <>", value, "modelId");
return (Criteria) this;
}
public Criteria andModelIdGreaterThan(Integer value) {
addCriterion("model_id >", value, "modelId");
return (Criteria) this;
}
public Criteria andModelIdGreaterThanOrEqualTo(Integer value) {
addCriterion("model_id >=", value, "modelId");
return (Criteria) this;
}
public Criteria andModelIdLessThan(Integer value) {
addCriterion("model_id <", value, "modelId");
return (Criteria) this;
}
public Criteria andModelIdLessThanOrEqualTo(Integer value) {
addCriterion("model_id <=", value, "modelId");
return (Criteria) this;
}
public Criteria andModelIdIn(List<Integer> values) {
addCriterion("model_id in", values, "modelId");
return (Criteria) this;
}
public Criteria andModelIdNotIn(List<Integer> values) {
addCriterion("model_id not in", values, "modelId");
return (Criteria) this;
}
public Criteria andModelIdBetween(Integer value1, Integer value2) {
addCriterion("model_id between", value1, value2, "modelId");
return (Criteria) this;
}
public Criteria andModelIdNotBetween(Integer value1, Integer value2) {
addCriterion("model_id not between", value1, value2, "modelId");
return (Criteria) this;
}
public Criteria andIsMustIsNull() {
addCriterion("is_must is null");
return (Criteria) this;
}
public Criteria andIsMustIsNotNull() {
addCriterion("is_must is not null");
return (Criteria) this;
}
public Criteria andIsMustEqualTo(Boolean value) {
addCriterion("is_must =", value, "isMust");
return (Criteria) this;
}
public Criteria andIsMustNotEqualTo(Boolean value) {
addCriterion("is_must <>", value, "isMust");
return (Criteria) this;
}
public Criteria andIsMustGreaterThan(Boolean value) {
addCriterion("is_must >", value, "isMust");
return (Criteria) this;
}
public Criteria andIsMustGreaterThanOrEqualTo(Boolean value) {
addCriterion("is_must >=", value, "isMust");
return (Criteria) this;
}
public Criteria andIsMustLessThan(Boolean value) {
addCriterion("is_must <", value, "isMust");
return (Criteria) this;
}
public Criteria andIsMustLessThanOrEqualTo(Boolean value) {
addCriterion("is_must <=", value, "isMust");
return (Criteria) this;
}
public Criteria andIsMustIn(List<Boolean> values) {
addCriterion("is_must in", values, "isMust");
return (Criteria) this;
}
public Criteria andIsMustNotIn(List<Boolean> values) {
addCriterion("is_must not in", values, "isMust");
return (Criteria) this;
}
public Criteria andIsMustBetween(Boolean value1, Boolean value2) {
addCriterion("is_must between", value1, value2, "isMust");
return (Criteria) this;
}
public Criteria andIsMustNotBetween(Boolean value1, Boolean value2) {
addCriterion("is_must not between", value1, value2, "isMust");
return (Criteria) this;
}
public Criteria andStatusIsNull() {
addCriterion("status is null");
return (Criteria) this;
}
public Criteria andStatusIsNotNull() {
addCriterion("status is not null");
return (Criteria) this;
}
public Criteria andStatusEqualTo(Byte value) {
addCriterion("status =", value, "status");
return (Criteria) this;
}
public Criteria andStatusNotEqualTo(Byte value) {
addCriterion("status <>", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThan(Byte value) {
addCriterion("status >", value, "status");
return (Criteria) this;
}
public Criteria andStatusGreaterThanOrEqualTo(Byte value) {
addCriterion("status >=", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThan(Byte value) {
addCriterion("status <", value, "status");
return (Criteria) this;
}
public Criteria andStatusLessThanOrEqualTo(Byte value) {
addCriterion("status <=", value, "status");
return (Criteria) this;
}
public Criteria andStatusIn(List<Byte> values) {
addCriterion("status in", values, "status");
return (Criteria) this;
}
public Criteria andStatusNotIn(List<Byte> values) {
addCriterion("status not in", values, "status");
return (Criteria) this;
}
public Criteria andStatusBetween(Byte value1, Byte value2) {
addCriterion("status between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andStatusNotBetween(Byte value1, Byte value2) {
addCriterion("status not between", value1, value2, "status");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNull() {
addCriterion("update_time is null");
return (Criteria) this;
}
public Criteria andUpdateTimeIsNotNull() {
addCriterion("update_time is not null");
return (Criteria) this;
}
public Criteria andUpdateTimeEqualTo(Integer value) {
addCriterion("update_time =", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotEqualTo(Integer value) {
addCriterion("update_time <>", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThan(Integer value) {
addCriterion("update_time >", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeGreaterThanOrEqualTo(Integer value) {
addCriterion("update_time >=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThan(Integer value) {
addCriterion("update_time <", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeLessThanOrEqualTo(Integer value) {
addCriterion("update_time <=", value, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeIn(List<Integer> values) {
addCriterion("update_time in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotIn(List<Integer> values) {
addCriterion("update_time not in", values, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeBetween(Integer value1, Integer value2) {
addCriterion("update_time between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andUpdateTimeNotBetween(Integer value1, Integer value2) {
addCriterion("update_time not between", value1, value2, "updateTime");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Integer value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Integer value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Integer value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Integer value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Integer value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Integer value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Integer> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Integer> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Integer value1, Integer value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Integer value1, Integer value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andValidateRuleIsNull() {
addCriterion("validate_rule is null");
return (Criteria) this;
}
public Criteria andValidateRuleIsNotNull() {
addCriterion("validate_rule is not null");
return (Criteria) this;
}
public Criteria andValidateRuleEqualTo(String value) {
addCriterion("validate_rule =", value, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleNotEqualTo(String value) {
addCriterion("validate_rule <>", value, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleGreaterThan(String value) {
addCriterion("validate_rule >", value, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleGreaterThanOrEqualTo(String value) {
addCriterion("validate_rule >=", value, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleLessThan(String value) {
addCriterion("validate_rule <", value, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleLessThanOrEqualTo(String value) {
addCriterion("validate_rule <=", value, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleLike(String value) {
addCriterion("validate_rule like", value, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleNotLike(String value) {
addCriterion("validate_rule not like", value, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleIn(List<String> values) {
addCriterion("validate_rule in", values, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleNotIn(List<String> values) {
addCriterion("validate_rule not in", values, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleBetween(String value1, String value2) {
addCriterion("validate_rule between", value1, value2, "validateRule");
return (Criteria) this;
}
public Criteria andValidateRuleNotBetween(String value1, String value2) {
addCriterion("validate_rule not between", value1, value2, "validateRule");
return (Criteria) this;
}
public Criteria andValidateTimeIsNull() {
addCriterion("validate_time is null");
return (Criteria) this;
}
public Criteria andValidateTimeIsNotNull() {
addCriterion("validate_time is not null");
return (Criteria) this;
}
public Criteria andValidateTimeEqualTo(Boolean value) {
addCriterion("validate_time =", value, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeNotEqualTo(Boolean value) {
addCriterion("validate_time <>", value, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeGreaterThan(Boolean value) {
addCriterion("validate_time >", value, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeGreaterThanOrEqualTo(Boolean value) {
addCriterion("validate_time >=", value, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeLessThan(Boolean value) {
addCriterion("validate_time <", value, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeLessThanOrEqualTo(Boolean value) {
addCriterion("validate_time <=", value, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeIn(List<Boolean> values) {
addCriterion("validate_time in", values, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeNotIn(List<Boolean> values) {
addCriterion("validate_time not in", values, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeBetween(Boolean value1, Boolean value2) {
addCriterion("validate_time between", value1, value2, "validateTime");
return (Criteria) this;
}
public Criteria andValidateTimeNotBetween(Boolean value1, Boolean value2) {
addCriterion("validate_time not between", value1, value2, "validateTime");
return (Criteria) this;
}
public Criteria andErrorInfoIsNull() {
addCriterion("error_info is null");
return (Criteria) this;
}
public Criteria andErrorInfoIsNotNull() {
addCriterion("error_info is not null");
return (Criteria) this;
}
public Criteria andErrorInfoEqualTo(String value) {
addCriterion("error_info =", value, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoNotEqualTo(String value) {
addCriterion("error_info <>", value, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoGreaterThan(String value) {
addCriterion("error_info >", value, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoGreaterThanOrEqualTo(String value) {
addCriterion("error_info >=", value, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoLessThan(String value) {
addCriterion("error_info <", value, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoLessThanOrEqualTo(String value) {
addCriterion("error_info <=", value, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoLike(String value) {
addCriterion("error_info like", value, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoNotLike(String value) {
addCriterion("error_info not like", value, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoIn(List<String> values) {
addCriterion("error_info in", values, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoNotIn(List<String> values) {
addCriterion("error_info not in", values, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoBetween(String value1, String value2) {
addCriterion("error_info between", value1, value2, "errorInfo");
return (Criteria) this;
}
public Criteria andErrorInfoNotBetween(String value1, String value2) {
addCriterion("error_info not between", value1, value2, "errorInfo");
return (Criteria) this;
}
public Criteria andValidateTypeIsNull() {
addCriterion("validate_type is null");
return (Criteria) this;
}
public Criteria andValidateTypeIsNotNull() {
addCriterion("validate_type is not null");
return (Criteria) this;
}
public Criteria andValidateTypeEqualTo(String value) {
addCriterion("validate_type =", value, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeNotEqualTo(String value) {
addCriterion("validate_type <>", value, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeGreaterThan(String value) {
addCriterion("validate_type >", value, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeGreaterThanOrEqualTo(String value) {
addCriterion("validate_type >=", value, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeLessThan(String value) {
addCriterion("validate_type <", value, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeLessThanOrEqualTo(String value) {
addCriterion("validate_type <=", value, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeLike(String value) {
addCriterion("validate_type like", value, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeNotLike(String value) {
addCriterion("validate_type not like", value, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeIn(List<String> values) {
addCriterion("validate_type in", values, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeNotIn(List<String> values) {
addCriterion("validate_type not in", values, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeBetween(String value1, String value2) {
addCriterion("validate_type between", value1, value2, "validateType");
return (Criteria) this;
}
public Criteria andValidateTypeNotBetween(String value1, String value2) {
addCriterion("validate_type not between", value1, value2, "validateType");
return (Criteria) this;
}
public Criteria andAutoRuleIsNull() {
addCriterion("auto_rule is null");
return (Criteria) this;
}
public Criteria andAutoRuleIsNotNull() {
addCriterion("auto_rule is not null");
return (Criteria) this;
}
public Criteria andAutoRuleEqualTo(String value) {
addCriterion("auto_rule =", value, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleNotEqualTo(String value) {
addCriterion("auto_rule <>", value, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleGreaterThan(String value) {
addCriterion("auto_rule >", value, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleGreaterThanOrEqualTo(String value) {
addCriterion("auto_rule >=", value, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleLessThan(String value) {
addCriterion("auto_rule <", value, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleLessThanOrEqualTo(String value) {
addCriterion("auto_rule <=", value, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleLike(String value) {
addCriterion("auto_rule like", value, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleNotLike(String value) {
addCriterion("auto_rule not like", value, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleIn(List<String> values) {
addCriterion("auto_rule in", values, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleNotIn(List<String> values) {
addCriterion("auto_rule not in", values, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleBetween(String value1, String value2) {
addCriterion("auto_rule between", value1, value2, "autoRule");
return (Criteria) this;
}
public Criteria andAutoRuleNotBetween(String value1, String value2) {
addCriterion("auto_rule not between", value1, value2, "autoRule");
return (Criteria) this;
}
public Criteria andAutoTimeIsNull() {
addCriterion("auto_time is null");
return (Criteria) this;
}
public Criteria andAutoTimeIsNotNull() {
addCriterion("auto_time is not null");
return (Criteria) this;
}
public Criteria andAutoTimeEqualTo(Boolean value) {
addCriterion("auto_time =", value, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeNotEqualTo(Boolean value) {
addCriterion("auto_time <>", value, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeGreaterThan(Boolean value) {
addCriterion("auto_time >", value, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeGreaterThanOrEqualTo(Boolean value) {
addCriterion("auto_time >=", value, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeLessThan(Boolean value) {
addCriterion("auto_time <", value, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeLessThanOrEqualTo(Boolean value) {
addCriterion("auto_time <=", value, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeIn(List<Boolean> values) {
addCriterion("auto_time in", values, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeNotIn(List<Boolean> values) {
addCriterion("auto_time not in", values, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeBetween(Boolean value1, Boolean value2) {
addCriterion("auto_time between", value1, value2, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTimeNotBetween(Boolean value1, Boolean value2) {
addCriterion("auto_time not between", value1, value2, "autoTime");
return (Criteria) this;
}
public Criteria andAutoTypeIsNull() {
addCriterion("auto_type is null");
return (Criteria) this;
}
public Criteria andAutoTypeIsNotNull() {
addCriterion("auto_type is not null");
return (Criteria) this;
}
public Criteria andAutoTypeEqualTo(String value) {
addCriterion("auto_type =", value, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeNotEqualTo(String value) {
addCriterion("auto_type <>", value, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeGreaterThan(String value) {
addCriterion("auto_type >", value, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeGreaterThanOrEqualTo(String value) {
addCriterion("auto_type >=", value, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeLessThan(String value) {
addCriterion("auto_type <", value, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeLessThanOrEqualTo(String value) {
addCriterion("auto_type <=", value, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeLike(String value) {
addCriterion("auto_type like", value, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeNotLike(String value) {
addCriterion("auto_type not like", value, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeIn(List<String> values) {
addCriterion("auto_type in", values, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeNotIn(List<String> values) {
addCriterion("auto_type not in", values, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeBetween(String value1, String value2) {
addCriterion("auto_type between", value1, value2, "autoType");
return (Criteria) this;
}
public Criteria andAutoTypeNotBetween(String value1, String value2) {
addCriterion("auto_type not between", value1, value2, "autoType");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}
|
package com.commercetools.sunrise.common.contexts;
import com.neovisionaries.i18n.CountryCode;
import org.junit.Test;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import java.util.List;
import java.util.Locale;
import static java.util.Arrays.asList;
import static java.util.Locale.*;
import static org.assertj.core.api.Assertions.assertThat;
public class ProjectContextTest {
private static final List<Locale> AVAILABLE_LANGUAGES = asList(ENGLISH, CHINESE, GERMAN);
private static final List<CountryCode> AVAILABLE_COUNTRIES = asList(CountryCode.UK, CountryCode.CN, CountryCode.DE);
private static final CurrencyUnit GBP = Monetary.getCurrency("GBP");
private static final CurrencyUnit CNY = Monetary.getCurrency("CNY");
private static final CurrencyUnit EUR = Monetary.getCurrency("EUR");
private static final CurrencyUnit USD = Monetary.getCurrency("USD");
private static final List<CurrencyUnit> AVAILABLE_CURRENCIES = asList(GBP, CNY, EUR);
private static final ProjectContext PROJECT_CONTEXT = ProjectContextImpl.of(AVAILABLE_LANGUAGES, AVAILABLE_COUNTRIES, AVAILABLE_CURRENCIES);
@Test
public void worksWithLocales() throws Exception {
assertThat(PROJECT_CONTEXT.locales()).containsExactlyElementsOf(AVAILABLE_LANGUAGES);
assertThat(PROJECT_CONTEXT.defaultLocale()).isEqualTo(ENGLISH);
assertThat(PROJECT_CONTEXT.isLocaleSupported(GERMAN)).isTrue();
assertThat(PROJECT_CONTEXT.isLocaleSupported(FRENCH)).isFalse();
}
@Test
public void worksWithCountries() throws Exception {
assertThat(PROJECT_CONTEXT.countries()).containsExactlyElementsOf(AVAILABLE_COUNTRIES);
assertThat(PROJECT_CONTEXT.defaultCountry()).isEqualTo(CountryCode.UK);
assertThat(PROJECT_CONTEXT.isCountrySupported(CountryCode.DE)).isTrue();
assertThat(PROJECT_CONTEXT.isCountrySupported(CountryCode.FR)).isFalse();
}
@Test
public void worksWithCurrencies() throws Exception {
assertThat(PROJECT_CONTEXT.currencies()).containsExactlyElementsOf(AVAILABLE_CURRENCIES);
assertThat(PROJECT_CONTEXT.defaultCurrency()).isEqualTo(GBP);
assertThat(PROJECT_CONTEXT.isCurrencySupported(EUR)).isTrue();
assertThat(PROJECT_CONTEXT.isCurrencySupported(USD)).isFalse();
}
}
|
package graph;
import java.util.*;
public class Graph<T> {
protected Map<T, List<T>> adjacencyMap;
private T header;
public Graph(){
this.adjacencyMap = new HashMap<T, List<T>>();
}
public void addVertex(T value, List<T> adjacencies){
// Precondition --> adjacency list is valid
this.adjacencyMap.put(value, adjacencies);
this.header = value;
}
public void addVertex(T value){
addVertex(value, new ArrayList<T>());
}
public void addAdjacencies(T value, T[] adjacencies){
for (int i = 0; i < adjacencies.length; i++){
addAdjacency(value, adjacencies[i]);
}
//addAdjacency(value, adjacencies[0]);
}
public void addAdjacency(T value, T adjacency){
if (hasAdjacency(value, adjacency)) return;
if (adjacencyMap.containsKey(value) && adjacencyMap.containsKey(adjacency)) {
adjacencyMap.get(value).add(adjacency);
adjacencyMap.get(adjacency).add(value);
}
}
public boolean hasAdjacency(T value, T adjacency){
return adjacencyMap.get(value).contains(adjacency);
}
public List<T> getAdjacencies(T value){
if (adjacencyMap.containsKey(value)) {
return adjacencyMap.get(value);
} else return null;
}
public Set<T> getVertices(){
return adjacencyMap.keySet();
}
public int size(){
return adjacencyMap.size();
}
public String toString(){
String str = "";
for (T item: adjacencyMap.keySet()) {
str += "\n" + item + " " + adjacencyMap.get(item);
}
return str;
}
public void iBFTraversal(T value){
Queue<T> nodesToProcess = new ArrayDeque<>();
Set<T> visitedNodes = new HashSet<>();
nodesToProcess.add(value);
while (!nodesToProcess.isEmpty()){
T node = nodesToProcess.poll();
if (visitedNodes.contains(node)) continue;
visitedNodes.add(node);
System.out.println(node);
nodesToProcess.addAll(adjacencyMap.get(node));
}
}
}
|
package com.geekparkhub.core.application.analysis.pornhub;
/**
* Geek International Park | 极客国际公园
* GeekParkHub | 极客实验室
* Website | https://www.geekparkhub.com/
* Description | Open开放 · Creation创想 | OpenSource开放成就梦想 GeekParkHub共建前所未见
* HackerParkHub | 黑客公园枢纽
* Website | https://www.hackerparkhub.com/
* Description | 以无所畏惧的探索精神 开创未知技术与对技术的崇拜
* GeekDeveloper : JEEP-711
*
* @author system
* <p>
* PornhubActionETLUtil
* <p>
* 过滤不合法数据 | Filter illegal data
* 去除类别字段中的空格 | Remove spaces in the category field
* 将\t替换成&符 | Replace \H with ampersand
* <p>
*/
public class PornhubActionETLUtil {
/**
* Data cleaning Method
* 数据清洗方法
*
* @param ori
* @return
*/
public static String getETLString(String ori) {
/**
* 1.Get data and cut data
* 获取数据并切割数据
*/
String[] split = ori.split("\t");
/**
* 2.Filter illegal data
* 过滤不合法数据
*/
if (split.length < 9) {
return null;
}
/**
* 3.Remove spaces in the category field
* 去除类别字段中的空格
*/
split[3] = split[3].replace(" ", "");
/**
* 4.Replace \H with ampersand
* 将\t替换成&符
*/
StringBuffer sb = new StringBuffer();
for (int i = 0; i < split.length; i++) {
if (i < 9) {
// 如果字段长度相等,则不追加\t字符
if (i == split.length - 1) {
sb.append(split[i]);
} else {
// 如果字段长度小于9,则追加\t字符
sb.append(split[i] + "\t");
}
} else {
// 如果字段长度相等,则不追加字符
if (i == split.length - 1) {
sb.append(split[i]);
} else {
// 如果字段长度小于9,则追加&字符
sb.append(split[i] + "&");
}
}
}
return sb.toString();
}
}
|
package com.tencent.mm.cache;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.util.SparseArray;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.c;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.t.d;
import com.tencent.mm.t.d.a;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Stack;
public final class g implements d<d> {
private Stack<d> dai;
private Stack<d> daj;
public int dal;
public SparseArray<String> daq;
public HashMap<String, Bitmap> dar;
public final /* synthetic */ Object pop() {
if (this.dai.size() > 0) {
return (d) this.dai.pop();
}
x.e("MicroMsg.MosaicCache", "[pop]");
return null;
}
public final void onCreate() {
x.i("MicroMsg.MosaicCache", "[onCreate]");
this.dai = new Stack();
this.daq = new SparseArray();
this.dar = new HashMap();
}
public final void onDestroy() {
Iterator it;
if (this.dai != null) {
it = this.dai.iterator();
while (it.hasNext()) {
it.next();
d.clear();
}
this.dai.clear();
}
if (this.daj != null) {
it = this.daj.iterator();
while (it.hasNext()) {
it.next();
d.clear();
}
this.daj.clear();
}
this.daq.clear();
for (Entry value : this.dar.entrySet()) {
Bitmap bitmap = (Bitmap) value.getValue();
if (!(bitmap == null || bitmap.isRecycled())) {
bitmap.recycle();
}
}
this.dar.clear();
}
public final void aV(boolean z) {
x.i("MicroMsg.MosaicCache", "[onSave] size:%s", new Object[]{Integer.valueOf(this.dai.size())});
if (this.daj != null) {
this.daj.clear();
}
this.daj = (Stack) this.dai.clone();
if (z) {
this.dai.clear();
}
}
public final void yo() {
x.i("MicroMsg.MosaicCache", "[onRestore] size:%s", new Object[]{Integer.valueOf(this.dai.size())});
this.dai.clear();
if (this.daj != null) {
x.i("MicroMsg.MosaicCache", "[onRestore] %s", new Object[]{Integer.valueOf(this.daj.size())});
this.dai.addAll(this.daj);
}
}
public final void a(Canvas canvas, boolean z) {
if (!z) {
d dVar = (this.dai == null || this.dai.size() <= 0) ? null : (d) this.dai.peek();
if (dVar != null && dVar.bCF == a.doc) {
dVar.draw(canvas);
}
}
}
public final void c(Canvas canvas) {
Bitmap yv = yv();
if (yv != null && !yv.isRecycled()) {
canvas.drawBitmap(yv, 0.0f, 0.0f, null);
}
}
public final Bitmap yv() {
String str = (String) this.daq.get(aW(true));
if (bi.oW(str)) {
x.w("MicroMsg.MosaicCache", "[getCacheFromLocal] path is null");
return null;
}
Bitmap bitmap;
x.i("MicroMsg.MosaicCache", "[getCacheFromLocal] path:%s size:%s", new Object[]{str, Integer.valueOf(aW(true))});
if (this.dar.containsKey(str)) {
bitmap = (Bitmap) this.dar.get(str);
} else {
bitmap = null;
}
if (bitmap == null || bitmap.isRecycled()) {
x.i("MicroMsg.MosaicCache", "");
bitmap = c.Wb(str);
x.i("MicroMsg.MosaicCache", "[getCacheFromLocal] get from local!");
}
if (bitmap == null) {
x.e("MicroMsg.MosaicCache", "[getCacheFromLocal] null == bitmap path:%s", new Object[]{str});
return null;
}
Bitmap copy = bitmap.copy(Config.ARGB_8888, true);
bitmap.recycle();
return copy;
}
/* renamed from: a */
public final void add(d dVar) {
if (this.dai != null) {
this.dai.push(dVar);
}
}
public final int aW(boolean z) {
if (z) {
if (this.dai != null) {
return this.dai.size();
}
return 0;
} else if (this.daj != null) {
return this.daj.size();
} else {
return 0;
}
}
public final void vN() {
this.dal++;
}
}
|
package com.sergiienko.xrserver.web.resources;
import com.sergiienko.xrserver.AppState;
import com.sergiienko.xrserver.EMF;
import com.sergiienko.xrserver.abstracts.RatesParser;
import com.sergiienko.xrserver.models.CurrencyGroupModel;
import com.sergiienko.xrserver.models.GroupModel;
import com.sergiienko.xrserver.models.RateModel;
import com.sergiienko.xrserver.models.SourceModel;
import com.sergiienko.xrserver.rest.resources.RateResource;
import com.sergiienko.xrserver.rest.resources.ResRate;
import org.glassfish.jersey.process.internal.RequestScoped;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Set;
import java.util.HashMap;
/**
* Serves admin related REST API and HTML pages
*/
@RequestScoped
@Path("/")
public class AdminResource {
/**
* Link to the main admin web page
*/
private final String ADMIN_PAGE_LINK = "<a href=\"/admin\">Admin page</a>";
/**
* HTML header
*/
private final String HEADER = "<html><head>"
+ "<link rel=\"stylesheet\" type=\"text/css\" href=\"/admin/static/css/main.css\">"
+ "<script src=\"/admin/static/js/sorttable.js\"></script>"
+ "</head><body>";
/**
* HTML footer
*/
private final String FOOTER = "</body></html>";
/**
* Entity manager object, for working with DB
*/
private EntityManager entityManager = EMF.ENTITY_MANAGER_FACTORY.createEntityManager();
/**
* Logger object, for writing logs
*/
private Logger logger = LoggerFactory.getLogger(AdminResource.class);
/**
Default admin web page
@return default admin HTMl page
*/
@GET
@Produces(MediaType.TEXT_HTML)
public final String main() {
entityManager.getTransaction().begin();
List<SourceModel> sources = entityManager.createQuery("from SourceModel", SourceModel.class).getResultList();
List<GroupModel> groups = entityManager.createQuery("from GroupModel", GroupModel.class).getResultList();
List<CurrencyGroupModel> currencyGroups = entityManager.createQuery("from CurrencyGroupModel", CurrencyGroupModel.class).getResultList();
entityManager.getTransaction().commit();
entityManager.close();
StringBuilder strSources = new StringBuilder();
for (SourceModel source : sources) {
strSources.append("<tr><td><a href=\"sources/" + source.getId() + "\">" + source.getId() + "</a>"
+ "</td><td>" + source.getName()
+ "</td><td>" + source.getUrl()
+ "</td><td>" + source.getDescr()
+ "</td><td>" + source.getParserClassName()
+ "</td><td>" + source.getEnabled()
+ "</td></tr>");
}
StringBuilder strGroups = new StringBuilder();
for (GroupModel group : groups) {
strGroups.append("<tr><td><a href=\"groups/" + group.getId() + "\">" + group.getId() + "</a>"
+ "</td><td>" + group.getName()
+ "</td><td>" + group.getDescr()
+ "</td><td>" + Arrays.toString(group.getSources())
+ "</td><td>" + group.getDefaultGroup()
+ "</td></tr>");
}
StringBuilder strCurrencyGroups = new StringBuilder();
for (CurrencyGroupModel currencyGroup : currencyGroups) {
strCurrencyGroups.append("<tr><td><a href=\"currencygroups/" + currencyGroup.getId() + "\">"
+ currencyGroup.getId() + "</a>"
+ "</td><td>" + currencyGroup.getName()
+ "</td><td>" + currencyGroup.getDescr()
+ "</td><td>" + currencyGroup.getDefaultGroup()
+ "</td></tr>");
}
String newSources = "<form action=\"sources/new\" method=\"post\">"
+ "<input type=\"text\" placeholder=\"Name\" name=\"name\">"
+ "<input type=\"text\" placeholder=\"URL\" name=\"url\">"
+ "<input type=\"text\" placeholder=\"Description\" name=\"descr\">"
+ getParsersHTMLClassNames()
+ "<input type=\"submit\"></form>";
String newGroup = "<form action=\"groups/new\" method=\"post\">"
+ "<input type=\"text\" placeholder=\"Name\" name=\"name\">"
+ "<input type=\"text\" placeholder=\"Description\" name=\"descr\">"
+ "<input type=\"submit\"></form>";
String newCurrencyGroup = "<form action=\"currencygroups/new\" method=\"post\">"
+ "<input type=\"text\" placeholder=\"Name\" name=\"name\">"
+ "<input type=\"text\" placeholder=\"Description\" name=\"descr\">"
+ "<input type=\"submit\"></form>";
return HEADER
+ "<h3>Sources</h3><table style=\"width:100%\"><tr><th>ID</th><th>Name</th>"
+ "<th>URL</th><th>Description</th><th>Parser</th><th>Enabled</th></tr>"
+ strSources + "</table><br><hr><br>"
+ "<h3>Add new source</h3><strong>all fields are mandatory</strong>"
+ newSources + "<br><hr><br>"
+ "<h3>Groups</h3><table style=\"width:100%\"><tr><th>ID</th><th>Name</th><th>Description</th><th>Sources</th><th>Default</th></tr>"
+ strGroups + "</table><br><hr><br>"
+ "<h3>Add new group</h3><strong>all fields are mandatory</strong>"
+ newGroup
+ "<br><hr><br>"
+ "<h3>Currency Groups</h3><table style=\"width:100%\"><tr><th>ID</th><th>Name</th><th>Description</th><th>Default</th></tr>"
+ strCurrencyGroups
+ "</table><br><hr><br>"
+ "<h3>Add new currency group</h3><strong>all fields are mandatory</strong>"
+ newCurrencyGroup + "<br><hr><br>"
+ FOOTER;
}
/**
Returns known parsers' full class names in HTML string
@return a select HTML element with list of known sources' parsers
*/
private String getParsersHTMLClassNames() {
StringBuilder parsers = new StringBuilder("<select name=\"parserclass\" id=\"parserclass\">");
Reflections reflections = new Reflections("com.sergiienko.xrserver.parsers");
Set<Class<? extends RatesParser>> allClasses = reflections.getSubTypesOf(RatesParser.class);
for (Class c : allClasses) {
String className = c.getName();
parsers.append("<option value=\"" + className + "\">" + className + "</option>");
}
parsers.append("</select>");
return parsers.toString();
}
/**
Show group edit page
@param groupid ID of the group
@return a web page for editing the group's properties
*/
@GET
@Path("/groups/{groupid}")
@Produces(MediaType.TEXT_HTML)
public final String editGroup(@PathParam("groupid") final Integer groupid) {
StringBuilder sb = new StringBuilder(HEADER);
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("from GroupModel where id=:arg1", GroupModel.class);
q.setParameter("arg1", groupid);
GroupModel group = (GroupModel) q.getSingleResult();
List<SourceModel> sources = entityManager.createQuery("from SourceModel", SourceModel.class).getResultList();
entityManager.getTransaction().commit();
entityManager.close();
sb.append("<form action=\"" + groupid + "\" method=\"post\">");
sb.append("Name <input name=\"name\" value=\"" + group.getName() + "\"><br>");
sb.append("Description <input name=\"descr\" value=\"" + group.getDescr() + "\"><br>");
sb.append("Default group <input type=\"checkbox\" name=\"default\" " + (group.getDefaultGroup() ? "checked=\"true\"><br>" : "><br>"));
sb.append("Sources in group<br>");
List<Integer> l = Arrays.asList(group.getSources());
for (SourceModel source: sources) {
String checked = l.contains(source.getId()) ? " checked=\"true\" " : "";
sb.append("<input type=\"checkbox\" name=\"source\" " + checked + " value=\"" + source.getId() + "\">" + source.getName() + "<br>");
}
sb.append("<input type=\"submit\"></form>");
sb.append("<br><a href=\"" + groupid + "/remove\">Delete group</a></br>");
return sb.toString();
}
/**
Remove group from DB
@param groupid ID of the group
@return a link on the admin web page
*/
@GET
@Path("/groups/{groupid}/remove")
@Produces(MediaType.TEXT_HTML)
public final String removeGroup(@PathParam("groupid") final Integer groupid) {
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("delete GroupModel where id=:arg1");
q.setParameter("arg1", groupid);
q.executeUpdate();
entityManager.getTransaction().commit();
entityManager.close();
logger.info("Group " + groupid + " has been removed");
return "<br>Return to " + ADMIN_PAGE_LINK;
}
/**
Remove source from DB
@param sourceid ID of the source
@return a link to the admin web page
*/
@GET
@Path("/sources/{sourceid}/remove")
@Produces(MediaType.TEXT_HTML)
public final String removeSource(@PathParam("sourceid") final Integer sourceid) {
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("from RateModel where source=:arg1", RateModel.class);
q.setParameter("arg1", sourceid);
q.setMaxResults(1);
List<Object> l = q.getResultList();
String res;
if (0 == l.size()) {
q = entityManager.createQuery("delete SourceModel where id=:arg1");
q.setParameter("arg1", sourceid);
q.executeUpdate();
res = "Success.";
} else {
res = "We have rates from this source in DB. Cannot be removed.";
}
entityManager.getTransaction().commit();
entityManager.close();
logger.info("Source " + sourceid + " has been removed");
return res + "<br>Return to " + ADMIN_PAGE_LINK;
}
/**
Show source edit page
@param sourceid ID of the source
@return web page for editing the surce's properties
*/
@GET
@Path("/sources/{sourceid}")
@Produces(MediaType.TEXT_HTML)
public final String editSource(@PathParam("sourceid") final Integer sourceid) {
StringBuilder sb = new StringBuilder(HEADER);
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("from SourceModel where id=:arg1", SourceModel.class);
q.setParameter("arg1", sourceid);
SourceModel source = (SourceModel) q.getSingleResult();
entityManager.getTransaction().commit();
entityManager.close();
sb.append("<form action=\"" + sourceid + "\" method=\"post\">");
sb.append("Name <input name=\"name\" value=\"" + source.getName() + "\"><br>");
sb.append("Description <input name=\"descr\" value=\"" + source.getDescr() + "\"><br>");
sb.append("URL <input name=\"url\" value=\"" + source.getUrl() + "\"><br>");
sb.append("Parser " + getParsersHTMLClassNames() + "<br>");
sb.append("Enabled <input type=\"checkbox\" name=\"enabled\" " + (source.getEnabled() ? "checked=\"true\"><br>" : "><br>"));
sb.append("Sources in group<br>");
sb.append("<input type=\"submit\"></form>");
sb.append("<br><a href=\"" + sourceid + "/remove\">Delete source</a> - can be deleted if no rates from this source are in DB</br>");
sb.append("<script>var el = document.getElementById(\'parserclass\');\nel.value=\""
+ source.getParserClassName() + "\"</script>");
return sb.toString();
}
/**
Persist group after edit
@param name name of the group
@param descr description of the group
@param dflt is the group default
@param groupid ID of the group
@param sources list of sources arranged in this group
@return a link on the admin web page
*/
@POST
@Path("/groups/{groupid}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public final String saveGroup(@PathParam("groupid") final Integer groupid,
@FormParam("source") final List<Integer> sources,
@FormParam("name") final String name,
@FormParam("descr") final String descr,
@FormParam("default") final Boolean dflt) {
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("from GroupModel where id=:arg1", GroupModel.class);
q.setParameter("arg1", groupid);
GroupModel group = (GroupModel) q.getSingleResult();
group.setSources(sources.toArray(new Integer[sources.size()]));
group.setDescr(descr);
group.setName(name);
if (null != dflt) {
entityManager.createQuery("UPDATE GroupModel SET dflt=:state WHERE id<>:groupid").
setParameter("state", false).setParameter("groupid", groupid).
executeUpdate();
}
group.setDefaultGroup(null == dflt ? false : true);
entityManager.merge(group);
entityManager.getTransaction().commit();
entityManager.close();
logger.info("Group " + groupid + "has been edited");
return "Success. Return to " + ADMIN_PAGE_LINK;
}
/**
Persist source after edit
@param groupid ID of the source
@param enabled is the source enabled
@param descr description of the source
@param name name of the source
@param parser class name of the parser which should serve this source
@param url URL of the source
@return a link to the admin web page
*/
@POST
@Path("/sources/{sourceid}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public final String saveSource(@PathParam("sourceid") final Integer groupid,
@FormParam("url") final String url,
@FormParam("name") final String name,
@FormParam("descr") final String descr,
@FormParam("parserclass") final String parser,
@FormParam("enabled") final Boolean enabled) {
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("from SourceModel where id=:arg1", SourceModel.class);
q.setParameter("arg1", groupid);
SourceModel source = (SourceModel) q.getSingleResult();
source.setParserClassName(parser);
source.setUrl(url);
source.setDescr(descr);
source.setName(name);
source.setEnabled((null == enabled ? false : true));
entityManager.merge(source);
entityManager.getTransaction().commit();
entityManager.close();
logger.info("Source " + groupid + "has been edited");
return "Success. Return to " + ADMIN_PAGE_LINK;
}
/**
Create new source
@param name name of the source
@param url URL of the source
@param descr description of the source
@param parserclass class name of the parser which serves this source
@return a link to the man admin web page
*/
@POST
@Path("/sources/new")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public final String createSource(@FormParam("name") final String name,
@FormParam("url") final String url,
@FormParam("descr") final String descr,
@FormParam("parserclass") final String parserclass) {
if (null == name || 0 == name.length()
|| null == url || 0 == url.length()
|| null == descr || 0 == descr.length()
|| null == parserclass || 0 == parserclass.length()) {
return "All form fields are mandatory. Return to " + ADMIN_PAGE_LINK;
}
SourceModel newsource = new SourceModel();
newsource.setName(name);
newsource.setDescr(descr);
newsource.setEnabled(false);
newsource.setParserClassName(parserclass);
newsource.setUrl(url);
entityManager.getTransaction().begin();
entityManager.persist(newsource);
entityManager.getTransaction().commit();
entityManager.close();
logger.info("New source added: " + url);
return "Success. Return to " + ADMIN_PAGE_LINK;
}
/**
Create new group
@param name name of the group
@param descr description of the group
@return a link to the main admin page
*/
@POST
@Path("/groups/new")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public final String createGroup(@FormParam("name") final String name, @FormParam("descr") final String descr) {
if (null == name || 0 == name.length() || null == descr || 0 == descr.length()) {
return "All form fields are mandatory. Return to " + ADMIN_PAGE_LINK;
}
GroupModel newgroup = new GroupModel();
newgroup.setName(name);
newgroup.setDescr(descr);
newgroup.setDefaultGroup(false);
newgroup.setSources(new Integer[]{});
entityManager.getTransaction().begin();
entityManager.persist(newgroup);
entityManager.getTransaction().commit();
entityManager.close();
logger.info("New group added: " + name);
return "Success. Return to " + ADMIN_PAGE_LINK;
}
/**
Get application state
@return last state of enabled sources, application/json
*/
@GET
@Path("/rest/state")
@Produces(MediaType.APPLICATION_JSON)
public final String getState() {
StringBuilder sb = new StringBuilder("{state: {sources: {");
Map<Integer, Boolean> state = AppState.getState();
int i = 0;
for (Map.Entry<Integer, Boolean> entry : state.entrySet()) {
if (i > 0) {
sb.append(",");
} else {
i++;
}
sb.append("\"" + entry.getKey() + "\":" + (entry.getValue() ? "\"OK\"" : "\"ERROR\""));
}
sb.append("}}}");
return sb.toString();
}
/**
Get state for specific source
@param sourceid ID of the source we want get state of
@return last state of the source, text/html
*/
@GET
@Path("/rest/state/{sourceid}")
@Produces(MediaType.TEXT_HTML)
public final String getStateID(@PathParam("sourceid") final Integer sourceid) {
StringBuilder sb = new StringBuilder("<html><body>");
Map<Integer, Boolean> state = AppState.getState();
Boolean sourceState = state.get(sourceid);
if (null == sourceState) {
sb.append("NO STATE");
} else {
sb.append(sourceState ? "OK" : "ERROR");
}
sb.append("</body></html>");
return sb.toString();
}
/**
Show currency group edit page
@param groupid ID of the currency group
@return a web page for editing the group's properties
*/
@GET
@Path("/currencygroups/{groupid}")
@Produces(MediaType.TEXT_HTML)
public final String editCurrencyGroup(@PathParam("groupid") final Integer groupid) {
StringBuilder sb = new StringBuilder(HEADER);
RateResource rateRes = new RateResource();
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("from CurrencyGroupModel where id=:arg1", CurrencyGroupModel.class);
q.setParameter("arg1", groupid);
CurrencyGroupModel group = (CurrencyGroupModel) q.getSingleResult();
List<ResRate> ratesList = rateRes.getAllLiveRates();
Map<Integer, SourceModel> allSources = getAllSources();
entityManager.getTransaction().commit();
entityManager.close();
sb.append("<form action=\"" + groupid + "\" method=\"post\">");
sb.append("Name <input name=\"name\" value=\"" + group.getName() + "\"><br>");
sb.append("Description <input name=\"descr\" value=\"" + group.getDescr() + "\"><br>");
sb.append("Default group <input type=\"checkbox\" name=\"default\" " + (group.getDefaultGroup() ? "checked=\"true\"><br>" : "><br>"));
sb.append("Sources in group<br>");
Integer[] groupSources = group.getSources();
String[] groupCurrencies = group.getCurrencies();
Map<Integer, List<ResRate>> ratesMap = new HashMap<>();
for (ResRate r : ratesList) {
if (null == ratesMap.get(r.getSource())) {
ratesMap.put(r.getSource(), new ArrayList<ResRate>());
}
ratesMap.get(r.getSource()).add(r);
}
sb.append("<table class=\"sortable\"><tr><th></th><th>Source ID</th><th>Source desc</th><th>Currency name</th></tr>");
for (Map.Entry<Integer, List<ResRate>> entry : ratesMap.entrySet()) {
Integer sourceID = entry.getKey();
for (ResRate rate : entry.getValue()) {
String currencyName = rate.getName();
String checked = "";
for (int i = 0; i < groupSources.length; i++) {
if (groupSources[i].equals(sourceID) && currencyName.equals(groupCurrencies[i])) {
checked = " checked=\"true\" ";
break;
}
}
String checkboxValue = sourceID + ":" + currencyName;
sb.append("<tr><td><input type=\"checkbox\" name=\"source\" " + checked + " value=\"" + checkboxValue + "\"></td>"
+ "<td>" + sourceID + "</td>"
+ "<td>" + allSources.get(sourceID).getDescr() + "</td>"
+ "<td>" + currencyName + "</td></tr>");
}
}
sb.append("</table><input type=\"submit\"></form>");
sb.append("<br><a href=\"" + groupid + "/remove\">Delete group</a></br>");
return sb.toString();
}
/**
Persist currency group after edit
@param name name of the group
@param descr description of the group
@param dflt is the group default
@param groupid ID of the group
@param sources list of pairs 'source:value' arranged in this group
@return a link on the admin web page
*/
@POST
@Path("/currencygroups/{groupid}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public final String saveCurrencyGroup(@PathParam("groupid") final Integer groupid,
@FormParam("source") final List<String> sources,
@FormParam("name") final String name,
@FormParam("descr") final String descr,
@FormParam("default") final Boolean dflt) {
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("from CurrencyGroupModel where id=:arg1", CurrencyGroupModel.class);
q.setParameter("arg1", groupid);
CurrencyGroupModel group = (CurrencyGroupModel) q.getSingleResult();
List<Integer> formSources = new ArrayList<>();
List<String> formCurrencies = new ArrayList<>();
for (String s : sources) {
String[] parts = s.split(":");
formSources.add(Integer.parseInt(parts[0]));
formCurrencies.add(parts[1]);
}
group.setSources(formSources.toArray(new Integer[formSources.size()]));
group.setCurrencies(formCurrencies.toArray(new String[formCurrencies.size()]));
group.setDescr(descr);
group.setName(name);
if (null != dflt) {
entityManager.createQuery("UPDATE CurrencyGroupModel SET dflt=:state WHERE id<>:groupid").
setParameter("state", false).setParameter("groupid", groupid).
executeUpdate();
}
group.setDefaultGroup(null == dflt ? false : true);
entityManager.merge(group);
entityManager.getTransaction().commit();
entityManager.close();
logger.info("Currency group " + groupid + "has been edited");
return "Success. Return to " + ADMIN_PAGE_LINK;
}
/**
Remove currency group from DB
@param groupid ID of the group
@return a link on the admin web page
*/
@GET
@Path("/currencygroups/{groupid}/remove")
@Produces(MediaType.TEXT_HTML)
public final String removeCurrencyGroup(@PathParam("groupid") final Integer groupid) {
entityManager.getTransaction().begin();
Query q = entityManager.createQuery("delete CurrencyGroupModel where id=:arg1");
q.setParameter("arg1", groupid);
q.executeUpdate();
entityManager.getTransaction().commit();
entityManager.close();
logger.info("Currency group " + groupid + " has been removed");
return "<br>Return to " + ADMIN_PAGE_LINK;
}
/**
Create empty currency group
@param name name of the group
@param descr description of the group
@return a link to the main admin page
*/
@POST
@Path("/currencygroups/new")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public final String createCurrencyGroup(@FormParam("name") final String name,
@FormParam("descr") final String descr) {
if (null == name || 0 == name.length() || null == descr || 0 == descr.length()) {
return "All form fields are mandatory. Return to " + ADMIN_PAGE_LINK;
}
CurrencyGroupModel newgroup = new CurrencyGroupModel();
newgroup.setName(name);
newgroup.setDescr(descr);
newgroup.setDefaultGroup(false);
newgroup.setSources(new Integer[]{});
newgroup.setCurrencies(new String[]{});
entityManager.getTransaction().begin();
entityManager.persist(newgroup);
entityManager.getTransaction().commit();
entityManager.close();
logger.info("New currency group added: " + name);
return "Success. Return to " + ADMIN_PAGE_LINK;
}
private Map<Integer, SourceModel> getAllSources() {
List<SourceModel> sources = entityManager.createQuery("from SourceModel").getResultList();
Map<Integer, SourceModel> m = new HashMap<>();
for (SourceModel source : sources) {
m.put(source.getId(),source);
}
return m;
}
}
|
package BOJ;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Q2947 {
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static int[] arr;
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
String[] input = br.readLine().split(" ");
int length = input.length;
arr = new int[length];
for (int i = 0; i < length; i++) {
arr[i] = Integer.parseInt(input[i]);
}
sort(arr);
bw.flush();
bw.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sort(int[] arr) throws Exception {
int temp;
int length = arr.length;
for (int i = 0; i < length; i++) {
for (int j = 0; j < length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
for (int target : arr)
bw.write(target + " ");
bw.write("\n");
}
}
}
}
}
|
package day25overridingexceptions;
public class Dog extends Animal {
public boolean tail;
public int birthYear;
public void bark() {
System.out.println("Dogs bark");
}
public void drink() {
System.out.println("Dogs drinks");
}
}
|
package com.mideas.rpg.v2.game;
import java.sql.SQLException;
import com.mideas.rpg.v2.Mideas;
import com.mideas.rpg.v2.game.item.Item;
import com.mideas.rpg.v2.game.item.ItemType;
import com.mideas.rpg.v2.game.item.stuff.Stuff;
import com.mideas.rpg.v2.game.shortcut.Shortcut;
import com.mideas.rpg.v2.game.spell.Spell;
import com.mideas.rpg.v2.game.spell.SpellType;
import com.mideas.rpg.v2.hud.LogChat;
public class Joueur {
private String classe;
private Shortcut[] spells;
private Spell[] spellUnlocked;
private Stuff[] stuff;
private Shortcut[] shortcut;
private int maxStamina;
private int expGained;
private int isHealer;
private int critical;
public int stamina;
private int maxMana;
private int baseExp;
private int strength;
private float armor;
private int mana;
private int stun;
private int exp;
private int gold;
private int goldGained;
private int defaultArmor;
private int defaultStuffArmor;
//private int tailorExp;
public int x;
public static int y;
public static int z;
public Joueur(int stamina, int strength, float armor, int defaultArmor, int defaultStuffArmor, int critical, int mana, Shortcut[] spells, Spell[] spellUnlocked, Stuff[] stuff, String classe, int id, int maxStamina, int maxMana, int isHealer, int expGained, int goldGained, int tailorExp) {
this.maxStamina = maxStamina;
this.expGained = expGained;
this.goldGained = goldGained;
this.isHealer = isHealer;
this.critical = critical;
//this.tailorExp = tailorExp;
this.stamina = stamina;
this.maxMana = maxMana;
this.strength = strength;
this.armor = armor;
this.mana = mana;
this.defaultArmor = defaultArmor;
this.defaultStuffArmor = defaultStuffArmor;
this.spells = spells;
this.spellUnlocked = spellUnlocked;
this.stuff = stuff;
this.classe = classe;
}
public void tick() throws SQLException {
if(stun > 0) {
System.out.println("Le joueur "+(Mideas.joueur1().equals(this)?1:2)+" est stun");
stun--;
}
else {
if(Mideas.getCurrentPlayer()) {
attack(Mideas.joueur2());
}
}
}
public boolean cast(Spell spell) throws SQLException {
if(spell.getType() == SpellType.DAMAGE) {
if(!spell.hasMana()) {
attack(Mideas.joueur2());
}
else {
spell.cast(Mideas.joueur2(), Mideas.joueur1(), spell);
LogChat.setStatusText("Le joueur 1 a enlevée "+spell.getDamage()+" hp au "+Mideas.joueur2().getClasse()+", "+Mideas.joueur2().getStamina()+" hp restant");
return true;
}
}
else if(spell.getType() == SpellType.HEAL) {
if(!spell.hasMana()) {
attack(Mideas.joueur2());
}
else {
if(Mideas.joueur1().getStamina()+spell.getHeal() >= Mideas.joueur1().getMaxStamina()) {
int diff = Mideas.joueur1().getMaxStamina()-Mideas.joueur1().getStamina();
spell.healMax(Mideas.joueur1(), spell);
LogChat.setStatusText("Vous vous êtes rendu "+diff+" hp, vous avez maintenant "+Mideas.joueur1().getStamina()+" hp");
return true;
}
else {
spell.heal(Mideas.joueur1(), spell);
LogChat.setStatusText("Vous vous êtes rendu "+spell.getHeal()+" hp, vous avez maintenant "+Mideas.joueur1().getStamina()+" hp");
return true;
}
}
}
return false;
}
public void attack(Joueur joueur) throws SQLException {
double damage = Mideas.joueur1().getStrength()+Math.random()*100;
if(Math.random() < critical/100.) {
damage*= 2;
}
joueur.setStamina(joueur.getStamina()-damage);
LogChat.setStatusText("Le joueur 1 a enlevé "+Math.round(damage)+" hp au "+joueur.getClasse()+", "+joueur.getStamina()+" hp restant"); //and "+Mideas.joueur2.getMana()+" mana left");
if(Mideas.joueur1().getStamina() <= 0) {
LogChat.setStatusText("Le joueur 2 a gagné !");
LogChat.setStatusText2("");
y = 1;
return;
}
else if(Mideas.joueur2().getStamina() <= 0) {
LogChat.setStatusText("Le joueur 1 a gagné !");
LogChat.setStatusText2("");
z = 1;
return;
}
}
public void attackUI(Spell spell) throws SQLException {
double damage = Mideas.joueur2().getStrength()+Math.random()*100;
float rand = (float)Math.random();
if(rand < Mideas.joueur2().getCritical()/100.) {
damage*= 2;
}
if(spell.getType() == SpellType.HEAL && spell.hasMana()) {
if(Mideas.joueur2().getStamina() < Mideas.joueur2().getMaxStamina()) {
if(Mideas.joueur2().getStamina()+spell.getHeal() >= Mideas.joueur2().getMaxStamina()) {
int diff = Mideas.joueur2().getMaxStamina()-Mideas.joueur2().getStamina();
spell.healMax(Mideas.joueur2(), spell);
LogChat.setStatusText2("Le joueur2 s'est rendu "+diff+" hp, il a maintenant "+Mideas.joueur2().getStamina()+" hp");
}
else {
spell.heal(Mideas.joueur2(), spell);
LogChat.setStatusText2("Le joueur2 s'est rendu "+spell.getHeal()+" hp, il a maintenant "+Mideas.joueur2().getStamina()+" hp");
}
}
}
else if(spell.getType() == SpellType.DAMAGE) {
Spell cast = Spell.getRandomSpell();
if(rand > .2 && rand <= .4 && cast.hasMana()) {
cast.cast(Mideas.joueur1(), Mideas.joueur2(), spell);
LogChat.setStatusText2("Le joueur 2 a enlevée "+cast.getDamage()+" hp au "+Mideas.joueur1().getClasse()+", "+Mideas.joueur1().getStamina()+" hp restant");
}
else {
Mideas.joueur1().setStamina(Mideas.joueur1().getStamina()-damage);
LogChat.setStatusText2("Le joueur 2 a enlevée "+Math.round(damage)+" hp au "+Mideas.joueur1().getClasse()+", "+Mideas.joueur1().getStamina()+" hp restant");
}
}
}
public void setStuffArmor(int armor) {
this.armor+= armor;
}
public void setStuffStrength(int strengh) {
this.strength+= strengh;
}
public void setStuffStamina(int stamina) {
this.maxStamina+= stamina;
this.stamina+= stamina;
}
public void setStuffCritical(int critical) {
this.critical+= critical;
}
public void setStuffMana(int mana) {
this.maxMana+= mana;
this.mana+= mana;
}
public int getDefaultStuffArmor() {
return defaultStuffArmor;
}
public String getClasse() {
return classe;
}
public float getArmor() {
return armor;
}
public int getIsHealer() {
return isHealer;
}
public void setStamina(double d) {
this.stamina = (int) Math.max(d, 0);
}
public int getMaxStamina() {
return maxStamina;
}
public int getStamina() {
return stamina;
}
public int getCritical() {
return critical;
}
public int getStrength() {
return strength;
}
public void setMana(int mana) {
this.mana = Math.max(mana, 0);
}
public int getMana() {
return mana;
}
public int getMaxMana() {
return maxMana;
}
public void setStun(int stun) {
this.stun = stun;
}
public int getX() {
return x;
}
public Shortcut[] getSpells() {
return spells;
}
public Shortcut getSpells(int i) {
return spells[i];
}
public void setSpells(int i, Shortcut spell) {
this.spells[i] = spell;
}
public Spell[] getSpellUnlocked() {
return spellUnlocked;
}
public Spell getSpellUnlocked(int i) {
return spellUnlocked[i];
}
public Stuff[] getStuff() {
return stuff;
}
public Stuff getStuff(int i) {
return stuff[i];
}
public void setStuff(int i, Item tempItem) {
if(tempItem == null) {
this.stuff[i] = null;
}
else if(tempItem.getItemType() == ItemType.STUFF) {
this.stuff[i] = (Stuff)tempItem;
}
}
public Shortcut getShortcut(int i) {
return shortcut[i];
}
public Shortcut[] getShortcut() {
return shortcut;
}
public void setSpellUnlocked(int i, Spell spell) {
this.spellUnlocked[i] = spell;
}
public int getExp() {
return exp;
}
public int getBaseExp() {
return baseExp;
}
public int getExpGained() {
return expGained;
}
public void setArmor(float number) {
this.armor = (Math.round(100*(armor+number))/100.f);
}
public int getDefaultArmor() {
return defaultArmor;
}
public int getGold() {
return gold;
}
public int getGoldGained() {
return goldGained;
}
public void setExp(int baseExp, int expGained ) {
exp = baseExp+expGained;
}
public void setMaxStamina(int stamina) {
maxStamina = stamina;
}
public void setMaxMana(int mana) {
maxMana = mana;
}
public int getNumberItem(Item item) {
if(item.getItemType() == ItemType.ITEM || item.getItemType() == ItemType.POTION) {
return Mideas.bag().getNumberStack().get(item);
}
return 0;
}
public void setNumberItem(Item potion, int number) {
if(potion.getItemType() == ItemType.ITEM || potion.getItemType() == ItemType.POTION) {
Mideas.bag().getNumberStack().put(potion, number);
}
}
}
|
package webstoreselenium.qa.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import webstoreselenium.qa.base.TestBase;
import webstoreselenium.qa.utils.TestUtil;
public class OrderSummary extends TestBase {
WebDriverWait wait;
public OrderSummary(){
PageFactory.initElements(driver, this);
}
@FindBy(xpath= "//span[@class='summary_term_continue']") public WebElement continue1;
@FindBy(id= "submit_mcl_order") public WebElement continue2;
@FindBy(xpath= "//span[@class='summary_cancel_order']") public WebElement cancel;
@FindBy(xpath= "//div[@class='card_drop_menu_head']") public WebElement selectCC;
@FindBy(xpath= "//span[@class='existing_card']") public WebElement savedCC;
@FindBy(xpath = "//div[@id='myModal']//div[@class='header']") private WebElement modalConfirm;
By loadWindow = By.id("myModal");
@FindBy(id= "sumbit_mcl_order_confirmed") public WebElement confirmPopUp;
@FindBy(id="submit_tejas_order") WebElement submitOrder;
@FindBy(xpath="//span[contains(text(),'Cancel Order')]") WebElement cancelOrder;
@FindBy(id="new_cc") WebElement newCC;
public void clickSubmitOrderTejas(){
TestUtil.click(submitOrder);
}
public void clickCancelOrderTejas(){
TestUtil.click(cancelOrder);
}
public void selectExistingCard(){
TestUtil.click(continue1);
//select card
//org.openqa.selenium.ElementNotVisibleException
TestUtil.waitTillElementFound(selectCC);
TestUtil.clickJS(selectCC);
TestUtil.waitTillElementFound(savedCC);
TestUtil.clickJS(savedCC);
TestUtil.click(continue2);
}
public void payByCreditCard(){
TestUtil.click(continue1);
TestUtil.waitTillElementFound(selectCC);
TestUtil.click(selectCC);
//TestUtil.moveToWebelement(selectCC);
//TestUtil.waitForElementToClick(newCC);
try{
TestUtil.clickJS(newCC);
}catch(org.openqa.selenium.TimeoutException e){
TestUtil.clickJS(newCC);
}
TestUtil.click(continue2);
}
public OrderConfirmation clickPlaceOrder(){
//TestUtil.waitTillElementFound(modalConfirm); // pop up
TestUtil.waitTillElementFound(confirmPopUp); // new 1 - wait til placeorderOK button appears instead of the pop up
//TestUtil.isElementPresent(driver, "//span[@id='sumbit_mcl_order_confirmed']", 20).click(); --> maybe this cause the delay
TestUtil.clickJS(confirmPopUp); //new 2 -
/*
* circle will load now, needs to wait to clear or waitURLContains
*
*
* **/
//TestUtil.waitTillInvisibleBy(loadWindow); // if this is not run not getting the correct url
TestUtil.waitTilURLContains("orderConfirmation.html?oid");
/* wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.);*/
return new OrderConfirmation();
}
public PayTracePage clickPlaceOrderGuestUser(){
TestUtil.waitTillElementFound(confirmPopUp);
TestUtil.clickJS(confirmPopUp);
return new PayTracePage();
}
}
|
package com.sample.bookstore.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.sample.bookstore.util.ConnectionUtil;
import com.sample.bookstore.util.QueryUtil;
import com.sample.bookstore.vo.Book;
import com.sample.bookstore.vo.Review;
import com.sample.bookstore.vo.User;
public class ReviewDAO {
public Review resultSetToReview(ResultSet rs) throws SQLException {
Review review = new Review();
int no = rs.getInt("review_no");
String content = rs.getString("review_content");
double point = rs.getDouble("review_point");
Date registeredDate = rs.getDate("review_registered_date");
Book book = new Book();
int bookNo = rs.getInt("book_no");
book.setNo(bookNo);
User user = new User();
String userId = rs.getString("user_id");
user.setId(userId);
review.setNo(no);
review.setContent(content);
review.setPoint(point);
review.setRegisteredDate(registeredDate);
review.setBook(book);
review.setUser(user);
return review;
}
public void addReview(Review review) throws SQLException {
Connection connection = ConnectionUtil.getConnection();
PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("review.addReview"));
pstmt.setString(1, review.getContent());
pstmt.setDouble(2, review.getPoint());
pstmt.setInt(3, review.getBook().getNo());
pstmt.setString(4, review.getUser().getId());
pstmt.executeUpdate();
pstmt.close();
connection.close();
}
public List<Review> getMyReviews(String userId) throws SQLException{
List<Review> myReviews = new ArrayList<Review>();
Connection connection = ConnectionUtil.getConnection();
PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("review.getMyReviews"));
pstmt.setString(1, userId);
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
myReviews.add(resultSetToReview(rs));
}
rs.close();
pstmt.close();
connection.close();
return myReviews;
}
public List<Review> getAllReviews() throws SQLException {
List<Review> allReviews = new ArrayList<Review>();
Connection connection = ConnectionUtil.getConnection();
PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("review.getAllReviews"));
ResultSet rs = pstmt.executeQuery();
while(rs.next()) {
allReviews.add(resultSetToReview(rs));
}
rs.close();
pstmt.close();
connection.close();
return allReviews;
}
public Review getReviewByNo(int reviewNo) throws SQLException {
Review review = null;
Connection connection = ConnectionUtil.getConnection();
PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("review.getReviewByNo"));
pstmt.setInt(1, reviewNo);
ResultSet rs = pstmt.executeQuery();
if(rs.next()) {
review = resultSetToReview(rs);
}
rs.close();
pstmt.close();
connection.close();
return review;
}
public boolean updateReview() {
return false;
}
public void removeReview(Review review) throws SQLException {
Connection connection = ConnectionUtil.getConnection();
PreparedStatement pstmt = connection.prepareStatement(QueryUtil.getSQL("review.removeReview"));
pstmt.setInt(1, review.getNo());
pstmt.executeUpdate();
pstmt.close();
connection.close();
}
}
|
package br.com.nozinho.dao.impl;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.TypedQuery;
import br.com.nozinho.dao.NotificacaoDAO;
import br.com.nozinho.ejb.dao.impl.GenericDAOImpl;
import br.com.nozinho.model.Notificacao;
import br.com.nozinho.model.Usuario;
@Stateless
public class NotificacaoDAOImpl extends GenericDAOImpl<Notificacao, Long> implements NotificacaoDAO{
@Override
public List<Notificacao> findByUsuarioNotificado(Usuario usuario) {
TypedQuery<Notificacao> query = getEntityManager().createNamedQuery("Notificacao.findAllOrdered", Notificacao.class);
query.setParameter("usuario", usuario);
query.setMaxResults(10);
return query.getResultList();
}
public Long findNumNotificacaoByUsuario(Usuario usuario){
TypedQuery<Long> query = getEntityManager().createNamedQuery("Notificacao.countByUser", Long.class);
query.setParameter("usuario", usuario);
return query.getSingleResult();
}
}
|
package services;
import java.util.List;
import java.util.Map;
import model.Medical;
import model.NYKGACar;
import model.NYKGARequisition;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.transform.AliasToEntityMapResultTransformer;
import util.DateUtil;
import db.HibernateUtil;
public class NYKGAService {
public static void sentRequisitionRequest(NYKGARequisition st, String empNo, String reqId, Session s) {
SQLQuery q = s.createSQLQuery("exec SPU_saverequisitionRequest " +
"@requestID= :reqId, " +
"@requester= :requester, " +
"@doctype= :docType, " +
"@item= :item, " +
"@requestdate= :requestDate, " +
"@requireddate= :requiredDate, " +
"@remarks= ''");
q.setString("reqId", reqId);
q.setString("requester", empNo);
q.setString("docType", st.type);
q.setString("item", st.itemId);
q.setDate("requestDate", st.requestDate);
q.setDate("requiredDate", st.requiredDate);
q.executeUpdate();
}
public static NYKGARequisition getRequisitionFromReqId(String reqId) {
Map<String, Object> map;
NYKGARequisition result = null;
Session s = HibernateUtil.getSessionFactory().openSession();
Query q = s.createSQLQuery("SPU_ViewrequisitionRequest @RequestId=:reqId");
q.setString("reqId", reqId);
q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List tmpList = null;
try {
tmpList = q.list();
} catch (HibernateException e) {
e.printStackTrace();
} finally {
s.close();
}
if(tmpList != null && tmpList.size() > 0 && tmpList.get(0) != null){
result = new NYKGARequisition();
map = (Map<String, Object>) tmpList.get(0);
result.convertFromMap(map);
}
return result;
}
public static void sentCarRequest(NYKGACar car, String empNo, String reqId, Session s) {
SQLQuery q = s.createSQLQuery("exec SPU_SaveCarRequest " +
"@requestID= :reqId, " +
"@carID= :carId, " +
"@User_Id= :requester, " +
"@requestdate= :reqDate, " +
"@driver= :driver, " +
"@purpose= '', " +
"@remarks= ''");
q.setString("reqId", reqId);
q.setString("requester", empNo);
q.setString("carId", car.carId);
q.setString("driver", car.driverId);
q.setDate("reqDate", DateUtil.getNowAsDateOnly());
q.executeUpdate();
}
}
|
package com.example.wattson.on_boarding_fragments;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.button.MaterialButton;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.wattson.OnBoardingActivity;
import com.example.wattson.R;
import com.google.android.material.button.MaterialButton;
public class OBpage3 extends Fragment {
private Button bt_doneButton;
private TextView txt_skip;
private TextView txt_plugNumber;
private MaterialButton bt_clickedButton;
private MaterialButton bt_info;
private Dialog m_infoDialog;
private boolean m_isLast = false;
private boolean m_optionPicked = false;
private boolean m_hasSkipped = false;
private int m_plugNum;
private String m_clickedButtonName;
private final String m_toastMessage = " Item already picked\nClick next, skip or double click to reset";
private MaterialButton bt_kettle;
private MaterialButton bt_washingMachine;
private MaterialButton bt_microwave;
private MaterialButton bt_tv;
private MaterialButton bt_iron;
private MaterialButton bt_ac;
private MaterialButton bt_oven;
private MaterialButton bt_computer;
private MaterialButton bt_dishWasher;
private MaterialButton bt_other;
public OBpage3() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
m_plugNum = 1;
return inflater.inflate(R.layout.fragment_ob_page3, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
bt_info = (MaterialButton) getView().findViewById(R.id.buttonInfo);
m_infoDialog = new Dialog(getContext());
bt_doneButton = (Button) getView().findViewById(R.id.button3Done);
txt_skip = (TextView) getView().findViewById(R.id.textSkip);
txt_plugNumber = (TextView) getView().findViewById(R.id.textPlugNumber);
txt_plugNumber.setText("Plug " + m_plugNum);
bt_kettle = (MaterialButton) getView().findViewById(R.id.buttonKettle);
bt_washingMachine = (MaterialButton) getView().findViewById(R.id.buttonWashingMachine);
bt_microwave = (MaterialButton) getView().findViewById(R.id.buttonMicro);
bt_tv = (MaterialButton) getView().findViewById(R.id.buttonTv);
bt_iron = (MaterialButton) getView().findViewById(R.id.buttonIron);
bt_ac = (MaterialButton) getView().findViewById(R.id.buttonAc);
bt_oven = (MaterialButton) getView().findViewById(R.id.buttonOven);
bt_computer = (MaterialButton) getView().findViewById(R.id.buttonComputer);
bt_dishWasher = (MaterialButton) getView().findViewById(R.id.buttonDishWasher);
bt_other = (MaterialButton) getView().findViewById(R.id.buttonOther);
txt_skip.setVisibility(View.INVISIBLE);
bt_doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(m_optionPicked || m_hasSkipped) {
if (m_isLast) {
((OnBoardingActivity) getActivity()).incrementBar();
} else {
incrementPlugNum();
txt_skip.setVisibility(View.VISIBLE);
txt_skip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bt_doneButton.setText("Done");
m_isLast = true;
m_hasSkipped = true;
}
});
}
}
else{
Toast.makeText(getContext(), "Please pick an Item", Toast.LENGTH_SHORT).show();
}
}
});
bt_kettle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_kettle;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_kettle.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_washingMachine.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_washingMachine;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_washingMachine.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_microwave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_microwave;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_microwave.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_tv;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_tv.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_iron.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_iron;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_iron.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_ac.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_ac;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_ac.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_oven.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_oven;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_oven.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_computer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_computer;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_computer.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_dishWasher.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_dishWasher;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_dishWasher.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_other.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!m_optionPicked) {
bt_clickedButton = bt_other;
setCLickedOption();
}
else if(bt_clickedButton.getText().toString().equals(bt_other.getText().toString())){
doUnclickButton();
}
else{
Toast.makeText(getContext(),m_toastMessage, Toast.LENGTH_SHORT).show();
}
}
});
bt_info.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
m_infoDialog.setContentView(R.layout.info_popup);
m_infoDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
m_infoDialog.show();
}
});
}
private void openDialog() {
}
/**
* Sets the clicked button when it is chosen
*/
private void setCLickedOption(){
m_clickedButtonName = bt_clickedButton.getText().toString();
bt_clickedButton.setBackgroundColor(getResources().getColor(R.color.new_background_blue));
m_optionPicked = true;
}
private void doUnclickButton(){
bt_clickedButton.setBackgroundColor(Color.WHITE);
m_optionPicked = false;
m_clickedButtonName = "";
bt_clickedButton = null;
}
/**
* This methd imcrements the plug number, reests the button colors
*/
private void incrementPlugNum(){
m_plugNum++;
String plugText = "Plug " + m_plugNum;
txt_plugNumber.setText(plugText);
doUnclickButton();
if (m_plugNum == 5){
bt_doneButton.setText("Done");
m_isLast = true;
}
}
}
|
package Index.Model;
import java.sql.ResultSet;
public class AttendanceModel {
String action="";
ResultSet result;
public String toS(String s){
String str;
try{
str = new String(s.getBytes("ISO-8859-1"),"utf-8");
}
catch(Exception e){str="";}
return str;
}
public ResultSet getResult(){
return result;
}
public void setResult(ResultSet result){
this.result=result;
}
public String getAction(){
return action;
}
public void setAction(String action){
this.action=action;
}
}
|
package com.tencent.mm.plugin.exdevice.f.a;
import com.tencent.mm.model.au;
import com.tencent.mm.network.q;
import com.tencent.mm.plugin.exdevice.a.a;
import com.tencent.mm.plugin.exdevice.a.b;
import com.tencent.mm.plugin.exdevice.f.b.a.c;
import com.tencent.mm.plugin.exdevice.model.ad;
import com.tencent.mm.protocal.c.aje;
import com.tencent.mm.protocal.c.ajf;
import com.tencent.mm.protocal.c.bre;
import com.tencent.mm.protocal.c.cig;
import com.tencent.mm.protocal.c.cih;
import com.tencent.mm.protocal.c.kc;
import com.tencent.mm.protocal.c.xj;
import com.tencent.mm.sdk.platformtools.x;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public final class i extends a<aje, ajf> {
public String appName;
public String bhd;
private final WeakReference<b<i>> isV;
public List<bre> ixA;
public List<cih> ixB;
public cig ixC;
public ArrayList<String> ixD;
public List<xj> ixE;
public List<kc> ixF;
public boolean ixG;
public int ixH;
public boolean ixI;
public String ixv;
public String ixw;
public String ixx;
public String ixy;
public String ixz;
public String username;
protected final /* synthetic */ com.tencent.mm.bk.a aGw() {
return new aje();
}
protected final /* synthetic */ com.tencent.mm.bk.a aGx() {
return new ajf();
}
protected final /* bridge */ /* synthetic */ void g(com.tencent.mm.bk.a aVar) {
aje aje = (aje) aVar;
aje.iEL = this.appName;
aje.username = this.username;
}
public i(String str, String str2, b<i> bVar) {
x.d("MicroMsg.NetSceneGetProfileDetail", "appusername: %s, username: %s", new Object[]{str2, str});
this.username = str;
this.appName = str2;
this.isV = new WeakReference(bVar);
}
public final void a(int i, int i2, int i3, String str, q qVar, byte[] bArr) {
super.a(i, i2, i3, str, qVar, bArr);
x.d("MicroMsg.NetSceneGetProfileDetail", "hy: getdetail scene gy end. errType: %d, errCode: %d, errMsg: %s", new Object[]{Integer.valueOf(i2), Integer.valueOf(i3), str});
if (i2 == 0 && i3 == 0) {
ajf ajf = (ajf) asj();
this.ixw = ajf.rLQ;
this.ixx = ajf.ixx;
this.ixB = ajf.rLT;
this.ixC = ajf.rLR;
this.ixy = ajf.rLV;
this.bhd = ajf.bhd;
this.ixz = ajf.rLW;
this.ixA = ajf.rcK;
this.ixG = ajf.ixG;
this.ixE = ajf.rch;
this.ixF = ajf.rLX;
this.ixD = new ArrayList();
this.ixH = ajf.iEk;
this.ixI = ajf.rLY;
this.ixv = ajf.ixv;
if (ajf.rLU != null) {
this.ixD.addAll(ajf.rLU);
}
this.ixA = new LinkedList();
if (ajf.rcK != null) {
this.ixA.addAll(ajf.rcK);
}
if (!(this.username == null || this.username.equalsIgnoreCase(com.tencent.mm.model.q.GF()))) {
if (this.ixG) {
com.tencent.mm.plugin.exdevice.f.b.b.a aHg = ad.aHg();
String str2 = this.username;
if (aHg.a(new com.tencent.mm.plugin.exdevice.f.b.b("hardcode_rank_id", "hardcode_app_name", str2)) == null) {
c cVar = new c();
cVar.field_rankID = "hardcode_rank_id";
cVar.field_appusername = "hardcode_app_name";
cVar.field_username = str2;
cVar.field_step = 0;
aHg.b(cVar);
}
} else {
ad.aHg().Ag(this.username);
}
}
if (ajf.rch != null) {
List arrayList = new ArrayList();
Iterator it = ajf.rch.iterator();
while (it.hasNext()) {
xj xjVar = (xj) it.next();
au.HU();
if (com.tencent.mm.model.c.FR().Yc(xjVar.username)) {
c cVar2 = new c();
cVar2.field_username = xjVar.username;
cVar2.field_step = xjVar.fHo;
arrayList.add(cVar2);
} else {
au.DF().a(new h(xjVar.username, null), 0);
}
}
x.d("MicroMsg.NetSceneGetProfileDetail", "follows %d %s", new Object[]{Integer.valueOf(arrayList.size()), arrayList.toString()});
if (com.tencent.mm.model.q.GF().equalsIgnoreCase(this.username)) {
ad.aHg().aS(arrayList);
}
}
this.ixF = new ArrayList();
if (ajf.rLX != null) {
this.ixF.addAll(ajf.rLX);
}
this.ixG = ajf.ixG;
com.tencent.mm.plugin.exdevice.f.b.a.a aVar = new com.tencent.mm.plugin.exdevice.f.b.a.a();
aVar.field_championMotto = this.ixx;
aVar.field_championUrl = this.ixw;
aVar.field_username = this.username;
LinkedList linkedList = ajf.rcK;
ad.aHi().a(aVar);
}
b bVar = (b) this.isV.get();
if (bVar != null) {
bVar.b(i2, i3, str, this);
}
}
protected final String getUri() {
return "/cgi-bin/mmbiz-bin/rank/getuserrankdetail";
}
public final int getType() {
return 1043;
}
}
|
package cualmemo.memoshop;
/**
* Created by El Memo on 11/09/2016.
*/
public class Base_datos {
private String BDusuario, BDcontrasena, BDcorreo;
public void setBDusuario(String BDusuario) {
this.BDusuario = BDusuario;
}
public void llenar(String usuario, String contrasena, String correo) {
BDusuario = usuario;
BDcontrasena = contrasena;
BDcorreo = correo;
}
public String getBDusuario() {
return BDusuario;
}
public String getBDcontrasena() {
return BDcontrasena;
}
public String getBDcorreo() {
return BDcorreo;
}
}
|
package cn.cnmua.car.controller;
import cn.cnmua.car.domian.Msg;
import cn.cnmua.car.domian.User;
import cn.cnmua.car.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @Author hjf
* @Date 2020/2/23
**/
@Controller
public class LoginController {
@Autowired
private UserService userService;
//登陆验证
@RequestMapping("toLogin")
public String toLogin(String username, String password, HttpServletRequest request){
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("user_name",username);
User u = userService.findUserByCondition(queryWrapper);
if (!u.getUserName().isEmpty()){
if (password.equals(u.getPassword())){
if ("1".equals(u.getType())){
HttpSession session = request.getSession();
session.setAttribute("user",u);
return "index";
} else{
HttpSession session = request.getSession();
session.setAttribute("user",u);
return "index-user";
}
}else {
return "";
}
} else {
return "";
}
}
}
|
package dao;
import model.Localizacao;
import model.Responsavel;
import model.User;
import util.HibernateUtil;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.transform.AliasToBeanResultTransformer;
import org.hibernate.transform.Transformers;
import java.util.ArrayList;
import java.util.List;
import javax.faces.model.SelectItem;
public class ResponsavelDaoImp implements ResponsavelDao {
@Override
public void save(Responsavel responsavel) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.save(responsavel);
t.commit();
}
@Override
public Responsavel getResponsavel(long id) {
Session session = HibernateUtil.getSessionFactory().openSession();
return (Responsavel) session.load(Responsavel.class, id);
}
@Override
public Responsavel getResponsavelByLocalizacao(long idLocalizacao) {
Responsavel r = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
r = (Responsavel) session.createQuery("FROM Responsavel WHERE id_localizacao=:idloc")
.setParameter("idloc", idLocalizacao)
.setMaxResults(1)
.uniqueResult();
t.commit();
}catch(Exception e) {
System.err.printf("Erro ao acessar função de resgatar Usuário por id de localização: " + e.getMessage() + " " + e);
}
return r;
}
@Override
public List<Responsavel> list() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
List lista = session.createQuery("from Responsavel").list();
t.commit();
return lista;
}
@Override
public void remove(Responsavel responsavel) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.delete(responsavel);
t.commit();
}
@Override
public void update(Responsavel responsavel) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.update(responsavel);
t.commit();
}
public User getLoginData(String email, String senha) {
Responsavel r = null;
Object tr = null;
try {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
tr = (Responsavel) session.createQuery("FROM Responsavel WHERE email=:email AND senha=:senha")
.setParameter("email", email)
.setParameter("senha", senha)
.setMaxResults(1)
.uniqueResult();
t.commit();
r = (Responsavel) tr;
}catch(Exception e) {
System.err.printf("Erro ao acessar função de logIn: " + e.getMessage() + " " + e + " TR: " + tr);
}
return r != null ? new User(r.getId(), r.getEmail(), r.getSenha()) : null;
}
@Override
public List<SelectItem> listItems() {
List<SelectItem> itens = new ArrayList<SelectItem>();
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
Query q = session.createQuery("from Responsavel");
List<Responsavel> responsaveis = q.list();
for(Responsavel r: responsaveis) {
SelectItem s = new SelectItem();
s.setValue(r.getId());
s.setLabel(r.getEmail());
itens.add(s);
}
t.commit();
return itens;
}
@Override
public void updateLocation(Responsavel responsavel, Localizacao localizacao){
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction t = session.beginTransaction();
session.createQuery("UPDATE Responsavel r SET r.idLocalizacao_id = :loc WHERE r.id = :id")
.setParameter("loc",localizacao.getId())
.setParameter("id", responsavel.getId()).executeUpdate();
t.commit();
}
}
|
package com.mi.model;
import java.util.Date;
public class T_Order {
private String order_id;
private String user_id;
private String user_address;
private String commodity_size;
private Date order_date;
public String getUser_address() {
return user_address;
}
public void setUser_address(String user_address) {
this.user_address = user_address;
}
public String getOrder_id() {
return order_id;
}
public void setOrder_id(String order_id) {
this.order_id = order_id;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getCommodity_size() {
return commodity_size;
}
public void setCommodity_size(String commodity_size) {
this.commodity_size = commodity_size;
}
public Date getOrder_date() {
return order_date;
}
public void setOrder_date(Date order_date) {
this.order_date = order_date;
}
}
|
package com.legalzoom.api.test.dto;
/**
*
*/
public class CreateProductIdDTO implements DTO {
private String productId; //pkProductConfiguration from ProductConfiguration
private boolean getChildren;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public boolean isGetChildren() {
return getChildren;
}
public void setGetChildren(boolean getChildren) {
this.getChildren = getChildren;
}
}
|
package day59_polymorphism_exceptions.exception_handling;
public class RuntimeErrorExample {
public static void main(String[] args) {
System.out.println(10 / 2);
// System.out.println( 10 / 0); runtimeException
System.out.println( 10 /3);
}
}
|
package edu.utexas.cs345.jdblisp;
/**
* @author Jonathan Bernard (jdbernard@gmail.com)
*/
public class Symbol implements SExp {
public final String name;
public Symbol(String name) { this.name = name; }
/** {@inheritdoc}*/
public SExp eval(SymbolTable table) throws LispException {
// lookup value in the symbol table
VariableEntry ve = table.lookupVariable(this);
// err if not defined
if (ve == null) throw new UndefinedVariableException(this);
return ve.value;
}
public String display(String offset) {
return offset + "Symbol: " + name + "\n";
}
@Override
public String toString() { return name; }
@Override
public boolean equals(Object that) {
if (this == that) return true;
if (that == null) return false;
if (!(that instanceof Symbol)) return false;
return this.name.equals(((Symbol) that).name);
}
@Override
public int hashCode() { return name.hashCode(); }
}
|
package com.devs4j.Rest.Controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.devs4j.Rest.Entity.Address;
import com.devs4j.Rest.Services.AddressJpaService;
@RestController
@RequestMapping("/users/{idUser}/perfil/{idProfile}/addresses")
public class AddressController {
@Autowired
private AddressJpaService addressJpaService;
@GetMapping
public ResponseEntity<List<Address>> getAddressByiduserAndidPerfil(@PathVariable("idUser") Integer idUser
,@PathVariable("idProfile") Integer idPerfil){
return new ResponseEntity<List<Address>>(addressJpaService.getAddressByiduserAndidPerfil(idUser,idPerfil),HttpStatus.OK);
}
@PostMapping
public ResponseEntity<Address> createaddress(@PathVariable("idUser") Integer idUser
,@PathVariable("idProfile") Integer idProfile
,@RequestBody Address address){
return new ResponseEntity<Address>(addressJpaService.createAddress(idUser,idProfile,address),HttpStatus.CREATED);
}
}
|
package com.sneaker.mall.api.model;
import java.util.Date;
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.
* 订单的操作信息
*/
public class OrderOper extends BaseModel<Long> {
/**
* 订单的ID号
*/
private long order_id;
/**
* 操作时间
*/
private Date oper_time;
/**
* 操作状态
*/
private int status;
/**
* 操作状态
*/
private String action;
/**
* 订单号
*/
private String order_no;
public String getOrder_no() {
return order_no;
}
public void setOrder_no(String order_no) {
this.order_no = order_no;
}
public long getOrder_id() {
return order_id;
}
public void setOrder_id(long order_id) {
this.order_id = order_id;
}
public Date getOper_time() {
return oper_time;
}
public void setOper_time(Date oper_time) {
this.oper_time = oper_time;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
|
package test;
public class Logout {
public static void main(String[] args) {
System.out.println("Hello B15");
// update some code
}
}
|
package servlets;
import models.Flight;
import models.Ticket;
import models.User;
import org.hibernate.cfg.Configuration;
import services.ServiceHolder;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class DependencyLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
Configuration config = new Configuration();
config.addAnnotatedClass(Flight.class);
config.addAnnotatedClass(Ticket.class);
config.addAnnotatedClass(User.class);
//service holder holders both the session factory and session. I'm calling the setters here
//to actually use the config to build them.
ServiceHolder.setSessionFactory(config.buildSessionFactory());
ServiceHolder.setSession(ServiceHolder.getSessionFactory().openSession());
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
//use the getter to grab the stored session and then close it
ServiceHolder.getSession().close();
}
}
|
package com.example.tagebuch.view;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import com.example.tagebuch.R;
import com.example.tagebuch.controller.ControladorInterfazPrincipal;
import com.example.tagebuch.controller.memento.Caretaker;
import com.example.tagebuch.controller.memento.Memento;
import com.example.tagebuch.model.pojo.Pensamiento;
import com.example.tagebuch.view.fragmentos.reportar_pensamiento;
import com.example.tagebuch.view.fragmentos.detalle_pensamiento;
import com.example.tagebuch.view.fragmentos.editar_pensamiento;
import com.example.tagebuch.view.fragmentos.item_pensamiento;
import java.util.List;
public class Actividad_interfaz_principal extends AppCompatActivity {
private Button botonReportarPensamiento;
private ControladorInterfazPrincipal controladorInterfazPrincipal;
private Caretaker caretaker = new Caretaker();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.interfaz_principal);
//Se crea el apuntador a los elementos de la interfaz
botonReportarPensamiento = findViewById(R.id.boton_reportar_pensamiento_interfaz_principal);
//Se crea una instancia del controlador
controladorInterfazPrincipal = new ControladorInterfazPrincipal();
crearCategorias();
listarPensamiento();
//Se establece el estado del bonton como visible
botonReportarPensamiento.setVisibility(View.VISIBLE);
//Se crea la accion del boton reportar pensamiento
botonReportarPensamiento.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Al hacer click se establece el estado del botón como invisibe y se ejecuta el
// metodo para reportar pensamiento
botonReportarPensamiento.setVisibility(View.GONE);
reportarPensamiento();
}
});
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.black)));
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.menu_principal, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.boton_deshacer:
Memento mementoDeshacer = caretaker.obtenerMementoDeshacer();
if(mementoDeshacer!=null){
controladorInterfazPrincipal.ejecutarMementoDeshacer(this,mementoDeshacer);
}
return true;
case R.id.boton_rehacer:
Memento mementoRehacer = caretaker.obtenerMementoRehacer();
if (mementoRehacer!=null){
controladorInterfazPrincipal.ejecutarMementoRehacer(this,mementoRehacer);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void crearCategorias(){
controladorInterfazPrincipal.insertarCategorias(this);
}
//Se crea un metodo para establecer el boton "reportar pensamiento" como visible
public void activarBoton(){
botonReportarPensamiento.setVisibility(View.VISIBLE);
}
//Se crea el metodo para activar la interfaz de reporte de pensamiento
public void reportarPensamiento(){
//Se invoca el fragmento encargado de crear el pensamiento
getSupportFragmentManager().beginTransaction().replace(R.id.linear_layout_interfaz_principal,
reportar_pensamiento.newInstance()).commit();
}
public void listarPensamiento(){
List<Pensamiento> pensamientos = controladorInterfazPrincipal.obtenerPensamientos(this);
for (Pensamiento pensamiento: pensamientos){
getSupportFragmentManager().beginTransaction().add(R.id.linear_layout_interfaz_principal,
item_pensamiento.newInstance(
pensamiento.getTitulo(),
pensamiento.getFecha(),
pensamiento.getDescripcion(),
pensamiento.getCategoria(),
controladorInterfazPrincipal.obtenerColor(
this,
pensamiento.getCategoria()
)
)
).commit();
}
}
public void visualizarDetallePensamiento(String categoria, String fecha, String titulo, String descripcion,
String color){
botonReportarPensamiento.setVisibility(View.GONE);
getSupportFragmentManager().beginTransaction().replace(R.id.linear_layout_interfaz_principal,
detalle_pensamiento.newInstance(categoria,fecha,titulo,descripcion,color)).commit();
}
public void visualizarEditarPensamiento(String titulo, String descripcion, String categoria, String fecha, String color){
botonReportarPensamiento.setVisibility(View.GONE);
getSupportFragmentManager().beginTransaction().replace(R.id.linear_layout_interfaz_principal,
editar_pensamiento.newInstance(titulo,descripcion,categoria,fecha,color)).commit();
}
//Se crea el metodo encargado de mostrar los mensajes al usuario
public void mensaje(String titulo, String mensaje){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(mensaje)
.setTitle(titulo)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
public void guardarMementoDeshacer(Memento memento, boolean limpiarRehacer){
caretaker.agregarMementoDeshacer(memento);
if (limpiarRehacer){
caretaker.limpiarRehacer();
}
}
public void guardarMementoRehacer(Memento memento){
caretaker.agregarMementoRehacer(memento);
}
public void actualizarLista(){
getSupportFragmentManager().beginTransaction().replace(R.id.linear_layout_interfaz_principal,new Fragment()).commit();
listarPensamiento();
}
}
|
package com.ex1;
import java.sql.*;
import java.util.Scanner;
import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class P6 {
public static void main(String[] args) throws SQLException {
Scanner sc = new Scanner(System.in);
MysqlDataSource mysqlDS = new MysqlDataSource();
String name = "Joker";
String fName = "Jack";
String sName = "Nicholson";
String dob = "1949-03-21";
double powers = 89.4;
mysqlDS.setURL("jdbc:mysql://localhost:3306/superheroes");
mysqlDS.setUser("root");
mysqlDS.setPassword("");
Connection conn = mysqlDS.getConnection();
Statement myStmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
System.out.println("Press Enter on the Console to Continue");
sc.nextLine();
sc.close();
String query = "insert into superhero_table values(" +
"'" + name + "', " +
"'" + fName + "', " +
"'" + sName + "', " +
"'" + dob + "', " +
"'" + powers + "')";
try{
myStmt.executeUpdate(query);
conn.close();
myStmt.close();
System.out.println(name+" sucessfully inserted into database.");
}catch(MySQLIntegrityConstraintViolationException e){
System.out.println("Error: Superhero "+name+" already exists in database.");
}
catch(SQLException e){
System.out.println(e.getMessage());
}
}
}
|
package com.hw.hackathon.model;
import java.util.List;
public class User {
private String name;
private String pwd;
private String location;
private List<String> intersts;
private String tel;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public List<String> getIntersts() {
return intersts;
}
public void setIntersts(List<String> intersts) {
this.intersts = intersts;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
|
package stringJava;
public class StringReverse {
public static void main(String[] args) {
String a = "Madan";
String b = "";
int l =a.length();// l =5 n a d a M
for(int i = l -1; i >=0; i--) // i = 4 ---->3--->2--->1--->0
{
b = b + a.charAt(i);
}
//StringBuilder r = new StringBuilder("Madan");
//System.out.println(r.reverse());
System.out.println(b);
}
}
|
package com.technology.share.mapper;
import com.technology.share.domain.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
public interface UserMapper extends MyMapper<User> {
/**
* 根据DI修改用户启用禁用状态
* @param id
*/
@Update("update t_user set user_status = !user_status where id = #{id}")
void enableDisable(@Param("id") Long id);
}
|
package com.ib.models;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.commons.collections.CollectionUtils;
import org.hibernate.annotations.Where;
/**
* Location entity stores information pertaining to the location which doesnt change like lat, long, name
*
* @author ishmael
*
*/
@Entity
@Table(name = "LOCATION")
public class Location extends BaseEntity{
@Id
@Column(name = "LOCATION_ID")
private String primaryId;
@Column(name = "NAME")
private String name;
@Column(name = "COUNTRY")
private String country;
@Column(name = "LATITUDE")
private String latitude;
@Column(name = "LONGITUDE")
private String longitude;
@OneToMany(fetch=FetchType.EAGER, cascade = { CascadeType.ALL }, mappedBy = "location")
@Where(clause = "DATE(INFO_DATE) = CURRENT_DATE")
private Set<LocationWeatherCondition> todaysConditions;
@OneToMany(fetch=FetchType.EAGER, cascade = { CascadeType.ALL }, mappedBy = "location")
@Where(clause = "DATE(INFO_DATE) = CURRENT_DATE")
private Set<LocationWeatherData> todaysData;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getLatitude() {
return latitude;
}
public void setLatitude(String latitude) {
this.latitude = latitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public Set<LocationWeatherCondition> getTodaysConditions() {
if (CollectionUtils.isEmpty(todaysConditions))
{
todaysConditions = new HashSet<LocationWeatherCondition>();
}
return todaysConditions;
}
public void setTodaysConditions(Set<LocationWeatherCondition> conditions) {
this.todaysConditions = conditions;
}
public Set<LocationWeatherData> getTodaysData() {
if (CollectionUtils.isEmpty(todaysData))
{
todaysData = new HashSet<LocationWeatherData>();
}
return todaysData;
}
public void setTodaysData(Set<LocationWeatherData> data) {
this.todaysData = data;
}
@Override
public String getPrimaryId() {
return primaryId;
}
@Override
public void setPrimaryId(String primaryId) {
this.primaryId = primaryId;
}
}
|
/*
* Copyright 2017 University of Michigan
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.umich.verdict.relation.expr;
import com.google.common.base.Optional;
import edu.umich.verdict.VerdictContext;
import edu.umich.verdict.parser.VerdictSQLBaseVisitor;
import edu.umich.verdict.parser.VerdictSQLParser;
import edu.umich.verdict.util.StringManipulations;
public class OrderByExpr extends Expr {
private Expr expr;
private Optional<String> direction;
public OrderByExpr(VerdictContext vc, Expr expr, String direction) {
super(vc);
this.expr = expr;
this.direction = Optional.fromNullable(direction);
}
public OrderByExpr(VerdictContext vc, Expr expr) {
this(vc, expr, null);
}
public Expr getExpression() {
return expr;
}
public Optional<String> getDirection() {
return direction;
}
public static OrderByExpr from(final VerdictContext vc, String expr) {
VerdictSQLParser p = StringManipulations.parserOf(expr);
VerdictSQLBaseVisitor<OrderByExpr> v = new VerdictSQLBaseVisitor<OrderByExpr>() {
@Override
public OrderByExpr visitOrder_by_expression(VerdictSQLParser.Order_by_expressionContext ctx) {
String dir = (ctx.ASC() != null) ? "ASC" : ((ctx.DESC() != null) ? "DESC" : null);
return new OrderByExpr(vc, Expr.from(vc, ctx.expression()), dir);
}
};
return v.visit(p.order_by_expression());
}
@Override
public String toString() {
if (direction.isPresent()) {
return expr.toString() + " " + direction.get();
} else {
return expr.toString();
}
}
@Override
public <T> T accept(ExprVisitor<T> v) {
return v.call(this);
}
@Override
public OrderByExpr withTableSubstituted(String newTab) {
Expr newExpr = expr.withTableSubstituted(newTab);
return new OrderByExpr(vc, newExpr, direction.orNull());
}
@Override
public String toSql() {
return toString();
}
@Override
public int hashCode() {
return expr.hashCode();
}
@Override
public boolean equals(Expr o) {
if (o instanceof OrderByExpr) {
return getExpression().equals(((OrderByExpr) o).getExpression())
&& getDirection().equals(((OrderByExpr) o).getDirection());
}
return false;
}
}
|
package com.ilearn.dao;
import com.ilearn.bean.CateBean;
import com.ilearn.bean.CategoryEntity;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.ContextHierarchy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import java.util.List;
/**
* Created by sl on 16-2-24.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "src/main/webapp")
@ContextHierarchy({
@ContextConfiguration(name = "parent", locations = "classpath*:conf/spring.xml"),
@ContextConfiguration(name = "child", locations = "classpath*:conf/springmvc.xml")
})
public class CategoryDaoTest {
@Autowired
@Qualifier("categoryDao")
private CategoryDao categoryDao;
@Test
public void testGetSecondCategory(){
// List<String> firstcates = categoryDao.getFirstCategory();
List<CateBean> secondCategory = categoryDao.getSecondCategory();
Assert.assertNotNull(secondCategory);
for(CateBean cateBean : secondCategory){
System.out.println(cateBean.getCate_name());
// List<String> cate2s = cateBean.getCate2s();
// for(String cate2 : cate2s){
// System.out.println(cate2);
//
// List<CateBean> cate2s2 = cateBean.getChildren();
//
// for (CateBean cate22 : cate2s2){
// List<String> cate3s = cate22.getCate2s();
// for (String cate3 : cate3s){
// System.out.println(cate3);
// }
// System.out.println();
// }
// System.out.println();
// }
System.out.println();
}
}
}
|
package ua.kpi;
public class Main {
public static void main(String[] args) {
// write your code here
Point point = new Point();
point.setX(3);
point.setY(5);
int coordinateX = point.getX();
int coordinateY = point.getY();
}
}
|
package com.mideas.rpg.v2.utils;
import org.lwjgl.input.Mouse;
import com.mideas.rpg.v2.Mideas;
import com.mideas.rpg.v2.render.Draw;
import com.mideas.rpg.v2.render.Sprites;
public class ScrollBar {
/*private final float Y_ASCENSOR_DOWN_SHIFT = -22;
private final float Y_ASCENSOR_UP_SHIFT = 22;
private float x;
private float y;
private float y_size;
private float x_frame_size;
private float y_frame_size;
private float scroll_tick_size;
private float y_ascensor = this.Y_ASCENSOR_UP_SHIFT;
private float y_ascensor_onclick = this.Y_ASCENSOR_UP_SHIFT;
private float y_ascensor_lastclick = this.Y_ASCENSOR_UP_SHIFT;
private int mouseWheel;
private boolean down;
private boolean dragAndScroll;
public ScrollBar(float x, float y, float y_size, float x_frame_size, float y_frame_size, boolean dragAndScroll, float scroll_tick_size) {
this.x = x;
this.y = y;
this.y_size = y_size;
this.x_frame_size = x_frame_size;
this.y_frame_size = y_frame_size;
this.dragAndScroll = dragAndScroll;
this.scroll_tick_size = scroll_tick_size;
}
public void draw() {
Draw.drawQuad(Sprites.scrollbar, this.x-2, this.y+Sprites.top_button.getImageHeight()*Mideas.getDisplayXFactor(), Sprites.scrollbar.getImageWidth()*Mideas.getDisplayXFactor(), this.y_size+17-Sprites.top_button.getImageHeight()*Mideas.getDisplayXFactor()-Sprites.bot_button.getImageHeight()*Mideas.getDisplayXFactor());
Draw.drawQuad(Sprites.top_button, this.x-2, this.y);
Draw.drawQuad(Sprites.bot_button, this.x-2, this.y+19+this.y_size-Sprites.top_button.getImageHeight()*Mideas.getDisplayXFactor());
drawUpArrow();
drawDownArrow();
Draw.drawQuad(Sprites.ascensor, this.x+5, this.y+this.y_ascensor);
}
public float getX() {
return this.x;
}
public void event() {
this.mouseWheel = Mouse.getDWheel()/12;
mouseDragEvent();
if(this.down) {
if(this.dragAndScroll) {
mouseScroll();
return;
}
this.mouseWheel = 0;
}
else {
mouseScroll();
}
}
private void mouseDragEvent() {
if(Mideas.mouseX() >= this.x+4 && Mideas.mouseX() <= this.x+24) {
if(Mideas.mouseY() >= this.y+this.y_ascensor && Mideas.mouseY() <= this.y+this.y_ascensor+16) {
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
if(Mouse.getEventButtonState()) {
this.down = true;
this.y_ascensor_onclick = Mideas.mouseY();
}
}
}
}
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
if(!Mouse.getEventButtonState()) {
this.down = false;
this.y_ascensor_lastclick = this.y_ascensor;
}
}
if(this.down) {
if(Mideas.mouseY() >= this.y+this.Y_ASCENSOR_UP_SHIFT+11 && Mideas.mouseY() <= this.y+this.y_size+7+this.Y_ASCENSOR_DOWN_SHIFT*Mideas.getDisplayXFactor()) {
this.y_ascensor = Mideas.mouseY()-this.y_ascensor_onclick+this.y_ascensor_lastclick;
}
else if(Mideas.mouseY() <= this.y+this.Y_ASCENSOR_UP_SHIFT+11) {
this.y_ascensor = this.Y_ASCENSOR_UP_SHIFT;
}
else if(Mideas.mouseY() >= this.y+this.y_size+this.Y_ASCENSOR_DOWN_SHIFT*Mideas.getDisplayXFactor()) {
this.y_ascensor = this.y_size+this.Y_ASCENSOR_DOWN_SHIFT*Mideas.getDisplayXFactor();
}
}
}
private void mouseScroll() {
if(Mideas.mouseX() >= this.x-this.x_frame_size+25 && Mideas.mouseX() <= this.x+25 && Mideas.mouseY() >= this.y-25 && Mideas.mouseY() <= this.y+this.y_frame_size+25) {
if(this.mouseWheel != 0 && this.y_ascensor-this.mouseWheel >= 17 && this.y_ascensor-this.mouseWheel < this.y_size-15) {
this.y_ascensor-= this.mouseWheel;
this.y_ascensor_lastclick = this.y_ascensor;
}
else if(this.mouseWheel != 0 && this.y_ascensor-this.mouseWheel < 17 && this.y_ascensor-this.mouseWheel <= this.y_size) {
this.y_ascensor = this.Y_ASCENSOR_UP_SHIFT;
this.y_ascensor_lastclick = this.y_ascensor;
}
else if(this.mouseWheel != 0 && this.y_ascensor-this.mouseWheel >= this.y_size-15 && this.y_ascensor-this.mouseWheel >= 17) {
this.y_ascensor = this.y_size+this.Y_ASCENSOR_DOWN_SHIFT*Mideas.getDisplayXFactor();
this.y_ascensor_lastclick = this.y_ascensor;
}
}
}
private void drawUpArrow() {
if(this.y_ascensor == this.Y_ASCENSOR_UP_SHIFT) {
Draw.drawQuad(Sprites.scrollbar_grey_up_arrow, this.x+5, this.y+5);
}
else {
Draw.drawQuad(Sprites.scrollbar_up_arrow, this.x+5, this.y+5);
}
}
private void drawDownArrow() {
if(this.y_ascensor == this.y_size+this.Y_ASCENSOR_DOWN_SHIFT*Mideas.getDisplayXFactor()) {
Draw.drawQuad(Sprites.scrollbar_grey_down_arrow, this.x+5, this.y+this.y_size);
}
else {
Draw.drawQuad(Sprites.scrollbar_down_arrow, this.x+5, this.y+this.y_size);
}
}
public float getScrollPercentage() {
if(this.y_ascensor == this.Y_ASCENSOR_UP_SHIFT) {
return 0;
}
if(this.y_ascensor == this.y_size+this.Y_ASCENSOR_DOWN_SHIFT*Mideas.getDisplayXFactor()) {
return 1;
}
return (this.y_ascensor)/(this.y_size-Sprites.ascensor.getImageHeight());
}
public void update(float x, float y, float y_size) {
this.x = x;
this.y = y;
this.y_size = y_size;
}*/
private float Y_ASCENSOR_DOWN_SHIFT = -22;
private final float Y_ASCENSOR_UP_SHIFT = 0;
private int x;
private int y;
private int scrollBarHeight;
private int frameWidth;
private int frameHeight;
private int scroll_tick_size;
private float y_ascensor = this.Y_ASCENSOR_UP_SHIFT;
private float y_ascensor_onclick = this.Y_ASCENSOR_UP_SHIFT;
private float y_ascensor_lastclick = this.Y_ASCENSOR_UP_SHIFT;
private int mouseWheel;
private boolean down;
private boolean dragAndScroll;
private boolean buttonDownTopArrow;
private boolean buttonHoverTopArrow;
private boolean buttonDownBotArrow;
private boolean buttonHoverBotArrow;
private boolean scrollbar_anchor_visible = true;
private Frame parentFrame;
private short xSave;
private short ySave;
private short scrollBarHeightSave;
private short frameWidthSave;
private short frameHeightSave;
private short scrollTickSizeSave;
private boolean isEnabled = true;
public ScrollBar(float x, float y, float y_size, float x_frame_size, float y_frame_size, boolean dragAndScroll, float scroll_tick_size) {
this.x = (int)x;
this.y = (int)y;
this.scrollBarHeight = (int)y_size;
this.frameWidth = (int)x_frame_size;
this.frameHeight = (int)y_frame_size;
this.dragAndScroll = dragAndScroll;
this.scroll_tick_size = (int)scroll_tick_size;
this.Y_ASCENSOR_DOWN_SHIFT = this.scrollBarHeight-45*Mideas.getDisplayYFactor();
}
public ScrollBar(Frame parentFrame, int x, int y, int scrollBarHeight, int frameWidth, int frameHeight, boolean dragAndScroll, float scroll_tick_size, boolean isEnabled)
{
this.parentFrame = parentFrame;
this.xSave = (short)x;
this.ySave = (short)y;
this.scrollBarHeightSave = (short)scrollBarHeight;
this.frameWidthSave = (short)frameWidth;
this.frameHeightSave = (short)frameHeight;
this.dragAndScroll = dragAndScroll;
this.scrollTickSizeSave = (short)scroll_tick_size;
this.Y_ASCENSOR_DOWN_SHIFT = this.scrollBarHeight-45*Mideas.getDisplayYFactor();
this.isEnabled = isEnabled;
}
public ScrollBar(float x, float y, float y_size, float x_frame_size, float y_frame_size, boolean dragAndScroll, float scroll_tick_size, boolean scrollbar_anchor_visible) {
this.x = (int)x;
this.y = (int)y;
this.scrollBarHeight = (int)y_size;
this.frameWidth = (int)x_frame_size;
this.frameHeight = (int)y_frame_size;
this.dragAndScroll = dragAndScroll;
this.scroll_tick_size = (int)scroll_tick_size;
this.Y_ASCENSOR_DOWN_SHIFT = this.scrollBarHeight-45*Mideas.getDisplayYFactor();
this.scrollbar_anchor_visible = scrollbar_anchor_visible;
}
public void initParentFrame(Frame parentFrame)
{
this.parentFrame = parentFrame;
updateSize();
}
public void draw() {
if (!this.isEnabled)
return;
if(this.scrollbar_anchor_visible)
Draw.drawQuad(Sprites.scrollbar, this.x, this.y+Sprites.top_button.getImageHeight()*Mideas.getDisplayYFactor(), Sprites.scrollbar.getImageWidth()*Mideas.getDisplayYFactor(), this.scrollBarHeight+19-Sprites.top_button.getImageHeight()*Mideas.getDisplayYFactor()-Sprites.bot_button.getImageHeight()*Mideas.getDisplayYFactor());
Draw.drawQuad(Sprites.top_button, this.x-3*Mideas.getDisplayXFactor(), this.y);
Draw.drawQuad(Sprites.bot_button, this.x-3*Mideas.getDisplayXFactor(), this.y+19+this.scrollBarHeight-Sprites.top_button.getImageHeight()*Mideas.getDisplayYFactor());
drawUpArrow();
drawDownArrow();
Draw.drawQuad(Sprites.ascensor, this.x+3, this.y+this.y_ascensor+22*Mideas.getDisplayYFactor());
}
public void resetScroll() {
setYAscensor(0);
}
public float getX() {
return this.x;
}
public boolean event() {
if (!this.isEnabled)
return (false);
this.mouseWheel = Mideas.getMouseScrolledTick()/12;
if(mouseDragEvent()) return true;
if(topArrowEvent()) return true;
if(botArrowEvent()) return true;
if(this.down) {
if(this.dragAndScroll) {
mouseScroll();
return true;
}
this.mouseWheel = 0;
}
else {
mouseScroll();
}
return false;
}
private boolean mouseDragEvent() {
if(Mideas.mouseX() >= this.x+4 && Mideas.mouseX() <= this.x+24) {
if(Mideas.getHover() && Mideas.mouseY() >= this.y+this.y_ascensor+22*Mideas.getDisplayYFactor() && Mideas.mouseY() <= this.y+this.y_ascensor+22*Mideas.getDisplayYFactor()+Sprites.ascensor.getImageHeight()*Mideas.getDisplayYFactor()) {
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
if(Mouse.getEventButtonState()) {
this.down = true;
this.y_ascensor_onclick = Mideas.mouseY();
return true;
}
}
Mideas.setHover(false);
}
else if(Mideas.getHover() && Mideas.mouseY() > this.y+22*Mideas.getDisplayYFactor() && Mideas.mouseY() <= this.y+this.scrollBarHeight) {
if(Mouse.getEventButtonState()) {
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
setYAscensor(Mideas.mouseY()-this.y-28*Mideas.getDisplayYFactor());
this.y_ascensor_lastclick = this.y_ascensor;
if(this.y_ascensor < this.Y_ASCENSOR_UP_SHIFT) {
setYAscensor(this.Y_ASCENSOR_UP_SHIFT);
this.buttonHoverTopArrow = false;
}
else if(this.y_ascensor > this.Y_ASCENSOR_DOWN_SHIFT) {
setYAscensor(this.Y_ASCENSOR_DOWN_SHIFT);
this.buttonHoverBotArrow = false;
}
return true;
}
}
Mideas.setHover(false);
}
}
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
if(!Mouse.getEventButtonState()) {
this.down = false;
this.y_ascensor_lastclick = this.y_ascensor;
}
}
if(this.down) {
this.y_ascensor = Mideas.mouseY()-this.y_ascensor_onclick+this.y_ascensor_lastclick;
if(this.y_ascensor < this.Y_ASCENSOR_UP_SHIFT) {
setYAscensor(this.Y_ASCENSOR_UP_SHIFT);
this.buttonHoverTopArrow = false;
}
else if(this.y_ascensor > this.Y_ASCENSOR_DOWN_SHIFT) {
setYAscensor(this.Y_ASCENSOR_DOWN_SHIFT);
this.buttonHoverBotArrow = false;
}
}
return false;
}
private void mouseScroll() {
if(Mideas.mouseX() >= this.x-this.frameWidth+25 && Mideas.mouseX() <= this.x+25 && Mideas.mouseY() >= this.y && Mideas.mouseY() <= this.y+this.frameHeight) {
if(this.mouseWheel != 0 ) {
if(this.mouseWheel > 0 && this.y_ascensor-this.scroll_tick_size > this.Y_ASCENSOR_UP_SHIFT) {
setYAscensor(this.y_ascensor-this.scroll_tick_size);
}
else if(this.mouseWheel > 0 && this.y_ascensor-this.scroll_tick_size <= this.Y_ASCENSOR_UP_SHIFT) {
setYAscensor(this.Y_ASCENSOR_UP_SHIFT);
this.buttonHoverTopArrow = false;
}
else if(this.mouseWheel < 0 && this.y_ascensor+this.scroll_tick_size < this.Y_ASCENSOR_DOWN_SHIFT) {
setYAscensor(this.y_ascensor+this.scroll_tick_size);
}
else if(this.mouseWheel < 0 && this.y_ascensor+this.scroll_tick_size >= this.Y_ASCENSOR_DOWN_SHIFT) {
setYAscensor(this.Y_ASCENSOR_DOWN_SHIFT);
this.buttonHoverBotArrow = false;
}
this.y_ascensor_lastclick = this.y_ascensor;
this.mouseWheel = 0;
}
}
}
private boolean topArrowEvent() {
if(this.y_ascensor == this.Y_ASCENSOR_UP_SHIFT) {
return false;
}
if(Mideas.mouseX() >= this.x+4*Mideas.getDisplayXFactor() && Mideas.mouseX() <= this.x+4*Mideas.getDisplayXFactor()+Sprites.scrollbar_up_arrow.getImageWidth()*Mideas.getDisplayXFactor() && Mideas.mouseY() >= this.y+2*Mideas.getDisplayYFactor() && Mideas.mouseY() <= this.y+2*Mideas.getDisplayYFactor()+Sprites.scrollbar_down_arrow.getImageHeight()*Mideas.getDisplayYFactor()) {
this.buttonHoverTopArrow = true;
}
else {
this.buttonHoverTopArrow = false;
}
if(this.buttonHoverTopArrow) {
if(Mouse.getEventButtonState()) {
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
this.buttonDownTopArrow = true;
}
}
else if(this.buttonDownTopArrow) {
if(Mouse.getEventButton() == 0) {
this.buttonDownTopArrow = false;
if(this.y_ascensor-this.scroll_tick_size > this.Y_ASCENSOR_UP_SHIFT) {
setYAscensor(this.y_ascensor-this.scroll_tick_size);
}
else if(this.y_ascensor-this.scroll_tick_size <= this.Y_ASCENSOR_UP_SHIFT) {
setYAscensor(this.Y_ASCENSOR_UP_SHIFT);
this.buttonHoverTopArrow = false;
}
this.y_ascensor_lastclick = this.y_ascensor;
return true;
}
else if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
this.buttonDownTopArrow = false;
}
}
}
else if(!Mouse.getEventButtonState()) {
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
this.buttonDownTopArrow = false;
}
}
return false;
}
private boolean botArrowEvent() {
if(this.y_ascensor != this.Y_ASCENSOR_DOWN_SHIFT) {
this.buttonHoverBotArrow = false;
if(Mideas.mouseX() >= this.x+4*Mideas.getDisplayXFactor() && Mideas.mouseX() <= this.x+4*Mideas.getDisplayXFactor()+Sprites.scrollbar_up_arrow.getImageWidth()*Mideas.getDisplayXFactor() && Mideas.mouseY() >= this.y+this.scrollBarHeight+2*Mideas.getDisplayYFactor() && Mideas.mouseY() <= this.y+this.scrollBarHeight+2*Mideas.getDisplayYFactor()+Sprites.scrollbar_down_arrow.getImageHeight()*Mideas.getDisplayYFactor()) {
this.buttonHoverBotArrow = true;
}
if(this.buttonHoverBotArrow) {
if(Mouse.getEventButtonState()) {
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
this.buttonDownBotArrow = true;
return true;
}
}
else if(this.buttonDownBotArrow) {
if(Mouse.getEventButton() == 0) {
this.buttonDownBotArrow = false;
if(this.y_ascensor+this.scroll_tick_size < this.Y_ASCENSOR_DOWN_SHIFT) {
setYAscensor(this.y_ascensor+this.scroll_tick_size);
}
else if(this.y_ascensor+this.scroll_tick_size >= this.Y_ASCENSOR_DOWN_SHIFT) {
setYAscensor(this.Y_ASCENSOR_DOWN_SHIFT);
this.buttonHoverBotArrow = false;
}
this.y_ascensor_lastclick = this.y_ascensor;
return true;
}
else if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
this.buttonDownBotArrow = false;
}
}
}
else if(!Mouse.getEventButtonState()) {
if(Mouse.getEventButton() == 0 || Mouse.getEventButton() == 1) {
this.buttonDownBotArrow = false;
}
}
}
return false;
}
private void drawUpArrow() {
if(this.y_ascensor == this.Y_ASCENSOR_UP_SHIFT) {
Draw.drawQuad(Sprites.scrollbar_grey_up_arrow, this.x+4*Mideas.getDisplayXFactor(), this.y+2*Mideas.getDisplayYFactor());
}
else if(this.buttonDownTopArrow) {
Draw.drawQuad(Sprites.scrollbar_up_arrow_down, this.x+4*Mideas.getDisplayXFactor(), this.y+2*Mideas.getDisplayYFactor());
}
else {
Draw.drawQuad(Sprites.scrollbar_up_arrow, this.x+4*Mideas.getDisplayXFactor(), this.y+2*Mideas.getDisplayYFactor());
}
if(this.buttonHoverTopArrow) {
Draw.drawQuadBlend(Sprites.scrollbar_arrow_hover, this.x+4*Mideas.getDisplayXFactor(), this.y+4*Mideas.getDisplayYFactor());
}
}
private void drawDownArrow() {
if(this.y_ascensor == this.Y_ASCENSOR_DOWN_SHIFT) {
Draw.drawQuad(Sprites.scrollbar_grey_down_arrow, this.x+4*Mideas.getDisplayXFactor(), this.y+this.scrollBarHeight+1*Mideas.getDisplayYFactor());
}
else if(this.buttonDownBotArrow) {
Draw.drawQuad(Sprites.scrollbar_down_arrow_down, this.x+4*Mideas.getDisplayXFactor(), this.y+this.scrollBarHeight+1*Mideas.getDisplayYFactor());
}
else {
Draw.drawQuad(Sprites.scrollbar_down_arrow, this.x+4*Mideas.getDisplayXFactor(), this.y+this.scrollBarHeight+1*Mideas.getDisplayYFactor());
}
if(this.buttonHoverBotArrow) {
Draw.drawQuadBlend(Sprites.scrollbar_arrow_hover, this.x+4*Mideas.getDisplayXFactor(), this.y+this.scrollBarHeight);
}
}
private void setYAscensor(float value) {
this.y_ascensor = value;
onScroll();
}
public float getScrollPercentage() {
/*if(this.y_ascensor == this.Y_ASCENSOR_UP_SHIFT) {
System.out.println("y_ascensor: 0");
return 0;
}
if(this.y_ascensor == this.y_size+this.Y_ASCENSOR_DOWN_SHIFT*Mideas.getDisplayYFactor()) {
System.out.println("y_ascensor: 1");
return 1;
}*/
//System.out.println("y_ascensor: "+(this.y_ascensor)/(this.y_size-45*Mideas.getDisplayYFactor()));
//return (this.y_ascensor)/(this.y_size-2*Sprites.ascensor.getImageHeight()*Mideas.getDisplayYFactor());
return this.y_ascensor/this.Y_ASCENSOR_DOWN_SHIFT;
}
public void update(float x, float y, float y_size, float scroll_tick_size) {
this.x = (int)x;
this.y = (int)y;
boolean resize = this.y_ascensor == this.Y_ASCENSOR_DOWN_SHIFT;
this.scrollBarHeight = (int)y_size;
this.scroll_tick_size = (int)scroll_tick_size;
this.Y_ASCENSOR_DOWN_SHIFT = this.scrollBarHeight-45*Mideas.getDisplayYFactor();
if(resize) {
this.y_ascensor = this.Y_ASCENSOR_DOWN_SHIFT;
}
}
public void updateSize()
{
this.x = (short)(this.parentFrame.getX() + this.xSave * Mideas.getDisplayXFactor());
this.y = (short)(this.parentFrame.getY() + this.ySave * Mideas.getDisplayYFactor());
this.scroll_tick_size = (int)(this.scrollTickSizeSave * Mideas.getDisplayYFactor());
this.scrollBarHeight = (short)(this.scrollBarHeightSave * Mideas.getDisplayYFactor());
this.frameWidth = (int)(this.frameWidthSave * Mideas.getDisplayXFactor());
this.frameHeight = (int)(this.frameHeightSave * Mideas.getDisplayYFactor());
this.Y_ASCENSOR_DOWN_SHIFT = this.scrollBarHeight-45*Mideas.getDisplayYFactor();
if(this.y_ascensor == this.Y_ASCENSOR_DOWN_SHIFT)
this.y_ascensor = this.Y_ASCENSOR_DOWN_SHIFT;
}
public void update(float x, float y, float y_size, float x_frame_size, float y_frame_size, float scroll_tick_size) {
this.x = (int)x;
this.y = (int)y;
boolean resize = this.y_ascensor == this.Y_ASCENSOR_DOWN_SHIFT;
this.scrollBarHeight = (int)y_size;
this.frameWidth = (int)x_frame_size;
this.frameHeight = (int)y_frame_size;
this.scroll_tick_size = (int)scroll_tick_size;
this.Y_ASCENSOR_DOWN_SHIFT = this.scrollBarHeight-45*Mideas.getDisplayYFactor();
if(resize) {
this.y_ascensor = this.Y_ASCENSOR_DOWN_SHIFT;
}
}
public void enable()
{
this.isEnabled = true;
}
public void disable()
{
this.isEnabled = false;
}
public void onScroll() {}
}
|
package com.home.test;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
public class ACLRoleService {
public void pushDataIntoDatabase() {
OrientBaseGraph graphNoTx = OrientGraphConnectionPool.getInstance().getOrientGraph(true);
List<Map<String, Object>> roles = new FirstExample().getData(
"select * from acl_group_type", Constants.ROLE.toLowerCase());
VertexUtility.createVertex(graphNoTx,Constants.ROLE);
if (roles != null) {
for (Map<String, Object> role : roles) {
if (VertexUtility.getVertex(graphNoTx, (String)role.get("name"),"name",Constants.ROLE) != null) {
System.out.println("Role already Exists.");
continue;
}
OrientVertex orientVertex = graphNoTx
.addVertex("class:Role");
for (Entry<String, Object> entry : role.entrySet()) {
orientVertex.setProperty(entry.getKey(), (String)entry.getValue());
}
}
}
}
}
|
package com.a3live.cacanindin.artemio.medcentral;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.app.ListFragment;
import android.os.Build;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import java.util.ArrayList;
public class MedsFragment extends ListFragment {
ArrayList<String> listItems = new ArrayList<>();
//DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
ArrayAdapter<String> adapter;
@TargetApi(Build.VERSION_CODES.M)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
adapter = new ArrayAdapter<String>(this.getContext(), android.R.layout.simple_list_item_1, listItems);
setListAdapter(adapter);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.meds_layout, container, false);
}
@Override
public void onStart() {
super.onStart();
Button addBtn;
addBtn = (Button) getView().findViewById(R.id.addBtn);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
addItems(view);
}
});
}
@Override
public void onPause() {
System.out.println("Medication Paused");
super.onPause();
}
@Override
public void onResume() {
System.out.println("Medication Resumed");
super.onResume();
}
@Override
public void onDestroy() {
System.out.println("Medication Destroyed");
super.onDestroy();
}
public void addItems(View v) {
listItems.add("Bradley");
adapter.notifyDataSetChanged();
}
}
|
package edu.uoc.arbolgenealogico.service.interfaces;
import java.util.List;
import edu.uoc.arbolgenealogico.model.UsuarioDAOImpl;
import edu.uoc.arbolgenealogico.pojo.Usuario;
public interface IUsuarioService {
public int create(Usuario u);
public Usuario getById(int codigo);
public Usuario getByUsername(String username);
public Usuario getByOnline();
public List<Usuario> getAll();
public int update(Usuario u);
public int delete(int codigo);
public void setUsuarioDAO(UsuarioDAOImpl usuarioDAO);
}
|
package com.paxos.simple;
/**
* Created by Vincent on 2017/5/4.
*/
public class Proposer implements Runnable {
private Channel channel;
private Network network;
private int pNum, index;//pNum:提议者向接收者发出提议的编号,故初始化为提议者自身的编号
private String message;
public Proposer(Network network, int index) {
this.network = network;
channel = network.getChannel(index);
pNum = index;
this.index = index;
System.out.println("Proposer " + index + " is created");
}
public void run() {
int i;
String tokens[];
int highNa = -1, valA, nA, value = -1;
int [] dest = new int[network.getNumAcceptors()];
int timeout;
while(true) {
while(channel.isProposer() == false);
//向所有的Acceptor发送提议
for(i=network.getNumProposers();i<network.getNumAcceptors()+network.getNumProposers(); i++) {
message = Integer.toString(pNum);
channel.sendMessage(i, message);
System.out.println("Proposer" + index + " send request to Acceptor" + i + ", and the request is: " + message);
}
i = 0;
timeout = 10;
do{
while(timeout != 0) {
if((message = channel.receiveMessage()) == null) {
timeout--;
channel.sleep(500);
continue;
}
break;
}
if(timeout == 0) break;
System.out.println("Proposer" + index + " received message, and the message is: " + message);
tokens = message.split(" ");
nA = Integer.parseInt(tokens[0]);
valA = Integer.parseInt(tokens[1]);
if(dest[Integer.parseInt(tokens[2])-network.getNumProposers()] == 0 && Integer.parseInt(tokens[3]) == pNum) {
dest[Integer.parseInt(tokens[2])-network.getNumProposers()] = Integer.parseInt(tokens[2]);
i++;
if(nA > highNa) {
value = valA;
highNa = nA;
}
}
} while(i < (network.getNumAcceptors()/2) +1);
if(timeout == 0) {
//进入确认提议阶段后,proposer向Acceptor确认提议编号,如果无法得到确认,则Proposer继续提议,编号自增
// (自增量为Proposer的总数量,方便确认提议是由哪个proposer产生的)
pNum += network.getNumProposers();
continue;
}
if(value == -1) {
value = channel.getInitialValueOfProposer();
}
message = pNum + " " + value;
for(i=0;i<network.getNumAcceptors();i++) {
if(dest[i] > 0) {
channel.sendMessage(dest[i], message);
}
}
pNum += network.getNumProposers();
}
}
}
|
package com.espendwise.manta.dao;
import com.espendwise.manta.model.data.GenericReportData;
import com.espendwise.manta.util.RefCodeNames;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;
public class GenericReportDAOImpl extends DAOImpl implements GenericReportDAO {
public GenericReportDAOImpl(EntityManager entityManager) {
super(entityManager);
}
@Override
public List<GenericReportData> findGenericReports(Long groupId) {
Query q = em.createQuery("Select report from GenericReportData report, GroupAssocData assoc " +
"where report.genericReportId = assoc.genericReportId " +
" and assoc.groupAssocCd = (:groupAssocCd) " +
" and assoc.groupId = (:groupId)"
);
q.setParameter("groupAssocCd", RefCodeNames.GROUP_ASSOC_CD.REPORT_OF_GROUP);
q.setParameter("groupId", groupId);
return q.getResultList();
}
}
|
package com.dental.lab.repositories;
import java.util.Optional;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.EntityGraph.EntityGraphType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.dental.lab.data.Entities.UserEntity;
public interface UserRepository extends JpaRepository<UserEntity, Long> {
@Query(value = "select u from UserEntity u join fetch u.authorities where u.username = :username",
countQuery = "select count(u) from UserEntity u join fetch u.authorities where u.username = :username")
Optional<UserEntity> findByUsernameWithAuthorities(@Param("username") String username);
@EntityGraph(value = "UserEntity.AddressesPhones", type = EntityGraphType.FETCH)
@Query(value = "select u from UserEntity u where u.id = :userId")
Optional<UserEntity> findByIdWithPhonesAndAddresses(@Param("userId") Long userId);
Optional<UserEntity> findByUsername(String username);
Optional<UserEntity> findById(Long id);
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
}
|
package fibonacci;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class FibonacciTest {
@Test
void fibonacciFunction() {
Fibonacci fibonacci = new Fibonacci();
int [] index = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34};
int result = fibonacci.fibonacciFunction(6);
assertEquals(index[6],result);
}
@Test
void fibonacciFunctionContainsThatNumber() {
Fibonacci fibonacci = new Fibonacci();
int result = fibonacci.fibonacciFunction(10);
assertEquals(55,result);
}
@Test
void fibonacciMinusIndex() {
Fibonacci fibonacci = new Fibonacci();
int result = fibonacci.fibonacciFunction(-2);
assertEquals(-1,result);
}
}
|
package com.curiouscorrelation.fluxvideo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import com.curiouscorrelation.fluxvideo.service.StreamingService;
import reactor.core.publisher.Mono;
@SpringBootApplication
@RestController
public class FluxVideoApplication {
@Autowired
private StreamingService streamingService;
/**
* Returns reactive `Mono` publisher containing video returned by {@link StreamingService}
*
* @param title Video title provided by the caller
* @param range Range header provided by the browser.
* The required range should be specified by the browser.
*/
@GetMapping(value = "video/{title}", produces = "video/mp4")
public Mono<Resource> getVideos(@PathVariable final String title,
@RequestHeader("Range") final String range) {
return streamingService.getVideo(title);
}
public static void main(final String[] args) {
SpringApplication.run(FluxVideoApplication.class, args);
}
}
|
package com.zhouyi.business.core.model;
import java.io.Serializable;
import java.util.Date;
public class LedenCollectPMessagerecords implements Serializable {
private String cjmbbh;
private String yddh;
private String gxrYddh;
private String gxrXm;
private String bdsjbs;
private Date dxsfsj;
private String dxJyqk;
private String ckzt;
private String dxccwz;
private String smxsz;
private String ljzt;
private String fjsxid;
private String xxscPdbz;
private Date xxscClsj;
private static final long serialVersionUID = 1L;
public String getCjmbbh() {
return cjmbbh;
}
public void setCjmbbh(String cjmbbh) {
this.cjmbbh = cjmbbh;
}
public String getYddh() {
return yddh;
}
public void setYddh(String yddh) {
this.yddh = yddh;
}
public String getGxrYddh() {
return gxrYddh;
}
public void setGxrYddh(String gxrYddh) {
this.gxrYddh = gxrYddh;
}
public String getGxrXm() {
return gxrXm;
}
public void setGxrXm(String gxrXm) {
this.gxrXm = gxrXm;
}
public String getBdsjbs() {
return bdsjbs;
}
public void setBdsjbs(String bdsjbs) {
this.bdsjbs = bdsjbs;
}
public Date getDxsfsj() {
return dxsfsj;
}
public void setDxsfsj(Date dxsfsj) {
this.dxsfsj = dxsfsj;
}
public String getDxJyqk() {
return dxJyqk;
}
public void setDxJyqk(String dxJyqk) {
this.dxJyqk = dxJyqk;
}
public String getCkzt() {
return ckzt;
}
public void setCkzt(String ckzt) {
this.ckzt = ckzt;
}
public String getDxccwz() {
return dxccwz;
}
public void setDxccwz(String dxccwz) {
this.dxccwz = dxccwz;
}
public String getSmxsz() {
return smxsz;
}
public void setSmxsz(String smxsz) {
this.smxsz = smxsz;
}
public String getLjzt() {
return ljzt;
}
public void setLjzt(String ljzt) {
this.ljzt = ljzt;
}
public String getFjsxid() {
return fjsxid;
}
public void setFjsxid(String fjsxid) {
this.fjsxid = fjsxid;
}
public String getXxscPdbz() {
return xxscPdbz;
}
public void setXxscPdbz(String xxscPdbz) {
this.xxscPdbz = xxscPdbz;
}
public Date getXxscClsj() {
return xxscClsj;
}
public void setXxscClsj(Date xxscClsj) {
this.xxscClsj = xxscClsj;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", cjmbbh=").append(cjmbbh);
sb.append(", yddh=").append(yddh);
sb.append(", gxrYddh=").append(gxrYddh);
sb.append(", gxrXm=").append(gxrXm);
sb.append(", bdsjbs=").append(bdsjbs);
sb.append(", dxsfsj=").append(dxsfsj);
sb.append(", dxJyqk=").append(dxJyqk);
sb.append(", ckzt=").append(ckzt);
sb.append(", dxccwz=").append(dxccwz);
sb.append(", smxsz=").append(smxsz);
sb.append(", ljzt=").append(ljzt);
sb.append(", fjsxid=").append(fjsxid);
sb.append(", xxscPdbz=").append(xxscPdbz);
sb.append(", xxscClsj=").append(xxscClsj);
sb.append("]");
return sb.toString();
}
}
|
package lt.kvk.i11.radiukiene;
import android.app.Application;
import android.database.sqlite.SQLiteDatabase;
import android.test.ApplicationTestCase;
import lt.kvk.i11.radiukiene.utils.DatabaseHandler;
/**
* Created by Vita on 4/25/2018.
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest(){
super(Application.class);
}
public void testCreateDb(){
mContext.deleteDatabase(DatabaseHandler.DATABASE_NAME);
SQLiteDatabase db = new DatabaseHandler(mContext).getWritableDatabase();
assertEquals(true, db.isOpen());
db.close();
}
}
|
package controller;
import java.util.*;
import fwk.TextFieldModel;
import model.IModel;
import model.MainModel;
/**
* implementation of Controller
*/
public class MyController implements Controller {
private IModel mainModel;
private IModel textModel;
/**
* default constructor
*/
public MyController() {
}
/**
* constructor for setting models
*
* @param a_model
* - model
* @param a_textModel
* - model of text field from view
*/
public MyController(IModel a_model, TextFieldModel a_textModel) {
mainModel = a_model;
textModel = a_textModel;
}
/**
* sets main model
*/
public void setMainModel(IModel a_mainModel) {
mainModel = a_mainModel;
}
/**
* set component model
*/
public void setComponentModel(IModel componentModel) {
textModel = componentModel;
}
/**
* method for button pressure processing
*/
public void OK() {
mainModel.setData(textModel.getData());
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package ohjelma.eiKaytossaOlevatTietorakenteet;
/**
*
* @author kkivikat
*/
public class Linkitettylista {
private PinoSolmu paalimmainen;
public Linkitettylista() {
paalimmainen = null;
}
public void push(int avain) {
PinoSolmu x = new PinoSolmu();
x.avain = avain;
x.seuraava = paalimmainen;
paalimmainen = x;
}
public int pop() {
PinoSolmu x = paalimmainen;
paalimmainen = x.seuraava;
return x.getAvain();
}
public boolean onkoTyhja() {
return (paalimmainen == null);
}
}
|
package client;
import controller.ProductController;
import model.Product;
import model.concrete.Book;
import model.concrete.Cigar;
import repository.impl.ProductRepository;
import service.impl.ProductNameComparator;
import service.impl.ProductPriceComparator;
import utils.ClassOfProduct;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Client {
Scanner sc = new Scanner(System.in);
List<Product> myProducts = new ArrayList<>();
ProductController productController = new ProductController();
ProductRepository productRepository = new ProductRepository();
ProductPriceComparator productPriceComparator = new ProductPriceComparator();
ProductNameComparator productNameComparator = new ProductNameComparator();
public final String adminPassword = "123";
public final String staffPassword = "111";
public String filePath = "D:\\Code Gym\\Git\\Module 2\\Java\\QLSP\\Products";
File file = new File(filePath);
public boolean checkFirstTime(){
if(file.length()==0){
return true;
}else return false;
}
public void menu(){
getLoad();
System.out.println("======Menu======");
System.out.println("Identify yourself");
System.out.println("1. Admin");
System.out.println("2. Staff");
int choice = sc.nextInt();
switch (choice){
case 1:
adminLogin();
break;
case 2:
staffLogin();
break;
default:
System.out.println("Enter 1 or 2");
menu();
}
}
public void adminLogin(){
System.out.println("Enter password: ");
String password = sc.next();
if(password.equals(adminPassword)){
adminMenu();
}else {
System.out.println("Wrong password! Check again!");
adminLogin();
}
}
public void staffLogin(){
System.out.println("Enter password: ");
String password = sc.next();
if (password.equals(staffPassword)){
staffMenu();
}
else {
System.out.println("Wrong password! Check again!");
staffLogin();
}
}
public void adminMenu(){
if (checkFirstTime()) {
System.out.println("First time running! Please add a new Product");
System.out.println("-------");
addNewProduct();
}else {
while (true) {
System.out.println("=====Menu====");
System.out.println("0. Exit");
System.out.println("1. Sort by Price");
System.out.println("2. Sort by Name");
System.out.println("3. Find a product by ID or Name");
System.out.println("4. Display all of products");
System.out.println("5. Update product");
System.out.println("6. Add a new product");
System.out.println("7. Delete product");
int choice = sc.nextInt();
switch (choice) {
case 1:
productController.sort(myProducts,productPriceComparator);
productController.display(myProducts);
productRepository.save(myProducts);
break;
case 2:
productController.sort(myProducts,productNameComparator);
productController.display(myProducts);
productRepository.save(myProducts);
break;
case 3:
System.out.println("Enter product ID or Name");
sc.nextLine();
String idOrName = sc.nextLine();
Product product = productController.find(myProducts,idOrName);
if(productController.checkType(product)==ClassOfProduct.BOOK){
product = (Book) product;
System.out.println(product.displayProductInfo());
}
else if(productController.checkType(product) == ClassOfProduct.CIGAR){
product = (Cigar) product;
System.out.println(product.displayProductInfo());
}
break;
case 4:
productController.display(myProducts);
break;
case 5:
System.out.println("Enter id");
sc.nextLine();
String id = sc.nextLine();
ClassOfProduct checkType = productController.checkType(productController.find(myProducts,id));
Product newProduct = productController.factoryProduct(checkType);
productController.update(myProducts,newProduct,Integer.parseInt(id));
productController.display(myProducts);
productRepository.save(myProducts);
break;
case 6:
addNewProduct();
break;
case 7:
System.out.println("Enter ID of Name");
sc.nextLine();
String checkID = sc.nextLine();
productController.remove(myProducts,checkID);
productRepository.save(myProducts);
break;
case 0:
System.exit(0);
default:
System.out.println("Enter your choice again!");
}
}
}
}
public void staffMenu(){
if (checkFirstTime()) {
System.out.println("First time running! Please add a new Product");
System.out.println("-------");
addNewProduct();
}else {
while (true) {
System.out.println("=====Menu====");
System.out.println("0. Exit");
System.out.println("1. Sort by Price");
System.out.println("2. Sort by Name");
System.out.println("3. Find a product by ID or Name");
System.out.println("4. Display all of products");
System.out.println("5. Update product");
System.out.println("6. Add a new product");
int choice = sc.nextInt();
switch (choice) {
case 1:
productController.sort(myProducts,productPriceComparator);
productController.display(myProducts);
productRepository.save(myProducts);
break;
case 2:
productController.sort(myProducts,productNameComparator);
productController.display(myProducts);
productRepository.save(myProducts);
break;
case 3:
System.out.println("Enter product ID or Name");
sc.nextLine();
String idOrName = sc.nextLine();
Product product = productController.find(myProducts,idOrName);
if(productController.checkType(product)==ClassOfProduct.BOOK){
product = (Book) product;
System.out.println(product.displayProductInfo());
}
else if(productController.checkType(product) == ClassOfProduct.CIGAR){
product = (Cigar) product;
System.out.println(product.displayProductInfo());
}
break;
case 4:
productController.display(myProducts);
break;
case 5:
System.out.println("Enter id");
sc.nextLine();
String id = sc.nextLine();
ClassOfProduct checkType = productController.checkType(productController.find(myProducts,id));
Product newProduct = productController.factoryProduct(checkType);
productController.update(myProducts,newProduct,Integer.parseInt(id));
productController.display(myProducts);
productRepository.save(myProducts);
break;
case 6:
addNewProduct();
break;
case 0:
System.exit(0);
default:
System.out.println("Enter your choice again!");
}
}
}
}
public void getLoad() {
productRepository.load(myProducts);
}
public void addNewProduct() {
while (true) {
System.out.println("Which type of Product do you want to add?");
System.out.println("0. Back");
System.out.println("1.Book");
System.out.println("2.Cigar");
System.out.println("3. Exit");
int choice = sc.nextInt();
switch (choice) {
case 1:
productController.add(myProducts, productController.factoryProduct(ClassOfProduct.BOOK));
productRepository.save(myProducts);
break;
case 2:
productController.add(myProducts, productController.factoryProduct(ClassOfProduct.CIGAR));
productRepository.save(myProducts);
break;
case 3:
System.exit(0);
case 0:
staffMenu();
default:
System.out.println("Enter 0 or 1 or 2");
}
}
}
}
|
package td.td4;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import td.entities.records.EmployeeJpaRecord;
public class TestFindEmployee {
private static void log(String msg) {
System.out.println( msg );
}
public static EmployeeJpaRecord findEmployee(EntityManager em, String pk ) {
log( "find : id = " + pk );
EmployeeJpaRecord employee = em.find(EmployeeJpaRecord.class, pk);
if ( employee != null ) {
log( "PK " + pk + " found : " + employee );
}
else {
log( "PK " + pk + " not found.");
}
return employee ;
}
public static void main(String[] args)
{
System.out.println("--- Persistence.createEntityManagerFactory(xx)...");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("td");
System.out.println("--- emf.createEntityManager()...");
EntityManager em = emf.createEntityManager();
System.out.println("----------");
System.out.println("EntityManager class : " + em.getClass().getCanonicalName() );
System.out.println("EntityManager isOpen() : " + em.isOpen() );
System.out.println("----------");
System.out.println("==================================");
EmployeeJpaRecord e = findEmployee(em, "A001");
if ( e != null ) {
System.out.println("employee : " + e);
System.out.println("get badbge");
// Lazy loading
System.out.println("badge : " + e.getBadge() );
}
System.out.println("----------");
findEmployee(em, "ZZZZ");
System.out.println("==================================");
// close the EM and EMF when done
System.out.println("--- closing EntityManager ...");
em.close();
System.out.println("EntityManager isOpen() : " + em.isOpen() );
System.out.println("--- closing EntityManagerFactory ...");
emf.close();
// ERROR ( em is closed )
// System.out.println("badge : " + e.getBadge() );
}
}
|
package com.javateam.demoMyBatis.vo;
import java.sql.Date;
import lombok.Data;
@Data
public class EmployeesVO {
private int employeeId;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private Date hireDate;
private String jobId;
private int salary;
private int commissionPct;
private int managerId;
private int departmentId;
}
|
package com.zooniverse.android.android_zooniverse.infrastructure;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class GraphProviderTest {
@Test
public void getInstance_returnsSameInstance() {
GraphProvider instance = GraphProvider.getInstance();
GraphProvider secondInstance = GraphProvider.getInstance();
assertThat(instance).isSameAs(secondInstance);
}
}
|
package com.jackie.classbook.entity;
/**
* Created with IntelliJ IDEA.
* Description:
*
* @author xujj
* @date 2018/12/7
*/
public class AccountClassMapper {
private Long id; //id
private Long accountId; //用户id
private Long schoolId; //学校id
private Long classId; //班级id
private Byte validFlag; //标志位
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public Long getSchoolId() {
return schoolId;
}
public void setSchoolId(Long schoolId) {
this.schoolId = schoolId;
}
public Long getClassId() {
return classId;
}
public void setClassId(Long classId) {
this.classId = classId;
}
public Byte getValidFlag() {
return validFlag;
}
public void setValidFlag(Byte validFlag) {
this.validFlag = validFlag;
}
}
|
package com.tsn.service.impl;
import com.tsn.entity.User;
import com.tsn.mapper.UserMapper;
import com.tsn.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 服务实现类
* </p>
*
* @author tsn
* @since 2021-07-06
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
|
package com.comviva.executor.restservice;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import com.comviva.executor.body.ServerExecutor;
import com.comviva.executor.sysout2log.SystemOutToLog4j;
@SpringBootApplication
@EnableAsync
public class Main {
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
SystemOutToLog4j.enableForPackage("main.java.com");
SpringApplication.run(Main.class, args);
//Add class that have println to convert them to log file
//ServerExecutor serverExec = new ServerExecutor();
}
}
|
package java2.database;
import java2.domain.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;
import java.util.Optional;
//@Component
public class UserORMDatabase implements UserDatabase {
@Autowired private SessionFactory sessionFactory;
private Session session() {
return sessionFactory.getCurrentSession();
}
private CriteriaBuilder criteriaBuilder() {
return session().getCriteriaBuilder();
}
@Override
public void add(User user) {
session().save(user);
}
@Override
public Optional<User> findById(int id) {
return Optional.empty();
}
@Override
public Optional<User> findByLogin(String login) {
return Optional.empty();
}
@Override
public Optional<User> findByEmail(String email) {
return Optional.empty();
}
@Override
@Transactional
public List<User> getAllUsers() {
CriteriaQuery<User> criteriaQuery = criteriaBuilder().createQuery(User.class);
criteriaQuery.from(User.class);
return session().createQuery(criteriaQuery).getResultList();
}
@Override
public void banUser(User user) {
}
}
|
package com.bit.myfood.service;
import com.bit.myfood.model.entity.Partner;
import com.bit.myfood.model.network.Header;
import com.bit.myfood.model.network.Pagination;
import com.bit.myfood.model.network.request.PartnerApiRequest;
import com.bit.myfood.model.network.response.PartnerApiResponse;
import com.bit.myfood.repository.CategoryRepository;
import com.bit.myfood.service.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class PartnerApiLogicService extends BaseService<PartnerApiRequest,PartnerApiResponse, Partner> {
@Autowired
CategoryRepository categoryRepository;
// region CRUD
@Override
public Header<PartnerApiResponse> create(Header<PartnerApiRequest> request) {
PartnerApiRequest body = request.getData();
Partner entity = Partner.builder()
.name(body.getName())
.status(body.getStatus())
.address(body.getAddress())
.callCenter(body.getCallCenter())
.partnerNumber(body.getPartnerNumber())
.businessNumber(body.getBusinessNumber())
.ceoName(body.getCeoName())
.registeredAt(LocalDateTime.now())
.category(categoryRepository.getOne(body.getCategoryId()))
.build();
Partner newEntity = baseRepository.save(entity);
return Header.OK(response(newEntity));
}
@Override
public Header<PartnerApiResponse> read(Long id) {
return baseRepository.findById(id)
.map(entity -> response(entity))
.map(Header::OK)
.orElseGet(() -> Header.ERROR("데이터 없음"));
}
@Override
public Header<PartnerApiResponse> update(Header<PartnerApiRequest> request) {
PartnerApiRequest body = request.getData();
Optional<Partner> optionalEntity = baseRepository.findById(body.getId());
return optionalEntity.map(entity -> {
entity.setName(body.getName())
.setStatus(body.getStatus())
.setAddress(body.getAddress())
.setCallCenter(body.getCallCenter())
.setPartnerNumber(body.getPartnerNumber())
.setBusinessNumber(body.getBusinessNumber())
.setCeoName(body.getCeoName())
.setRegisteredAt(LocalDateTime.now())
.setCategory(categoryRepository.getOne(body.getCategoryId()));
return entity;
})
.map(entity -> baseRepository.save(entity))
.map(newEntity -> response(newEntity))
.map(Header::OK)
.orElseGet(() -> Header.ERROR("데이터 없음"));
}
@Override
public Header delete(Long id) {
Optional<Partner> optionalEntity = baseRepository.findById(id);
return optionalEntity.map(entity -> {
baseRepository.delete(entity);
return Header.OK();
})
.orElseGet(() -> Header.ERROR("데이터 없음"));
}
// endregion
@Override
protected PartnerApiResponse response(Partner entity) {
// item -> itemApiResponse
PartnerApiResponse partnerApiResponse = PartnerApiResponse.builder()
.id(entity.getId())
.name(entity.getName())
.status(entity.getStatus())
.address(entity.getAddress())
.callCenter(entity.getCallCenter())
.partnerNumber(entity.getPartnerNumber())
.businessNumber(entity.getBusinessNumber())
.ceoName(entity.getCeoName())
.registeredAt(entity.getRegisteredAt())
.unregisteredAt(entity.getUnregisteredAt())
.categoryId(entity.getCategory().getId())
.build();
return partnerApiResponse;
}
@Override
public Header<List<PartnerApiResponse>> search(Pageable pageable) {
Page<Partner> entities = baseRepository.findAll(pageable);
List<PartnerApiResponse> partnerApiResponseList = entities.stream()
.map(entity -> response(entity))
.collect(Collectors.toList());
Pagination pagination = Pagination.builder()
.totalPages(entities.getTotalPages())
.totalElements(entities.getTotalElements())
.currentPage(entities.getNumber())
.currentElements(entities.getNumberOfElements())
.build();
return Header.OK(partnerApiResponseList, pagination);
}
}
|
package com.timmy.framework.vlayout;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import com.alibaba.android.vlayout.VirtualLayoutAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import java.util.HashMap;
import java.util.Hashtable;
/**
* Created by admin on 2017/10/25.
*/
public class MyVirtualLayoutAdapter extends VirtualLayoutAdapter {
public MyVirtualLayoutAdapter(@NonNull VirtualLayoutManager layoutManager) {
super(layoutManager);
HashMap hashMap = new HashMap();
Hashtable hashtable = new Hashtable();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.